'Twitter APIv2 Expansions Using Tweepy
I have a pretty basic application which uses Tweepy's StreamingClient to stream tweets from a defined list of users. When one of them tweets, I have a couple conditions based on keywords to determine if I should alert myself. I want it to send me both the text of the tweet and the username of who sent it. I can do the former, but can figure out how to get the username.
From what I have seen I need to use expansions, but I'm a complete novice and don't know how I would integrate that into my code because the majority of the documentation for expansions is on the twitter API and I'm not sure how to apply that to my python code which uses tweepy.
Stripped down version of my code, currently just handling the tweet text is as follows ( I want to print user name in addition to tweet.text):
import tweepy
import json
import re
import logging
class MyListener(tweepy.StreamingClient):
def on_tweet(self, tweet):
keyword = ["xxxx", "yyyy","zzzz"]
key_patterns = [r'\b%s\b' % re.escape(s.strip()) for s in keyword]
key_there = re.compile('|'.join(key_patterns))
if key_there.search(tweet.text):
print(tweet.text)
else:
print("No Match")
def on_error(self, status):
print(status)
return True
twitter_stream = MyListener("token")
twitter_stream.get_rules()
twitter_stream.filter()
Solution 1:[1]
tweet objects has a user atribute, and the user attribute has a screen_name attribute, this is the username.
You can get it this way:
class MyListener(tweepy.StreamingClient):
def on_tweet(self, tweet):
keyword = ["xxxx", "yyyy","zzzz"]
key_patterns = [r'\b%s\b' % re.escape(s.strip()) for s in keyword]
key_there = re.compile('|'.join(key_patterns))
if key_there.search(tweet.text):
print(tweet.text)
print(tweet.user.screen_name)
else:
print("No Match")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Joshua Okonkwo |
