skip to Main Content

I am trying to filter out tweets that include a specific hashtag, which works great, I can even display the text. But additionally, I want to print the user_screenname or author name. But it seems like my class can only display the text of the tweet and every other value is None or 0.

class MyStream(tweepy.StreamingClient):


# This function gets called when the stream is working
def on_connect(self):

    print("Connected")


# This function gets called when a tweet passes the stream
def on_tweet(self, tweet):

    # Displaying tweet in console
    if tweet.referenced_tweets == None:
        
        #-------------Doesnt Work----------------------------    
        #print(tweet.created_at)

        print(tweet.text)
        
        #-----------Doesnt Work---------------------------
        #print(tweet.author_id)
        #client.like(tweet.id)
      
        #Doesnt work
        #client.get_user(username=tweet.user_screenname)

      
        #---------Store in CSV------------
        #data.append([tweet.created_at, tweet.user.screen_name, tweet.text])
        #df = pd.DataFrame(data, columns=columns)
       # df.to_csv('StreamTweets.csv')

        # Delay between tweets
        time.sleep(0.1)

How can I display the name of the author of the tweet?
tweet.created_at, author_id, tweet.id all return none but tweet.text works fine.
Using Twitter API v2 and Tweepy.

Thanks guys!

2

Answers


  1. 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) # this will have the author_id
           return
    
    stream = MyStream(bearer_token=bearer_token)
    stream.filter(tweet_fields=['author_id])
    

    In the tweet.data you will now have the author_id and can just use the client.get_user(id=author_id) to get the rest of the user information.

    Login or Signup to reply.
  2. When you create your filter, you need to add the "author_id" expansion, which will then give you access to tweet.author_id:

    class MyStream(tweepy.StreamingClient):
        
        def on_tweet(self, tweet):
            author_id = tweet.author_id
            print(author_id)
    
    stream = MyStream(bearer_token=bearer_token)
    stream.filter(expansions=["author_id"])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search