在twitter的用户页面或搜索页面上观看tweets。
twittcher的Python项目详细描述
twittcher(用于twitter watcher)是一个python模块,用于生成机器人程序,这些机器人程序将监视twitter用户页面或搜索页面,并对它们找到的tweets作出反应。
它很简单,很小(目前大约150行代码),不需要在twitter或dev.twitter.com上注册,因为它不依赖于twitter api(而是解析html)。
twittcher是一个开源软件,最初由Zulko编写,在mit许可下发布。该项目位于Github上,您可以在这里报告错误、提出改进建议等。
安装
如果您有pip,请通过键入终端安装twittcher:
(sudo) pip install twittcher
否则,下载源代码(在Github或PyPI),并在与setup.py文件相同的目录中,在终端中键入此代码:
(sudo) python setup.py install
twittcher需要python包beautifulsoup(也称为bs4),安装twittcher时会自动安装该包。
使用示例
目前还没有Twittcher的文档,但是下面的示例应该向您展示开始所需的一切。
一。打印给定用户的tweets
每隔120秒,打印john d.cook的所有新推文:
from twittcher import UserWatcher UserWatcher("JohnDCook").watch_every(120)
结果:
Kicking off some simulations before I quit work for the day. #dejavu Author: JohnDCook Date: 15:43 - 24 juil. 2014 Link: https://twitter.com/JohnDCook/status/492440083073859585 “Too often we enjoy the comfort of opinion without the discomfort of thought." -- John F. Kennedy, Author: JerryWeinberg Date: 13:18 - 24 juil. 2014 Link: https://twitter.com/JerryWeinberg/status/492403371975114752
userwatcher的默认操作是打印tweets,但是您可以请求任何其他操作。 例如,下面是如何仅打印john d.cook实际编写的tweets(而不是他转发的那些tweets):
from twittcher import UserWatcher def my_action(tweet): if tweet.username == "JohnDCook": print(tweet) UserWatcher("JohnDCook", action=my_action).watch_every(120)
2.通过Twitter控制一台远程机器!
每60秒,对于我的任何新的cmd: my_command形式的tweets,在终端中运行my_command。 使用简单的tweets,我可以控制任何运行此脚本的远程计算机。
import subprocess from twittcher import UserWatcher def my_action(tweet): """ Execute the tweet's command, if any. """ if tweet.text.startswith("cmd: "): subprocess.Popen( tweet.text[5:], shell=True ) # Watch my account and react to my tweets bot = UserWatcher("Zulko___", action=my_action) bot.watch_every(60)
例如,tweetcmd: firefox将在计算机上打开firefox,tweetcmd: echo "Hello"将让计算机在终端中打印hello。
三。查看搜索结果并发送提醒邮件
每隔20秒,向我发送twitter搜索结果中所有关于巧克力牛奶的新tweets。
from twittcher import TweetSender, SearchWatcher sender = TweetSender(smtp="smtp.gmail.com", port=587, login="tintin.zulko@gmail.com", password="fibo112358", # be nice, don't try. to_addrs="tintin.zulko@gmail.com", # where to send sender_id = "chocolate milk") bot = SearchWatcher("chocolate milk", action=sender.send) bot.watch_every(20)
四。多机器人监视
如果要同时运行多个机器人,请确保在不同机器人的请求之间留出几秒钟的时间。 这里是你如何打印约翰d库克,马萨贝比,和奥拉斯的新推文。每分钟监视一个,两个机器人的请求之间间隔20秒:
import time import itertools from twittcher import UserWatcher bots = [ UserWatcher(user) for user in ["JohnDCook", "mathbabedotorg", "Maitre_Eolas"]] for bot in itertools.cycle(bots): bot.watch() time.sleep(20)
5个。保存tweets
机器人可以将已经看到的tweets保存到一个文件中,以便在以后的会话中记住不再处理这些tweets,以防它们仍然出现在关注的页面上。
from twittcher import SearchWatcher bot = SearchWatcher("chocolate milk", database="choco.db") bot.watch_every(20)