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.mzph.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…