如何开发可识别指定关键词并回复对应推荐内容的Twitter机器人?
Twitter机器人关键词响应问题修复方案
我正在开发一款Twitter机器人,希望实现:
- 用户发送关键词「romantic movie」时,机器人回复「In the mood for love」
- 用户发送关键词「Scifi movie」时,机器人回复「interstellar」
但当前代码无法实现预期功能,以下是我用的代码:
import tweepy import time CONSUMER_KEY = 'xxxxxxxxxxxx' CONSUMER_SECRET = 'xxxxxxxxxxxxxxxx' ACCESS_TOKEN = 'xxxxxxxxxxxxxxxxxxxxxxxxxx' ACCESS_TOKEN_SECRET = 'xxxxxxxxxxxxxxxxxxx' public_tweets = api.mentions_timeline() while True: for tweet in public_tweets: print(tweet.text) if tweet.text.lower() in ('Romantic movie'): api.update_status(status='@' + tweet.user.screen_name + ' I recommend the movie "Midnight in Paris"!',in_reply_to_status_id=tweet.id) elif tweet.text.lower()in ('Romantic Manga'): api.update_status(status='@' + tweet.user.screen_name + ' I recommend the Manga "Bakuman"!',in_reply_to_status_id=tweet.id) api.update_status(status='@' + tweet.user.screen_name + ' Thanks for tweeting about recommendations!', in_reply_to_status_id=tweet.id) time.sleep(5)
问题出在这几个地方:
- 未初始化API对象:代码直接调用
api但没创建Tweepy的API实例,会直接报错 - 关键词匹配逻辑错误:
tweet.text.lower() in ('Romantic movie')写法完全错误,应该检查目标关键词是否包含在推文文本里,还要统一用小写比对避免大小写问题;而且原代码的关键词和需求不符 - 回复逻辑混乱:不管有没有匹配到关键词,都会执行最后的感谢回复,导致一条推文可能收到两条回复
- 推文只获取一次:
public_tweets = api.mentions_timeline()放在循环外,只会在程序启动时获取一次提及,后续不会更新最新推文 - 无去重机制:会重复回复同一条推文
修复后的代码:
import tweepy import time # 配置密钥 CONSUMER_KEY = 'xxxxxxxxxxxx' CONSUMER_SECRET = 'xxxxxxxxxxxxxxxx' ACCESS_TOKEN = 'xxxxxxxxxxxxxxxxxxxxxxxxxx' ACCESS_TOKEN_SECRET = 'xxxxxxxxxxxxxxxxxxx' # 初始化API,开启请求限制等待 auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) api = tweepy.API(auth, wait_on_rate_limit=True) # 记录已回复的推文ID,避免重复操作 replied_tweets = set() while True: # 每次循环重新获取最新的10条提及推文 public_tweets = api.mentions_timeline(count=10) for tweet in public_tweets: # 跳过已回复过的推文 if tweet.id in replied_tweets: continue print(f"收到推文:{tweet.text}") tweet_text_lower = tweet.text.lower() reply_prefix = f"@{tweet.user.screen_name} " # 匹配目标关键词并回复 if 'romantic movie' in tweet_text_lower: api.update_status(status=reply_prefix + 'In the mood for love', in_reply_to_status_id=tweet.id) print("已回复romantic movie关键词") elif 'scifi movie' in tweet_text_lower: api.update_status(status=reply_prefix + 'interstellar', in_reply_to_status_id=tweet.id) print("已回复scifi movie关键词") else: # 无匹配关键词时发送感谢 api.update_status(status=reply_prefix + 'Thanks for tweeting about recommendations!', in_reply_to_status_id=tweet.id) print("未匹配到关键词,发送感谢回复") # 标记该推文已回复 replied_tweets.add(tweet.id) time.sleep(5) # 循环间隔,避免频繁请求接口 time.sleep(60)
关键修改说明:
- 补全了Tweepy API的初始化流程,确保能正常调用Twitter接口
- 用集合
replied_tweets记录已回复推文ID,彻底避免重复回复 - 调整关键词匹配逻辑为「检查推文文本是否包含目标关键词」,并统一小写比对
- 将感谢回复移到
else分支,只有无匹配时才发送 - 把推文获取逻辑放到循环内部,每次循环都能拉取最新提及
- 开启
wait_on_rate_limit=True,自动处理Twitter的接口请求限制
内容的提问来源于stack exchange,提问作者Ricardo Rosario
相关产品推荐
相关产品推荐

