Created
July 23, 2024 08:22
-
-
Save intrd/bd446c27b5d23877d5d6212fa9957d91 to your computer and use it in GitHub Desktop.
Python3 OAuth 2.0 PKCE with Tweepy: Upload and Tweet an Image using Twitter API v1 w/ X API v2.
This file contains hidden or 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
## Python3 OAuth 2.0 PKCE with Tweepy: Upload and Tweet an Image using Twitter API v1 w/ X API v2. | |
# This script uploads an image using the old Twitter API v1, retrieves the media URL, and then tweets it using the new X API v2. (Yes, currently, this is the easiest way to accomplish this). | |
# Author: [email protected] | |
import tweepy, sys | |
if len(sys.argv) < 3: | |
print("Usage: python3 script.py <file_path> <long_text>") | |
sys.exit(1) | |
file_path = sys.argv[2] | |
long_text = sys.argv[1] | |
print(f"File path: {file_path}") | |
print(f"Long text: {long_text}") | |
api_key = "YOURAPIKEY" | |
api_secret = "YOURAPISECRET" | |
access_token = "xxxxxx-YOURACCTOKEN" | |
access_token_secret = "ACCTOKENSECRET" | |
def get_twitter_conn_v1(api_key, api_secret, access_token, access_token_secret) -> tweepy.API: | |
auth = tweepy.OAuth1UserHandler(api_key, api_secret) | |
auth.set_access_token( | |
access_token, | |
access_token_secret, | |
) | |
return tweepy.API(auth) | |
def get_twitter_conn_v2(api_key, api_secret, access_token, access_token_secret) -> tweepy.Client: | |
client = tweepy.Client( | |
consumer_key=api_key, | |
consumer_secret=api_secret, | |
access_token=access_token, | |
access_token_secret=access_token_secret, | |
) | |
return client | |
client_v1 = get_twitter_conn_v1(api_key, api_secret, access_token, access_token_secret) | |
client_v2 = get_twitter_conn_v2(api_key, api_secret, access_token, access_token_secret) | |
media_path = file_path | |
media = client_v1.media_upload(filename=media_path) | |
media_id = media.media_id | |
client_v2.create_tweet(text=long_text, media_ids=[media_id]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment