python 微信bot_使用Tweepy在Python中創建Twitter Bot

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:

該機器人旨在:

  1. Follow everyone following you.

    跟隨所有人關注您。
  2. Favorite and Retweet a Tweet based on keywords.

    根據關鍵字收藏和轉發一條推文。
  3. 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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/394476.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394476.shtml
英文地址,請注明出處:http://en.pswp.cn/news/394476.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

第五周學習進度

1.學習所花時間:單純Java是12個小時左右; 2.代碼量:大約300行; 3.博客量:1篇。 4.了解到的知識點:數據庫語言的增刪改查 5.下周計劃除了掌握課上知識外,還要再復習之前的關于Java的相關知識點。…

另一個域的cookie_一定要知道的第一方Cookie和第三方Cookie

Cookie 是您訪問過的網站創建的文件,用于存儲瀏覽信息,例如您的網站偏好設置或個人資料信息。共有兩種類型的 Cookie:第一方 Cookie 是由地址欄中列出的網站域設置的 Cookie,而第三方 Cookie 來自在網頁上嵌入廣告或圖片等項的其他…

蘋果手機怎么連接不了無線網絡連接服務器,蘋果手機連接wifi顯示無互聯網連接怎么辦?...

在開始對網絡操作以后,也可嘗試著把 iPhone 重新啟動一下,按下 iPhone 電源鍵不放,直到出現關機選項并滑動關機,最后再開機。在 iPhone 的無線局域網列表中,當前連接的這個無線網絡顯示“無互聯網連接”。此時可以通過…

中小企業大數據應用之道:思維在于借力

要想大數據落地,特別是中小企業,首先得有大數據思維,否則大數據的案例不能直接借鑒,自己摸索又怕不專業、坑太多。 何謂大數據思維,個人認為不是什么決策都參考數據,也不是什么問題都要足夠精準&#xff0c…

git學習心得之從遠程倉庫克隆

現在,遠程庫已經準備好了,下一步是用命令git clone克隆一個本地庫: $ git clone gitgithub.com:michaelliao/gitskills.git Cloning into gitskills... remote: Counting objects: 3, done. remote: Total 3 (delta 0), reused 0 (delta 0) R…

leetcode350. 兩個數組的交集 II(hashmap)

給定兩個數組&#xff0c;編寫一個函數來計算它們的交集。 將長度小的數組放入hashmap&#xff0c;記錄出現的次數&#xff0c;遍歷另一個數組&#xff0c;找出交集 class Solution {public int[] intersect(int[] nums1, int[] nums2) {ArrayList<Integer> resnew Arra…

如何使用Swift Playgrounds制作東西

by Harshita Arora通過Harshita Arora 如何使用Swift Playgrounds制作東西 (How to make something with Swift Playgrounds) Just a few days ago, I finished my WWDC 2018 scholarship submission. It was so much fun creating Alice in codeLand. This was my first year…

2018-2019 20165208 網絡對抗 Exp3 免殺原理與實踐

目錄 2018-2019 20165208 網絡對抗 Exp3 免殺原理與實踐實驗內容基礎問題回答實踐過程記錄任務一&#xff1a;正確使用免殺工具或技巧任務二&#xff1a;通過組合應用各種技術實現惡意代碼免殺任務三&#xff1a;用另一電腦實測&#xff0c;在殺軟開啟的情況下&#xff0c;可運…

k均值例子 數據挖掘_人工智能、數據挖掘、機器學習和深度學習的關系

一、人工智能人工智能是計算機科學的一個分支&#xff0c;它企圖了解智能的實質&#xff0c;并生產出一種新的能以人類智能相似的方式做出反應的智能機器。實際應用比如&#xff1a;機器視覺&#xff0c;指紋識別&#xff0c;人臉識別&#xff0c;視網膜識別&#xff0c;虹膜識…

hive中sql使用英文分號

hql只要遇見分號則認識是語句的EOF&#xff0c;所以對于分號&#xff0c;需要用“\“轉義。 例如&#xff1a; insert overwrite table test_json_map select {"accountid":"1_:\;11"}, t.map_col from t where dt 2017-08-08 limit 1; 或者用”\073&qu…

軟件系統換服務器地址,天正軟件客戶端修改服務器地址

天正軟件客戶端修改服務器地址 內容精選換一換如果IP經過NAT/WAF&#xff0c;則只能獲取到NAT/WAF轉化后的IP地址&#xff0c;無法獲取到NAT/WAF前的IP地址。如果客戶端為容器&#xff0c;只能獲取到容器所在主機的IP地址&#xff0c;無法獲取容器的IP。四層監聽器(TCP/UDP)開啟…

orcale可視化建立用戶_建立動態可視化的新方法

orcale可視化建立用戶by Sushrut Shivaswamy通過Sushrut Shivaswamy 建立動態可視化的新方法 (A new way of building dynamic visualisations) The Flux architecture gained popularity after Facebook adopted it. It’s a way of managing the state of React components …

leetcode劍指 Offer 47. 禮物的最大價值(動態規劃)

在一個 m*n 的棋盤的每一格都放有一個禮物&#xff0c;每個禮物都有一定的價值&#xff08;價值大于 0&#xff09;。你可以從棋盤的左上角開始拿格子里的禮物&#xff0c;并每次向右或者向下移動一格、直到到達棋盤的右下角。給定一個棋盤及其上面的禮物的價值&#xff0c;請計…

atoi()函數

原型&#xff1a;int atoi &#xff08;const char *nptr&#xff09; 用法&#xff1a;#include <stdlib.h> 功能&#xff1a;將字符串轉換成整型數&#xff1b;atoi()會掃描參數nptr字符串&#xff0c;跳過前面的空格字符&#xff0c;直到遇上數字或正負號才開始做…

python socket.error: [Errno 24] Too many open files

以openwrt AR9331開發板為例&#xff0c;socket連接到1019個就報錯 “python socket.error: [Errno 24] Too many open files” 1.查看開發板socket默認連接個數rootTijio:~# ulimit -m1024 2.修改socket連接個數&#xff0c;以root用戶運行以下命令rootTijio:~# ulimit -HSn 1…

選中下拉列表顯示全部數據_小白都能學會的多級下拉列表,讓你的Excel效率提升百倍...

私信回復關鍵詞【工具】&#xff0c;獲取Excel高效小工具合集&#xff01;讓你的Excel效率開掛~你有沒有遇到過這樣的場景&#xff1f;收集上來的各部門工作進度表&#xff0c;里面的答案五花八門。即使在表頭上進行提示規范&#xff0c;手動輸入也十分低效。有沒有什么辦法能夠…

你不知道的javascript(上卷)----讀書筆記

<!DOCTYPE html> <html><head><meta charset"utf-8"><title>你不知道的javascript&#xff08;上卷&#xff09;</title> </head><body><script type"text/javascript">/*//9、this 的全面解析this…

lightgbm 數據不平衡_不平衡數據下的機器學習(下)

本文從不平衡學習的基礎概念和問題定義出發&#xff0c;介紹了幾類常見的不平衡學習算法和部分研究成果。總體來說&#xff0c;不平衡學習是一個很廣闊的研究領域&#xff0c;但受筆者能力和篇幅的限制&#xff0c;本文僅對其中部分內容做了簡單概述&#xff0c;有興趣深入學習…

netty實現高性能文件服務器,通用文件服務組件(Netty實現版本)

本文所述文件服務組件在筆者此前一篇文章中已有闡述(基于netty的文件上傳下載組件)&#xff0c;不過本文將基于之前這個實現再次進行升級改造&#xff0c;利用基于注解的方式進行自動裝配。1. 簡介1.1 Netty簡介Netty是一個異步事件驅動的網絡應用程序框架&#xff0c;用于快速…

leetcode343. 整數拆分(動態規劃)

給定一個正整數 n&#xff0c;將其拆分為至少兩個正整數的和&#xff0c;并使這些整數的乘積最大化。 返回你可以獲得的最大乘積。 示例 1: 輸入: 2 輸出: 1 解釋: 2 1 1, 1 1 1。 解題思路 組成整數兩個數可以進一步拆分&#xff0c;所以可以運用到動態規劃&#xff0c…