Files
mymach_social_nextgen/extra-addons/mymach_social_nextgen/api/x_api.py

70 lines
2.8 KiB
Python

import requests
import base64
from urllib.parse import urlencode
class XAPI:
"""Helper class for X (Twitter) OAuth 2.0 API."""
AUTH_URL = "https://twitter.com/i/oauth2/authorize"
TOKEN_URL = "https://api.twitter.com/2/oauth2/token"
def __init__(self, client_id, client_secret, redirect_uri):
self.client_id = client_id
self.client_secret = client_secret
self.redirect_uri = redirect_uri
def get_auth_url(self, state, code_challenge="challenge"):
# Note: X requires PKCE. For a complete implementation, a real code_verifier and code_challenge should be generated.
params = {
'response_type': 'code',
'client_id': self.client_id,
'redirect_uri': self.redirect_uri,
'scope': 'tweet.read tweet.write users.read offline.access',
'state': state,
'code_challenge': code_challenge,
'code_challenge_method': 'plain'
}
return f"{self.AUTH_URL}?{urlencode(params)}"
def exchange_code_for_token(self, code, code_verifier="challenge"):
data = {
'grant_type': 'authorization_code',
'client_id': self.client_id,
'redirect_uri': self.redirect_uri,
'code': code,
'code_verifier': code_verifier
}
auth_string = f"{self.client_id}:{self.client_secret}"
b64_auth = base64.b64encode(auth_string.encode('ascii')).decode('ascii')
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': f'Basic {b64_auth}'
}
response = requests.post(self.TOKEN_URL, data=data, headers=headers, timeout=10)
response.raise_for_status()
return response.json()
def upload_media(self, access_token, media_data, mime_type="image/jpeg"):
"""Upload media to X using API v1.1."""
url = "https://upload.twitter.com/1.1/media/upload.json"
headers = {'Authorization': f'Bearer {access_token}'}
files = {'media': ('media_file', media_data, mime_type)}
response = requests.post(url, headers=headers, files=files, timeout=30)
response.raise_for_status()
return response.json().get('media_id_string')
def create_tweet(self, access_token, text, media_ids=None):
"""Post a tweet using API v2."""
url = "https://api.twitter.com/2/tweets"
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
payload = {'text': text}
if media_ids:
payload['media'] = {'media_ids': media_ids}
response = requests.post(url, headers=headers, json=payload, timeout=15)
response.raise_for_status()
return response.json()