跳转到主要内容

用于Twitter机器人的Python工具

项目描述

twitter bot utils

Twitter bot utils使设置Twitter机器人变得更容易,着眼于使配置和命令行选项易于管理和复制。它们旨在管理一台机器上的小型到中型Twitter账户群组。该包是出色的Tweepy库的超简单包装。它还提供了使用argparse设置命令行工具的快捷方式。

此包旨在协助创建用于艺术或个人项目的机器人。不要用它来垃圾邮件或骚扰人们。

与python >= 3.6兼容。

使用pip install twitter_bot_utils安装。

Hello World部分查看基本运行过程。

认证

设置机器人时遇到的一个难题是获取正确的认证密钥。登录和退出Twitter的应用程序网站可能会有些麻烦。Twitter bot utils附带tbu auth,这是一个用于此的命令行辅助工具

$ tbu auth --consumer-key 1233... --consumer-secret 345...

这会提示您一个URL。在您的机器人登录的浏览器中打开此URL,点击“授权”。Twitter将显示授权码,在命令行中输入此代码,然后奇迹般地!您的密钥将显示出来。

tbu auth受到了Twitter官方命令行工具twurl一个功能灵感的启发。

配置文件

Twitter Bot Utils的一个目标是通过一个简单的配置文件存储认证数据来创建Tweepy实例。这为bot制作者提供了一个简单、可重用的存储密钥的位置,避免了源代码控制。

默认情况下,Twitter Bot Utils会在当前目录、您的家目录(~/)或~/bots目录中查找名为bots.yaml(或.yml)的文件。也可以设置自定义配置位置。

以下是如何布局bots配置文件的两种方式。基本方式只涵盖一个用户和一个应用

token: ...
secret: ...
consumer_key: ...
consumer_secret: ...
my_setting: "bots are good"

如果您有多个bot,一个简单的设置是为每个bot使用一个应用。访问apps.twitter.com,注册应用,然后在“keys and tokens”标签中选择“创建我的访问令牌”。

general_setting: "all bots share this setting"

users:
    # twitter screen_name
    MyBotName:
        token: ...
        secret: ...
        consumer_key: ...
        consumer_secret: ...
        custom_setting: "bots are great"

    other_bot:
        ...

如果您有多个bot共享一个应用,在配置文件中创建一个apps部分

apps:
    my_app_name:
        consumer_key: ...
        consumer_secret: ...
users:
    MyBotName:
        token: ...
        secret: ...
        app: my_app_name

twitter-auth实用程序将愉快地从这种设置的bots.yaml文件中读取设置

twitter-auth -c ~/bots.yaml --app my_app_name

使用配置文件与Twitter通信

使用默认位置之一的配置文件不需要任何额外设置

import twitter_bot_utils as tbu

# Automatically check for a config file in the above-named directories
twitter = tbu.API(screen_name='MyBotName')

twitter对象是一个完全认证的tweepy API对象。因此,您现在可以这样做

twitter.update_status(status='hello world')

bots配置文件也适用于存储其他API的密钥和参数,或您自己的bot。

# Get a config settings from your bots config file. This might be the key for a third-party API
# Use a general setting
twitter.config['general_setting']
# "all bots share this setting"

# Settings from the user and app section are also available:
twitter.config['custom_setting']
# "bots are great"

twitter.config['app_setting']
# "apple juice"

使用config_file参数设置自定义配置文件

# Specify a specific config file
twitter = tbu.API(screen_name='MyBotName', config_file='path/to/config.yaml')

Twitter Bot Utils附带了一些内置的命令行解析器,API对象也会愉快地消耗argparse.parser.parse_args()的结果(详见下文)。

无需用户认证

某些Twitter API查询不需要用户认证。要设置不带用户认证的Tweepy API实例,设置一个像上面那样的bots.yaml文件,但省略users部分。使用app关键字参数

twitter = tbu.API(app='my_app_name', config_file='path/to/config.yaml')

twitter.search(q="Twitter searches don't require user authentication")

最新推文

twitter_bot_utils.API对象通过一些对bot有用的方法扩展了tweepy.API

  • 检查最新推文ID的方法:last_tweetlast_replylast_retweet。如果您想避免重复摄入相同的内容,那么这些方法很有用。
twitter = tbu.API(screen_name='MyBotName')

twitter.last_tweet
# id of most recent tweet from MyBotName

twitter.last_reply
# id of most recent reply from MyBotName

twitter.last_retweet
# id of most recent retweet from MyBotName

# Example: what's happened since the last time the bot was active?
twitter.search('#botALLY', since_id=twitter.last_tweet)

当Twitter容量不足时,Twitter Bot Utils会在update_status中添加重试。如果update_status从Twitter收到503错误,它将等待10秒并再次尝试。

默认命令行选项

将bot打包为命令行应用很有用,这样就可以通过cron轻松运行。Twitter Bot Utils包含一些与argparse一起工作的辅助程序。

默认情况下有一些有用的命令行标志

  • -u, --user:运行的屏幕名
  • -n, --dry-run:不推文,只输出到stdout
  • -v, --verbose:记录到stdout
  • -q, --quiet:仅记录错误
  • -c, --config:配置文件路径。这是一个根据上述格式排列的JSON或YAML文件。如果配置文件在默认位置之一,则不需要此选项。

假设这是mybot.py

import argparse
import twitter_bot_utils as tbu

# This sets up an argparse.ArgumentParser with the default arguments
parent = tbu.args.parent()
parser = argparse.ArgumentParser('My Example Bot', parents=[parent])
parser.add_argument('--my-arg', type=str, help='A custom argument')

args = parser.parse_args()

# Set up the tweepy API
# Note that you can pass the argparse.Namespace object
twitter = tbu.API(args)

# Generate a tweet somehow
tweet = my_tweet_function(args.my_arg)

# The API includes an instance of logging
# debug logs will output to stdout only if --verbose is set
# info logs will output even without --verbose
api.logger.debug("Generated %s", tweet)

# Use args.dry_run to control tweeting
if not args.dry_run:
    twitter.update_status(tweet)

然后在命令行上

> python mybot.py --help
usage: mybot.py [options]

My Example Bot

optional arguments:
  -h, --help            show this help message and exit
  -c PATH, --config PATH
                        bots config file (json or yaml)
  -u SCREEN_NAME, --user SCREEN_NAME
                        Twitter screen name
  -n, --dry-run         Don't actually do anything
  -v, --verbose         Run talkatively
  -q, --quiet           Run quietly
  --my-arg MY_ARG       A custom argument

# Looks for settings in a config file (e.g. bots.yaml, see config section above)
# Prints results to stdout and doesn't publish anything 
> python yourapp.py  --dry-run --verbose
Generated <EXAMPLE TWEET>

# Run quietly, say in a crontab file
> python yourapp.py --user MyBotName --quiet
Generated <EXAMPLE TWEET 2>

辅助程序

检查实体

轻松检查推文是否包含特定实体

import twitter_bot_utils

# Don't set include_entities to False and expect the below to work
statuses = twitter.search('example search', include_entities=True)

status = status[0]

twitter_bot_utils.helpers.has_mention(status)
# returns True if status has one or more mentions, otherwise False 

twitter_bot_utils.helpers.has_hashtag(status)
# returns True if status has one or more hashtags, otherwise False 

twitter_bot_utils.helpers.has_media(status)
# returns True if status has one or more media entities (images, video), otherwise False 

twitter_bot_utils.helpers.has_entities(status)
# returns True if status has any entities

# These also exist:
twitter_bot_utils.helpers.has_url
twitter_bot_utils.helpers.has_symbol

过滤实体

这些辅助程序从推文的文本中删除实体。

import twitter_bot_utils as tbu

api = tbu.API(screen_name='MyBotName')

results = api.search("special topic")

results[0].text
# 'This is an example tweet with a #hashtag and a link http://foo.com'

tbu.helpers.remove_entity(results[0], 'hashtags')
# 'This is an example tweet with a  and a link http://foo.com'

tbu.helpers.remove_entity(results[0], 'urls')
# 'This is an example tweet with a #hashtag and a link '

# Remove multiple entities with remove_entities.
tbu.helpers.remove_entities(results[0], ['urls', 'hashtags', 'media'])
# 'This is an example tweet with a  and a link '

命令行工具

Twitter Bot Utils包含一个带有几个有用子命令的命令行工具

  • tbu auth:使用Twitter应用进行认证和账户
  • tbu follow:关注关注您的bot的账户
  • tbu like:喜欢(也称为收藏)您的bot的提及
  • tbu post:发布文本和图像的基本命令行

项目详情


下载文件

下载适合您平台文件。如果您不确定选择哪个,请了解有关安装包的更多信息。

源代码分发

twitter_bot_utils-0.14.0.tar.gz (48.8 kB 查看哈希)

上传时间

构建分发

twitter_bot_utils-0.14.0-py2.py3-none-any.whl (30.7 kB 查看哈希)

上传时间 Python 2 Python 3

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面