Skip to content

Instantly share code, notes, and snippets.

@designervoid
Last active April 22, 2023 14:46
Show Gist options
  • Save designervoid/d984c646f8245a3c59413e8060f474b6 to your computer and use it in GitHub Desktop.
Save designervoid/d984c646f8245a3c59413e8060f474b6 to your computer and use it in GitHub Desktop.
Twitter API
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())
@designervoid
Copy link
Author

designervoid commented Apr 21, 2023

now insert the generated token into, for example, this package

import { TwitterApi } from 'twitter-api-v2';

const asyncRun = async () => {
    const twitterPersonClient = new TwitterApi('generated_bearer_v2');
    const readOnlyClient = twitterPersonClient.readOnly;
    const user = await readOnlyClient.v2.me();

    console.log(user);
}

@designervoid
Copy link
Author

designervoid commented Apr 21, 2023

@designervoid
Copy link
Author

designervoid commented Apr 22, 2023

import requests
from requests_oauthlib import OAuth1

# Your app's credentials
CONSUMER_KEY = "top_secret" # change this
CONSUMER_SECRET = "top_secret" # change this
ACCESS_TOKEN = "top_secret" # change this
ACCESS_TOKEN_SECRET = "top_secret" # change this

# OAuth1 authentication
auth = OAuth1(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
likes_url = "https://api.twitter.com/1.1/favorites/list.json?id={}"

# Fetch user likes for a specific user id
user_id = input("Enter your user id which u get throw the OAuth2.0 Auth: ")
likes_response = requests.get(likes_url.format(user_id), auth=auth)
if likes_response.status_code == 200:
    likes_tweets = likes_response.json()
    print("\Tweet likes:")
    for tweet in likes_tweets:
        print(tweet)
else:
    print(f"Failed to fetch user likes: {likes_response.status_code}")

# API endpoint URL
retweets_url = "https://api.twitter.com/1.1/statuses/retweets/{}.json?count={}"

# Fetch retweets
tweet_id = "1648624097960640514"  # replace with the ID of the tweet you want to fetch retweets for
count = 100  # replace with the maximum number of retweets you want to fetch
retweets_response = requests.get(retweets_url.format(tweet_id, count), auth=auth)
if retweets_response.status_code == 200:
    retweets = retweets_response.json()
    print("Retweets:")
    for retweet in retweets:
        print(retweet)
else:
    print(f"Failed to fetch retweets: {retweets_response.status_code}")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment