简体   繁体   中英

How to stream tweets using twitter API V2?

I am trying to stream tweets using twitter API V.2. But the online tutorial that I am following uses API v1. I looked at the documentation, I understand that I should use (tweepy.StreamingClient) now instead? But I cannot find any examples on how to stream tweets. How can I convert the code below so that it works for API v2?


import tweepy

# API KEYS
bearer_token = ""
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''

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

# not working 
class Listener(tweepy.Stream):
  
    def on_status(self, status):
        print(status)
        return True


twitter_stream = Listener(
    consumer_key, consumer_secret,
    access_token, access_token_secret
)

twitter_stream.filter(track=['#Bitcoin'])

Edit: my attempt to solve

class MyStream(tweepy.StreamingClient):
    # This function gets called when the stream is working
    def on_connect(self):
        print("Connected")

    def on_tweet(self, tweet):
       print(tweet.data) 
       return


stream = MyStream(bearer_token=bearer_token)
stream.filter(track=['#Bitcoin'])

In the new StreamingClient some of the old options for stream.filter() have been removed. (track, follow, etc)

Instead you have to use the new StreamingClient.add_rules() and use tweepy.StreamRule("text rule here")


How to use rules is documented here. For instance "hello" would search for tweets matching hello, "hello OR #greeting" would match a tweet with hello or the #greeting https://developer.twitter.com/en/docs/twitter-api/tweets/filtered-stream/integrate/build-a-rule

I'd recommend taking a look at the Operators table in that article


class MyStream(tweepy.StreamingClient):
    # This function gets called when the stream is working
    def on_connect(self):
        print("Connected")

    def on_tweet(self, tweet):
       print(tweet.data) 
       return


stream = MyStream(bearer_token=bearer_token)
stream.add_rules(tweepy.StreamRule("#Bitcoin")) #adding the rules
stream.filter() #runs the stream

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM