You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Tweepy中on_direct_message未触发:Python3.7私信监听失效问题

解决Tweepy中on_direct_message方法无法触发的问题

我之前也碰到过一模一样的问题,结合你的代码和描述,主要有两个核心点需要调整,就能让私信监听正常工作:

1. 重写on_data时未触发父类的事件分发逻辑

你自定义的StdOutListener重写了on_data方法,但没有调用父类StreamListeneron_data实现。而Tweepy正是通过父类的on_data来解析收到的数据流,判断内容是推文还是私信,进而触发对应的on_direct_messageon_status方法。

修改你的on_data方法,添加对父类方法的调用:

def on_data( self, status ):
    print("Entered on_data()")
    print(status, flush = True)
    # 调用父类on_data,让Tweepy处理事件分发
    return super().on_data(status)

2. 确认Stream监听的是包含私信的数据流

虽然你用了follow=[user.id_str],但要确保这个user是你的当前认证账号(也就是拥有私信权限的账号)。私信属于用户专属数据流,只有监听当前账号的相关流才能收到私信事件。

另外再做一次权限校验:

  • 确认Twitter开发者后台已经勾选了Read, write, and Direct Messages权限
  • 权限变更后,必须重新生成Access Token and Secret并替换到代码中,旧的token不会自动获取新权限

修改后的完整代码示例

from tweepy import Stream, StreamListener, OAuthHandler

# 假设你已经配置好了认证参数
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

class StdOutListener( StreamListener ):
    def __init__( self ):
        self.tweetCount = 0
    def on_connect( self ):
        print("Connection established!!")
    def on_disconnect( self, notice ):
        print("Connection lost!! : ", notice)
    def on_data( self, status ):
        print("Entered on_data()")
        print(status, flush = True)
        # 关键:调用父类方法触发事件分发
        return super().on_data(status)
    def on_direct_message( self, status ):
        print("Entered on_direct_message()")
        try:
            print(status, flush = True)
            return True
        except BaseException as e:
            print("Failed on_direct_message()", str(e))
            return True  # 返回True保持连接不中断
    def on_error( self, status ):
        print(status)
        # 遇到错误时返回True避免断开连接(可选)
        return True

# 获取当前认证账号的ID
api = tweepy.API(auth)
current_user = api.me()
twitter_stream=Stream(auth,StdOutListener())
print('Stream created...')
twitter_stream.filter(follow=[current_user.id_str], is_async=True)

这样调整后,当有私信发送到你的账号时,on_direct_message方法就会被正确触发了。

内容的提问来源于stack exchange,提问作者Saroj Satapathy

火山引擎 最新活动