Hi I am looking for some help with my code below. I am using Twitter API v2 and the added a rule for a filter in my StreamingClient. However the filter is not working as I am seeing all kinds of tweets coming through.
My goal is to use the StreamingClient API to find any tweets that contain certain text (that is listed in my StreamRule - I am using apple as an example). Can anyone tell me what is wrong with my code below?
import tweepy
client = tweepy.Client(BEARER_TOKEN)
class IDPrinter(tweepy.StreamingClient):
def on_tweet(self, tweet):
status_var = "\"" + tweet.text + "\""
print(tweet.text)
def on_errors(self, errors):
print(f"Received error code {errors}")
self.disconnect()
return False
printer = IDPrinter(BEARER_TOKEN)
printer.add_rules(tweepy.StreamRule("apple lang:en"))
printer.filter()
Thanks
Are you sure you don’t have any other existing rules?
Hi @Harmon758 , thanks for your quick reply. That is basically my whole code.
Is there any way for me to check if there are any other rules on that streaming endpoint? I dont see anything appearing on my web interface on the developer account under my project. Can you kindly guide me please? I am stuck on this for 2+ days now.
You can use StreamingClient.get_rules to check what rules you have in place.
Rules persist on Twitter’s end unless you delete them, so if you’ve previously added rules without doing so, they’re still there and you’re probably receiving Tweets that match them.
2 Likes
Thank you so much that did the trick. I was not able to view what rules were already in place. So using the get_rules() method, i found out there were 5 rules present. Then I deleted them and added my new rule. That worked. Thank you.
1 Like
reign
#6
Hi! I am facing this issue with the Twitter API v2 with StreamingClient. I amfairly new at this, would it be possible for you to share your codes?
How do i use the get_rules() method? Also, how do you delete them and add new rules?
@reign You could try something like this:
...
for rule in result.data:
print(f"rule marked to delete: {rule.id} - {rule.value}")
rule_ids.append(rule.id)
if(len(rule_ids) > 0):
printer.delete_rules(rule_ids)
printer = TweetPrinterV2(bearer_token)
else:
print("no rules to delete")
...
Example copied from “Python Friday #117: Streaming Search Results With Tweepy” (you can find it on google) - twitter doesn’t allow to post links for some reasons.