【问题标题】:How to create a twitter bot that replies back as soon as another person tweets?如何创建一个推特机器人,一旦另一个人发推文就会回复?
【发布时间】:2022-03-30 11:38:13
【问题描述】:

昨天我用 Python 写了一个推特机器人,它从唐纳德特朗普那里获取最新的推文,在谷歌翻译中翻译了 45 次,并将最终的英文翻译回推给他。一切正常,除了我现在需要在代码开头添加某种“监听器”以自动检测他何时发推文,以便其余代码可以发挥其魔力。我已经在互联网上浏览了一段时间,但似乎找不到任何类型的事件处理程序可以让脚本检测他何时发推文。所以这就是我来找你们的原因。有没有办法使用 Tweepy 或其他 Python 库来主动检测某人何时发推文?我将包含我的代码,这样你们就可以在他发推文时确切地看到我想要发生的事情。它已注释,因此希望它不会太复杂而难以理解。谢谢!


import tweepy
from googletrans import Translator

#Keys for accessing the Twitter API

consumer_key = 'PLACEHOLDER'
consumer_secret = 'PLACEHOLDER'
access_token = 'PLACEHOLDER'
access_token_secret = 'PLACEHOLDER'

#Setting up authentification

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

#Scrapes my timeline for DT's latest tweet. I want this to be done AUTOMATICALLY when he tweets.

tweet = api.user_timeline(screen_name = 'realDonaldTrump', count = 1, include_rts = False, tweet_mode = 'extended')

#Translates the text from the .json file that is pulle from the previous line using the Google translate library.

for status in tweet:
    translator = Translator()
    translation = translator.translate(translation.text, 'mn')
    translation = translator.translate(status._json["full_text"], 'ja')

#There are more translations in the actual code, but to reduce the length and complexity, I've taken those out. They don't matter to the specific question.   

#Include his handle in a message so that the tweet is tweeted back at him once the translation is complete.

message = ('@realDonaldTrump', translation.text)

#Tweets the message back at him under that specific tweet using it's ID.

send = api.update_status(message, status._json["id"])

我只希望代码能够实时抓取 DT 的一条推文的时间线。谢谢!

【问题讨论】:

  • 1.检查他最近的推文 2. 将日期与上次检查中的推文日期进行比较 3. 如果日期更大,则不执行任何操作 4. 安排此运行每 X 秒/分钟/天
  • 这将违反 Twitter 的自动化规则,因此对于自动和未经请求的回复或提及 help.twitter.com/en/rules-and-policies/twitter-automation 可能会很快受到写入限制
  • 自从 Twitter 更新了它的自动化规则,你将无法在大规模层面上做到这一点。然而,每小时 1 或 2 条推文可能会起作用,但可能仅限于执行写入操作。

标签: python twitter anaconda bots tweepy


【解决方案1】:

要自动化您的脚本,您可能需要将其推送到生产服务器中,然后创建一个 cron 作业,该作业将在给定的定期间隔运行脚本。为了在本地运行它,我使用 1. NGROK - 将您的本地主机地址和端口暴露给外界,即它为您提供了一种从互联网访问本地主机的方法,以及 2. Invictify - 这允许您按计划运行脚本.此外,脚本需要触发 Web 服务。使用 Flask 或 FastAPI 创建在触发时调用脚本的端点。

【讨论】:

    猜你喜欢
    • 2021-07-14
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 2013-04-04
    • 2020-09-26
    • 2017-12-05
    • 2017-05-15
    • 2018-01-23
    相关资源
    最近更新 更多