joe blow
joe blow

Reputation: 1

How can i get a notification when someone tweets using tweepy and python

I want to get a notifaction when someone tweets

I have here this code

import tweepy

# API keys and tokens
API_KEY = ''
API_SECRET = ''
ACCESS_TOKEN = ''
ACCESS_TOKEN_SECRET = ''
BEARER_TOKEN = ''



# Step 1: Authenticate using OAuth 1.0a for other API calls (if needed)
auth = tweepy.OAuth1UserHandler(API_KEY, API_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(auth)

# Step 2: Define the StreamingClient class
class MyStream(tweepy.StreamingClient):
    def on_tweet(self, tweet):
        print(f"New tweet: {tweet.text}")

    def on_error(self, status_code):
        print(f"Error: {status_code}")
        return True  # To keep the stream running

# Initialize the StreamingClient with the Bearer Token
stream = MyStream(bearer_token=BEARER_TOKEN)

# Clear any existing rules (optional)
rules = stream.get_rules()
if rules.data:
    rule_ids = [rule.id for rule in rules.data]
    stream.delete_rules(rule_ids)

# Get the user ID for the user you want to follow (using OAuth 1.0a)
username = "elonmusk"  # Replace with the actual username
user = api.get_user(username=username)
user_id = user.data.id  # Use the retrieved user ID

# Add a rule to track tweets from the specified user
stream.add_rules(tweepy.StreamRule(f"from:{user_id}"))

# Start streaming
stream.filter(expansions="author_id")`

this code gives me this error, but my credentials are correct

tweepy.errors.Forbidden: 403 Forbidden When authenticating requests to the Twitter API v2 endpoints, you must use keys and tokens from a Twitter developer App that is attached to a Project. You can create a project via the developer portal.

I try to authenticate and get a notification as soon someone tweets

Upvotes: 0

Views: 62

Answers (0)

Related Questions