You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Tweepy实现Twitter提及回复流?解决Bot自回复异常

问题分析与修复方案

核心问题

你的机器人出现自回复循环,主要源于两个关键错误:

  1. 流规则未过滤自身推文:当前规则会捕获所有触发匹配条件的内容,包括机器人自己发出的回复,导致循环触发。
  2. exclude_reply_user_ids参数使用错误:你传入的是字符串占位符"bot_id",但该参数要求传入数字用户ID的列表,且仅靠这个参数无法阻止流捕获自身推文。

具体修复步骤

1. 修正exclude_reply_user_ids参数

将占位符替换为机器人账号的真实数字ID,以列表形式传入:

# 替换为你的机器人真实数字ID,例如123456789
BOT_USER_ID = 123456789

client.create_tweet(
    text=random_phrase(),
    in_reply_to_tweet_id=tweet.id,
    exclude_reply_user_ids=[BOT_USER_ID]
)

2. 在流处理中跳过自身推文

在on_tweet方法里先判断推文作者是否为机器人自己,是则直接跳过:

class Tweetmentions(tweepy.StreamingClient):
    def on_tweet(self, tweet):
        # 过滤机器人自身发送的推文
        if tweet.author_id == BOT_USER_ID:
            return
        print(tweet.text)
        client.create_tweet(
            text=random_phrase(),
            in_reply_to_tweet_id=tweet.id,
            exclude_reply_user_ids=[BOT_USER_ID]
        )
        print('Successfully tweeted!')

3. 优化流规则(推荐)

直接在流规则层面排除机器人自身的推文,减少不必要的请求:

# 替换为你的机器人账号用户名,规则含义:监听@机器人的推文,但排除机器人自己发的内容
stream_mentions.add_rules(tweepy.StreamRule("@你的机器人账号 -from:你的机器人账号"))

4. 启用用户认证

调用filter方法时添加user_auth=True,确保能正确获取推文的作者ID信息:

stream_mentions.filter(user_auth=True)

完整修正代码示例

import tweepy
import random

# 替换为你的真实凭证
bearer_token = "你的bearer token"
consumer_key = "你的consumer key"
consumer_secret = "你的consumer secret"
access_token = "你的access token"
access_token_secret = "你的access token secret"
# 替换为机器人真实数字ID
BOT_USER_ID = 123456789

def random_phrase():
    phrases = ["你好呀!", "感谢提及~", "很高兴收到你的消息!"]
    return random.choice(phrases)

client = tweepy.Client(
    bearer_token=bearer_token,
    consumer_key=consumer_key,
    consumer_secret=consumer_secret,
    access_token=access_token,
    access_token_secret=access_token_secret
)

class Tweetmentions(tweepy.StreamingClient):
    def on_tweet(self, tweet):
        if tweet.author_id == BOT_USER_ID:
            return
        print(tweet.text)
        client.create_tweet(
            text=random_phrase(),
            in_reply_to_tweet_id=tweet.id,
            exclude_reply_user_ids=[BOT_USER_ID]
        )
        print('Successfully tweeted!')

stream_mentions = Tweetmentions(bearer_token=bearer_token)
stream_mentions.add_rules(tweepy.StreamRule("@你的机器人账号 -from:你的机器人账号"))
stream_mentions.filter(user_auth=True)

内容的提问来源于stack exchange,提问作者Paulo Caldeira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 23:30:57