流使用Tweepy AsyncStream异步推送

2024-10-01 04:49:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试运行AsyncStream Tweepy,但遇到了一个问题

我的代码

from __future__ import absolute_import, print_function
from tweepy.streaming import Stream
from tweepy import OAuthHandler
from tweepy import Stream
from pprint import pprint
from tweepy.asynchronous import AsyncStream 
import asyncio

async def main():

    stream = StdOutListener(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
    await stream.filter(follow=['1082189695252074496'])
    await asyncio.sleep(1.5)


class StdOutListener(AsyncStream):
    
    
    async def on_status(self, status):
        print(status_json)

    async def on_error(self, status):
        print(status)
            
if __name__ == '__main__':
    asyncio.run(main())

当我在.py文件中运行它时,它不工作,并返回错误“流中发生了HTTP:420错误”。 我也在Jupyter Notebook中运行代码,只是没有使用async io.run(main()),而是编写wait main(),它也会返回此错误,但流可以工作,并且返回响应

为什么它在Jupyter笔记本中工作,而在.py文件中不工作。如何解决这个问题


Tags: 代码fromimportasynciostreamasyncmaindef
1条回答
网友
1楼 · 发布于 2024-10-01 04:49:25

根据Tweepy关于Handling Errors的文档部分:

If clients exceed a limited number of attempts to connect to the streaming API in a window of time, they will receive error 420. The amount of time a client has to wait after receiving error 420 will increase exponentially each time they make a failed attempt.

Tweepy’s Stream Listener passes error codes to an on_error stub. The default implementation returns False for all codes, but we can override it to allow Tweepy to reconnect for some or all codes...

这里还有一个关于HTTP Error Codes的Twitter API文档部分的参考

  1. 第一个问题是print(status_json)应该是print(status._json)

  2. 第二个问题是on_status方法需要基于status._json有条件地返回True或False,如下所示:

    async def on_status(self, status):
        if hasattr(status, "_json"):
            print(status._json)
            # returning non-False continues the stream
            return True
        else:
            # returning False disconnects the stream
            return False
    
  3. 第三个问题是on_error方法需要根据status的值有条件地返回True或False,如下所示:

    async def on_error(self, status):
        if status == 420:
            # returning False disconnects the stream
            return False
        else:
            # returning non-False continues the stream
            return True
    

相关问题 更多 >