python 微信bot
by Lucas Kohorst
盧卡斯·科斯特(Lucas Kohorst)
使用Tweepy在Python中創建Twitter Bot (Create a Twitter Bot in Python Using Tweepy)
With about 15% of Twitter being composed of bots, I wanted to try my hand at it. I googled how to create a Twitter bot and was brought to a cleanly laid out web app. It allowed you to create a bot that would like, follow, or retweet a tweet based on a keyword. The problem was that you could only create one bot for one function.
Twitter約有15%由機器人組成,我想嘗試一下。 我用谷歌搜索了如何創建Twitter機器人,并帶到一個布局簡潔的Web應用程序中。 它使您可以創建一個機器人,該機器人根據關鍵字對某條推文進行關注,關注或轉發。 問題是您只能為一個功能創建一個機器人。
So I decided to code a bot myself with Python and the Tweepy library.
因此,我決定自己使用Python和Tweepy庫編寫一個機器人程序。
建立 (Setup)
First, I downloaded Tweepy. You can do this using the pip package manager.
首先,我下載了Tweepy。 您可以使用pip包管理器執行此操作。
pip install tweepy
You can also clone the GitHub repository if you do not have pip installed.
如果沒有安裝pip,也可以克隆GitHub存儲庫。
git clone https://github.com/tweepy/tweepy.gitcd tweepypython setup.py install
You’ll need to import Tweepy and Tkinter (for the GUI interface).
您需要導入Tweepy和Tkinter(用于GUI界面)。
import tweepyimport Tkinter
證書 (Credentials)
Next, we need to link our Twitter account to our Python script. Go to apps.twitter.com and sign in with your account. Create a Twitter application and generate a Consumer Key, Consumer Secret, Access Token, and Access Token Secret. Now you are ready to begin!
接下來,我們需要將Twitter帳戶鏈接到我們的Python腳本。 轉到apps.twitter.com并使用您的帳戶登錄。 創建一個Twitter應用程序并生成使用者密鑰,使用者密鑰,訪問令牌和訪問令牌密鑰。 現在您可以開始了!
Under your import statements store your credentials within variables and then use the second block of code to authenticate your account with tweepy.
在導入語句下,將憑據存儲在變量中,然后使用第二段代碼對tweepy進行身份驗證。
consumer_key = 'consumer key'consumer_secret = 'consumer secrets'access_token = 'access token'access_token_secret = 'access token secret'
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth)
In order to check if your program is working you could add:
為了檢查程序是否正常運行,您可以添加:
user = api.me()print (user.name)
This should return the name of your Twitter account in the console.
這應該在控制臺中返回您的Twitter帳戶的名稱。
建立機器人 (Building the Bot)
This bot is meant to:
該機器人旨在:
- Follow everyone following you. 跟隨所有人關注您。
- Favorite and Retweet a Tweet based on keywords. 根據關鍵字收藏和轉發一條推文。
- Reply to a user based on a keyword. 根據關鍵字回復用戶。
Step one is the easiest, you simply loop through your followers and then follow each one.
第一步是通過你的追隨者最簡單的,你只需循環 ,然后按照各一個。
for follower in tweepy.Cursor(api.followers).items(): follower.follow() print ("Followed everyone that is following " + user.name)
At this point in order to make sure your code is working you should log onto Twitter and watch as the people you’re following increase.
在這一點上,為了確保您的代碼正常工作,您應該登錄Twitter并關注您所關注的人的增加。
From this point onwards, besides setting up and packing the labels in the GUI, I am coding everything under the function mainFunction()
.
從現在開始,除了在GUI中設置和打包標簽外,我還在編寫所有代碼 在函數mainFunction()
。
def mainFunction(): #The code
You might be able to see where this is going. In order to favorite or retweet a tweet we can use a for loop and a try statement like this:
您也許能夠看到前進的方向。 為了收藏或轉發推文,我們可以使用for循環和如下try語句:
search = "Keyword"
numberOfTweets = "Number of tweets you wish to interact with"
for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets): try: tweet.retweet() print('Retweeted the tweet')
except tweepy.TweepError as e: print(e.reason)
except StopIteration: break
In order to favorite a tweet you can simply replace the
為了收藏一條推文,您只需替換
tweet.retweet()
with
與
tweet.favorite()
In order to reply to a user based on a keyword, we need to store the users username and twitter ID.
為了基于關鍵字回復用戶,我們需要存儲用戶的用戶名和Twitter ID。
tweetId = tweet.user.idusername = tweet.user.screen_name
We can then loop through the tweets and update our status (tweet) at each user.
然后,我們可以遍歷這些推文并更新每個用戶的狀態(推文)。
phrase = "What you would like your response tweet to say"
for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets): try: tweetId = tweet.user.id username = tweet.user.screen_name api.update_status("@" + username + " " + phrase, in_reply_to_status_id = tweetId) print ("Replied with " + phrase) except tweepy.TweepError as e: print(e.reason)
except StopIteration: break
If you want to only utilize the script through the terminal and update the code every time you wish to run it then you have completed your bot.
如果您只想通過終端使用腳本并在每次希望運行該腳本時都更新代碼,那么您已經完成了機器人程序。
創建GUI (Creating the GUI)
We can create a GUI application that will take our inputs of the keyword you would like to search for and whether or not you would like to favorite a tweet.
我們可以創建一個GUI應用程序,該應用程序將接受您想要搜索的關鍵字以及您是否喜歡收藏推文的輸入。
We first need to initialize Tkinter and setup the layout.
我們首先需要初始化Tkinter并設置布局。
To create our user interface, we are going to have seven labels for search, number of tweets, and reply. Plus the questions do you want to reply, favorite, retweet the tweet, and follow the user.
要創建我們的用戶界面,我們將有七個標簽用于搜索,推文數量和回復。 加上您要回答的問題,收藏,轉發推文并關注用戶。
Remember the code below is outside and above our mainFunction()
.
請記住,下面的代碼在mainFunction()
外部和上方 。
root = Tk()
label1 = Label( root, text="Search")E1 = Entry(root, bd =5)
label2 = Label( root, text="Number of Tweets")E2 = Entry(root, bd =5)
label3 = Label( root, text="Response")E3 = Entry(root, bd =5)
label4 = Label( root, text="Reply?")E4 = Entry(root, bd =5)
label5 = Label( root, text="Retweet?")E5 = Entry(root, bd =5)
label6 = Label( root, text="Favorite?")E6 = Entry(root, bd =5)
label7 = Label( root, text="Follow?")E7 = Entry(root, bd =5)
We also need to pack each label so that they show up and then call the root function in a loop so that it remains on the screen and doesn’t immediately close.
我們還需要打包每個標簽,以便它們顯示出來,然后循環調用root函數,以便它保留在屏幕上并且不會立即關閉。
The following is what packing the first label looks like. I packed all of the labels below the mainFunction()
.
以下是包裝第一個標簽的樣子。 我將所有標簽打包在mainFunction()
下面。
label1.pack()E1.pack()
root.mainloop()
If you only ran your GUI code, it should look something like this:
如果僅運行GUI代碼,則它應如下所示:
However, inputing text into the labels or clicking the submit button will do nothing at this point. As the interface is not yet connected to the code.
但是,此時在標簽中輸入文本或單擊“提交”按鈕將無濟于事。 由于接口尚未連接到代碼。
In order to store the user input in the labels, we need to use the .get()
function. I used individual functions for each label.
為了將用戶輸入存儲在標簽中,我們需要使用.get()
函數。 我為每個標簽使用了單獨的功能。
def getE1(): return E1.get()
Then in my mainFunction()
, I called the function getE1()
and stored the input into a variable. For E1 it looks like this:
然后在我的mainFunction()
,調用函數getE1()
并將輸入存儲到變量中。 對于E1,它看起來像這樣:
getE1()search = getE1()
You must do this for every label. For the numberOfTweets
label make sure to convert the input into an integer.
您必須對每個標簽都執行此操作。 對于numberOfTweets
標簽,請確保將輸入轉換為整數。
getE2()numberOfTweets = getE2()numberOfTweets = int(numberOfTweets)
For the last four labels (Reply, Favorite, Retweet and Follow), we need to check to see if the input from the user is “yes” or “no” in order to run that given function or not. This can be accomplished through if statements.
對于最后四個標簽(“答復”,“收藏夾”,“轉發”和“關注”),我們需要檢查用戶輸入的內容是“是”還是“否”,以便運行該給定功能。 這可以通過if語句來完成。
This would be the code for the reply function:
這將是回復功能的代碼:
if reply == "yes":
for tweet in tweepy.Cursor(api.search, search).items(numberOfTweets): try: tweetId = tweet.user.id username = tweet.user.screen_name api.update_status("@" + username + " " + phrase, in_reply_to_status_id = tweetId) print ("Replied with " + phrase) except tweepy.TweepError as e: print(e.reason)
except StopIteration: break
For the favorite, retweet and follow functions simply replace the reply with “retweet”, “favorite” and “follow”. Then copy and paste the code you wrote above for each one underneath the if statement.
對于收藏夾,轉發和關注功能,只需將回復替換為“轉發”,“收藏夾”和“關注”即可。 然后將上面編寫的代碼復制并粘貼到if語句下的每個代碼。
Now we just need to add the submit button and tell it to call the mainFunction()
and execute the code for our Twitter Bot. Again, don’t forget to pack it!
現在,我們只需要添加提交按鈕,并告訴它調用mainFunction()
并為我們的Twitter Bot執行代碼。 同樣,不要忘記打包!
submit = Button(root, text ="Submit", command = mainFunction)
That’s it! After you run your bot script, a GUI application should run and you will be able to reply, retweet, favorite and follow users.
而已! 運行bot腳本后,將運行GUI應用程序,您將能夠回復,轉發,收藏和關注用戶。
With this Twitter Bot, I have created the account FreeWtr which advocates for use of filtered tap water over bottled water. Here is a screenshot of the profile.
通過這個Twitter Bot,我創建了一個FreeWtr帳戶,該帳戶提倡使用過濾的自來水而不是瓶裝水。 這是個人資料的屏幕截圖。
Here is the full source code on Github.
這是Github上的完整源代碼 。
翻譯自: https://www.freecodecamp.org/news/creating-a-twitter-bot-in-python-with-tweepy-ac524157a607/
python 微信bot