How to disconnect the stream (Tweepy)?

Viewed 123

I'm trying to update the stream every 15 minutes to change its rules. As far as I understand it is impossible to update the filter rules in real time. So I try to stop the stream and then start it again.

    class MyStream(tweepy.StreamingClient):    
       def disconnect(self):
    
                self.running=False
    
                print('stop stream)
    
    stream = MyStream(bearer_token=bearer_token, wait_on_rate_limit=True)

stream.disconnect()

But it doesn't work. Streaming continues to work. Can you please tell me how to reallocate what I have in mind?

update

I try to add a rule to the stream, then wait 10 seconds and add another one. But it doesn't work. Can you please tell me what the problem is and how to fix it?

    import telebot
    import tweepy
    import time
    bot = telebot.TeleBot()
    api_key = 
    api_key_secret = 
    bearer_token = 
    access_token = 
    access_token_secret = 
    client = tweepy.Client(bearer_token, api_key, api_key_secret, access_token, access_token_secret)
    auth = tweepy.OAuth1UserHandler(api_key, api_key_secret, access_token, access_token_secret)
    api = tweepy.API(auth)
    
    
    class MyStream(tweepy.StreamingClient):
        def on_connect(self):
            print('Connected')
    
        def on_response(self, response):
            print(response)
            
    
    stream = MyStream(bearer_token=bearer_token, wait_on_rate_limit=True)
    
    rules = ['book', 'tree', 'word']
    
    #create the stream
    for rule in rules:
        stream.add_rules(tweepy.StreamRule(rule))
        print('Showing the rule')
        print(stream.get_rules().data)
        stream.filter(tweet_fields=["referenced_tweets"])
        # this part of the code no longer works.
        print('sleep 10 sec')
        time.sleep(10)
    # this part not working too
    print('Final Streaming Rules:')
    print(stream.get_rules().data)
1 Answers

In Twitter API v2 (Tweepy using the tweepy.client interface and StreamingClient object) the stream does not need to disconnect in order to update the rules, you do that by adding rules via StreamingClient.add_rules(). Docs:

StreamingClient.add_rules() can be used to add rules before using StreamingClient.filter() to connect to and run a filtered stream:

streaming_client.add_rules(tweepy.StreamRule("Tweepy"))

streaming_client.filter() StreamingClient.get_rules() can be used to retrieve existing rules and StreamingClient.delete_rules() can be used to delete rules.

Related