Last active
April 22, 2023 14:46
-
-
Save designervoid/d984c646f8245a3c59413e8060f474b6 to your computer and use it in GitHub Desktop.
Twitter API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import base64 | |
import secrets | |
import hashlib | |
# App's credentials | |
CLIENT_ID = "top_id" # change this | |
CLIENT_SECRET = "top_secret" # change this | |
REDIRECT_URI = "https://ton-design-system-next-typescript.vercel.app/" # change this | |
# Generate a random code verifier and challenge | |
CODE_VERIFIER = secrets.token_urlsafe(32) | |
CODE_CHALLENGE = hashlib.sha256(CODE_VERIFIER.encode()).hexdigest() | |
# Step 1: Construct the authorize URL | |
AUTHORIZE_URL = f"https://twitter.com/i/oauth2/authorize?response_type=code&client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&scope=tweet.read%20users.read%20follows.read%20follows.write&state=state&code_challenge={CODE_CHALLENGE}&code_challenge_method=plain" | |
# Step 2: Redirect the user to the authorize URL | |
print(f"Please visit the following URL to authorize the app:\n{AUTHORIZE_URL}") | |
auth_code = input("Enter the authorization code: ") | |
# Step 3: Exchange authorization code for access token | |
token_url = "https://api.twitter.com/2/oauth2/token" | |
headers = { | |
"Content-Type": "application/x-www-form-urlencoded", | |
"Authorization": f"Basic {base64.b64encode(f'{CLIENT_ID}:{CLIENT_SECRET}'.encode()).decode()}" | |
} | |
data = { | |
"grant_type": "authorization_code", | |
"code": auth_code, | |
"redirect_uri": REDIRECT_URI, | |
"code_verifier": CODE_CHALLENGE | |
} | |
try: | |
response = requests.post(token_url, headers=headers, data=data) | |
response.raise_for_status() | |
access_token = response.json()["access_token"] | |
print(access_token) | |
except requests.exceptions.HTTPError as error: | |
print(error) | |
print(response.json()) |
Author
designervoid
commented
Apr 22, 2023
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment