# 推特监控 **Published by:** [DrewL](https://paragraph.com/@dreworld/) **Published on:** 2022-03-05 **URL:** https://paragraph.com/@dreworld/JHXMNksecWuD477EPTHq ## Content 非教程,纯记录,准备慢慢打造成好用的工具。 最近很多项目都搞关门,烦得很。写一个监控程序,在指定推特发文的时候进行提醒。大概逻辑是指定一个间隔时间,每隔N分钟查询一次指定的推特在上一个N分钟内有没有发文。 使用比较成熟的tweepy模块,需要先去developer.twitter.com注册自己的应用,并生成Bearer Token。网上的中文教程都是用的v1的接口,现在貌似只支持v2了。 https://developer.twitter.com/en 首先是认证模块,注册自己的client。 import tweepy client = tweepy.Client("Bearer Token") 然后设定一下监控的时间间隔,这里设置为3分钟查询一次。 interval = 3 tweepy的api需要使用推特ID作为参数进行查询,只知道用户名的话,可以通过get_user接口获取对应ID。 client.get_user(“Drew20135733”) 获得的结果是这样的. Response(data=<User id=1172784929941229568 name=dreworld.eth( 👻, 👻) username=Drew20135733>, includes={}, errors=[], meta={}) 把Userid拿出来留着用。 然后就是监控的逻辑。 无限循环,设置获取时间为当前时间的3分钟前到现在所发的推特。 while True: s = "" st = datetime.datetime.utcnow()-datetime.timedelta(minutes=interval) st = st.strftime("%Y-%m-%dT%H:%M:%SZ") tweets = client.get_users_tweets("1172784929941229568", start_time=st) 判断是否有获取到推文,有的话,就把推文打印出来。 if (tweets[0] is not None and len(tweets[0]) > 0): for i in range(len(tweets[0])): s += '{}\r\n'.format(tweets[0][i].text) print(s) 最后暂停3分钟后再运行。 time.sleep(180) 要监控多个项目的话,只需要加一个字典,写入用户的用户名和ID对。 userid ={ "xxx":"xxx", "Drew":"1172784929941229568" } 然后在循环的时候遍历一下,这个后面再写。 后面再加上监测到以后发邮件提醒的环节,以及正则捕获discord邀请码和图片ocr识别的逻辑。 看了下好像完全没什么技术含量,ORZ,今天先这样了。 ## Publication Information - [DrewL](https://paragraph.com/@dreworld/): Publication homepage - [All Posts](https://paragraph.com/@dreworld/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@dreworld): Subscribe to updates - [Twitter](https://twitter.com/Drew20135733): Follow on Twitter