Skip to content

Instantly share code, notes, and snippets.

@chrisalbon
Last active July 5, 2023 00:23
Show Gist options
  • Save chrisalbon/79e4a6f2a9868d7d41eb02ef3cd10967 to your computer and use it in GitHub Desktop.
Save chrisalbon/79e4a6f2a9868d7d41eb02ef3cd10967 to your computer and use it in GitHub Desktop.
Three Legged Auth To Tweet Something
import tweepy
from dotenv import load_dotenv
import os
# Constants
load_dotenv()
#Secrets
CONSUMER_KEY = os.getenv("CONSUMER_KEY")
CONSUMER_SECRET = os.getenv("CONSUMER_SECRET")
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
ACCESS_TOKEN_SECRET = os.getenv("ACCESS_TOKEN_SECRET")
# Create an OAuthHandler instance
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
if ACCESS_TOKEN and ACCESS_TOKEN_SECRET:
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
else:
# Redirect user to Twitter to authorize
redirect_user_url = auth.get_authorization_url()
print(f"Please authorize the app at this url: {redirect_user_url}")
# After the user authorizes, they will be redirected
# back to your app with a verifier in the URL query string
verifier = input('Please input the verifier: ')
# You can now use that verifier to obtain an access token
auth.get_access_token(verifier)
# At this point, auth.access_token and auth.access_token_secret
# can be saved for future use (so that you don't need to go through
# the 3-legged OAuth process every time the user runs your app)
ACCESS_TOKEN = auth.access_token
ACCESS_TOKEN_SECRET = auth.access_token_secret
# Save these in your environment or some other secure place
# Now you can use the API as the authenticated user
api = tweepy.API(auth)
# Post a tweet
status = "Hello, world! This is my second automated tweet via Tweepy!"
api.update_status(status=status)
print("Tweet successfully posted!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment