twitter机器人的python实用程序

twitter_bot_utils的Python项目详细描述


twitter bot实用程序使设置twitter bot变得更容易一些, 着眼于使配置和命令行选项易于管理和 复制。他们打算管理一个中小型的小圈子 一台机器上的twitter帐户。这个包裹非常简单 优秀的Tweepy库的包装。它 还提供设置命令行工具的快捷方式 argparse

此软件包旨在帮助创建 艺术或个人项目。不要用它来垃圾邮件或骚扰别人。

适用于Python2.7、3.4和3.5(2.6&3.3也可能适用)。

使用pip install twitter_bot_utils安装。

请参见Hello World中的基本贯穿 剖面图 documentation

认证

设置机器人程序的一个障碍是获得正确的身份验证 钥匙。登录和退出Twitter的应用程序站点可能会有点痛苦。 twitter bot实用程序附带tbu auth,这是 这个:

$ twitter-auth --consumer-key 1233... --consumer-key 345...

这将提示你一个网址。在浏览器中打开这个 登录后,单击“授权”。Twitter将向您显示授权 代码,在命令行中输入,然后开始!你的钥匙是 显示。

tbu auth的灵感来自 `twurl<;https://github.com/twitter/twurl>;`,Twitter已经成熟 命令行工具。

配置文件

twitter bot实用程序的一个目标是创建 身份验证数据存储在一个简单的配置文件中。这给了肉瓶制造商 一个简单的、可重用的地方,用于在源代码管理之外存储密钥。

默认情况下,twitter bot实用程序查找名为bots.yamlbots.json在当前目录中,您的主目录(~/)或 ~/bots目录。也可以设置自定义配置位置。

这是两种布局bots配置文件的方法。基本方法包括 只有一个用户和一个应用程序:

token:LONGSTRINGOFLETTERS-ANDNUMBERSsecret:LETTERSANDNUMBERSconsumer_key:LOL123...consumer_secret:OMG456...my_setting:"botsaregood"

如果您有多个机器人或应用程序,请使用多机器人布局:

general_setting:"allbotssharethissetting"users:# twitter screen_nameMyBotName:token:LONGSTRINGOFLETTERS-ANDNUMBERSsecret:LETTERSANDNUMBERS# The app key should match a key in apps belowapp:my_app_namecustom_setting:"botsaregreat"other_bot:...apps:my_app_name:app_setting:"applejuice"consumer_key:...consumer_secret:...

twitter-auth实用程序将很高兴地从 bots.yaml文件:

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

使用配置文件与Twitter交谈

在一个默认位置使用配置文件不需要任何 额外设置:

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

twitter对象是经过完全身份验证的Tweepy API对象。所以 现在您可以这样做:

twitter.update_status(status='hello world')

botsconfig文件对于存储密钥和参数也很有用 对于其他api,或者对于您自己的bot。

# Get a config settings from your bots config file. This might be the key for a third-party API# Use a general settingtwitter.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实用程序带有一些内置的命令行解析器,并且 api对象也会很高兴地使用 argparse.parser.parse_args()(详见下文)。

无需用户认证

一些twitter api查询不需要用户身份验证。建立 Tweepy API实例未经用户身份验证,请设置bots.yaml文件 如上所述,但省略users部分。使用app keyword参数:

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对象使用一些 对机器人程序有用的方法:

  • 检查最近的tweets的id的方法:last_tweetlast_replylast_retweet。如果你的机器人 搜索twitter并希望避免摄入相同的内容。
twitter=tbu.API(screen_name='MyBotName')twitter.last_tweet# id of most recent tweet from MyBotNametwitter.last_reply# id of most recent reply from MyBotNametwitter.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是 容量过大。如果update_status从twitter得到一个503错误,那么 将等待10秒,然后重试。

默认命令行选项

将机器人程序打包为命令行应用程序很有用,这样它们就可以 使用cron轻松运行。twitter bot实用程序包括 使用argparse

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

  • -u,--user:要运行的屏幕名称
  • -n,--dry-run:不要发tweet,只输出到stdout
  • -v,--verbose:登录到stdout
  • -q,--quiet:仅记录错误
  • -c,--config:配置文件的路径。这是一个json或yaml文件 按上述格式布置。如果 配置文件位于默认位置之一。

假设这是mybot.py

importargparseimporttwitter_bot_utilsastbu# This sets up an argparse.ArgumentParser with the default argumentsparent=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 objecttwitter=tbu.API(args)# Generate a tweet somehowtweet=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 --verboseapi.logger.debug("Generated %s",tweet)# Use args.dry_run to control tweetingifnotargs.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>

助手

检查实体

轻松检查推文是否具有特定实体:

importtwitter_bot_utils# Don't set include_entities to False and expect the below to workstatuses=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 Falsetwitter_bot_utils.helpers.has_hashtag(status)# returns True if status has one or more hashtags, otherwise Falsetwitter_bot_utils.helpers.has_media(status)# returns True if status has one or more media entities (images, video), otherwise Falsetwitter_bot_utils.helpers.has_entities(status)# returns True if status has any entities# These also exist:twitter_bot_utils.helpers.has_urltwitter_bot_utils.helpers.has_symbol

过滤出实体

这些助手从tweet文本中移除实体。

importtwitter_bot_utilsastbuapi=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实用程序包括一个命令行工具,其中包含一些有用的 子命令:

  • tbu auth:通过twitter应用程序进行身份验证并注册。
  • tbu follow:跟踪跟踪您的机器人的帐户
  • tbu like:就像(又称最爱)你的机器人提到的
  • tbu post:用于发布文本和图像的基本命令行

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java有没有工具可以将zephyr转换为velocity模板?   java在安卓 studio中从JSON响应中获取值   jvm如何在Java中设计一个好的permgen空间字符串?   java如何防止Rest webservice使用被盗令牌进行身份验证   java无法遍历列表JSTL   找不到用于ResourceServerTokenServices的java Bean SpringSecurityOauth2   java子字符串替换问题   爪哇玻璃鱼3。十、 以编程方式处理任意HTTPSession的终止   java如何检查输入是否为整数,并在最后添加一个命令来重新启动while循环?   引发java ical4j 1.0.6不可解析日期异常   Java等价于Delphi的DBCtrlGrid?   如果发生错误,java将查找下一个预期标记ANTLR 3   java自打开应用程序(创建锁屏)   java为什么netty有自己的ConcurrentHashMap?   Gradle任务中的java拉取和运行依赖项   继承与Java继承的混淆   java使用shell脚本中的版本执行jar   java我无法让Sqlite数据库与带有Maven的JavaFX应用程序IDE Eclipse包正确通信   java控制台日志未通过org打印。阿帕奇。hadoop。mapreduce。作业的waitForCompletion(true)方法   JAVAlang.NoSuchMethodError:apachestorm螺栓中的spring getrequest