Twitter 允许一个人 分享 与世界有关的博客文章和文章。 使用 Python 和 tweepy 库可以很容易地创建一个 Twitter 机器人来为你处理所有的推文。 本文将向您展示如何构建这样的机器人。 希望您可以将这里的概念应用到其他使用在线服务的项目中。
入门
要创建 Twitter 机器人 呸呸呸 图书馆派上用场。 它管理 Twitter API 调用并提供一个简单的接口。
以下命令使用 Pipenv 将 tweepy 安装到虚拟环境中。 如果您没有安装 Pipenv,请查看我们之前的文章,如何安装 Pipenv Fedora.
$ mkdir twitterbot $ cd twitterbot $ pipenv --three $ pipenv install tweepy $ pipenv shell
Tweepy – 入门
要使用 Twitter API,机器人需要针对 Twitter 进行身份验证。 为此,tweepy 使用 OAuth 身份验证标准。 您可以通过在以下位置创建新应用程序来获取凭据 https://apps.twitter.com/.
创建一个新的 Twitter 应用程序
填写以下表格并单击创建您的 Twitter 应用程序按钮后,您可以访问应用程序凭据。 Tweepy 需要消费者密钥 (API Key) 和消费者秘密 (API Secret),两者都可从密钥和访问令牌中获得。
向下滚动页面后,使用 Create my access token 按钮生成 Access Token 和 Access Token Secret。
使用 Tweepy – 打印您的时间线
现在您拥有所需的所有凭据,打开一个新文件并编写以下 Python 代码。
import tweepy auth = tweepy.OAuthHandler("your_consumer_key", "your_consumer_key_secret") auth.set_access_token("your_access_token", "your_access_token_secret") api = tweepy.API(auth) public_tweets = api.home_timeline() for tweet in public_tweets: print(tweet.text)
确保您使用的是 Pipenv 虚拟环境后,运行您的程序。
$ python tweet.py
上面的程序调用 home_timeline API 方法从你的时间线上检索 20 条最近的推文。 既然机器人能够使用 tweepy 从 Twitter 获取数据,请尝试更改代码以发送推文。
使用 Tweepy – 发送推文
要发送推文,API 方法 update_status 会派上用场。 用法很简单:
api.update_status("The awesome text you would like to tweet")
tweepy 库还有许多其他对 Twitter 机器人有用的方法。 有关 API 的完整详细信息,请查看 文件.
杂志机器人
让我们创建一个搜索 Fedora 杂志推文并自动转发它们。
为避免多次转发同一条推文,机器人会存储最后一次转发的推文 ID。 两个帮助函数 store_last_id 和 get_last_id 将用于保存和检索此 ID。
然后机器人使用 tweepy 搜索 API 来查找 Fedora 比存储的 ID 更新的杂志推文。
import tweepy def store_last_id(tweet_id): """ Store a tweet id in a file """ with open("lastid", "w") as fp: fp.write(str(tweet_id)) def get_last_id(): """ Read the last retweeted id from a file """ with open("lastid", "r") as fp: return fp.read() if __name__ == '__main__': auth = tweepy.OAuthHandler("your_consumer_key", "your_consumer_key_secret") auth.set_access_token("your_access_token", "your_access_token_secret") api = tweepy.API(auth) try: last_id = get_last_id() except FileNotFoundError: print("No retweet yet") last_id = None for tweet in tweepy.Cursor(api.search, q="fedoramagazine.org", since_id=last_id).items(): if tweet.user.name == 'Fedora Project': store_last_id(tweet.id) tweet.retweet() print(f'"{tweet.text}" was retweeted'
为了只转发来自 Fedora 杂志,该机器人搜索包含 fedoramagazine.org 并由“Fedora 项目”推特账号。
结论
在本文中,您了解了如何使用 tweepy Python 库创建 Twitter 应用程序来自动阅读、发送和搜索推文。 您现在可以利用您的创造力来创建自己的 Twitter 机器人。
本文示例的源代码可在 Github.