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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值