Detener/Iniciar el flujo de tweets programáticamente utilizando Tweepy
Estoy intentando construir una aplicación web utilizando Django para rastrear tweets por hashtags. Estoy utilizando Tweepy AsyncStreaming y está funcionando bien. Soy nuevo en la programación asíncrona. Necesito ayuda sobre cómo detener el stream en ejecución y comenzar un nuevo stream cuando se agrega un nuevo hashtag.
Aquí está mi código:
import os
from tweepy.asynchronous import AsyncStream
import asyncio
consumer_key = os.getenv('XXXXXXXXXXX')
consumer_secret = os.getenv('XXXXXXXXXXX')
access_token = os.getenv('XXXXXXXXXXX')
access_token_secret = os.getenv('XXXXXXXXXXX')
async def main():
stream = TweetStream(consumer_key, consumer_secret,
access_token, access_token_secret)
await stream.filter(follow=['web3', 'crypto'])
class TweetStream(AsyncStream):
async def on_connect(self):
print('Stream connected')
async def on_status(self, status):
if status.in_reply_to_user_id is None and not(status.entities['user_mentions']):
print(status.text)
print(status.user.screen_name)
async def on_error(self, status):
print(status)
if __name__ == '__main__':
asyncio.run(main())
davy.ai
Para detener el flujo actual y comenzar un nuevo flujo cuando se agregue un nuevo hashtag, puedes modificar el código de la siguiente manera:
Modifica el método
main()
para que tome un parámetro de hashtag y lo almacene en la variable global.Modifica la clase
TweetStream
para que utilice la variable global para filtrar los tweets.Crea un nuevo bucle para ejecutar el flujo y utiliza
asyncio.gather
para ejecutar el bucle y el método principal de forma concurrente.Aquí está el código modificado:
Para iniciar un nuevo flujo, simplemente llama al método
main()
con un nuevo hashtag. El flujo actual se detendrá automáticamente y se iniciará un nuevo flujo con el nuevo hashtag.Por ejemplo: