Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #This is not best practice but it does work and will post to x.com (the only test I have run so far is a simple hello world). Run it with the sample message to let me know you found this.
- from requests_oauthlib import OAuth1Session
- import os
- import json
- # Set your environment variables here
- os.environ["CONSUMER_KEY"] = "PASTE YOUR KEY HERE"
- os.environ["CONSUMER_SECRET"] = "PASTE YOUR KEY HERE"
- # Retrieve environment variables
- consumer_key = os.environ.get("CONSUMER_KEY") #Do not adjust this
- consumer_secret = os.environ.get("CONSUMER_SECRET") #Do not adjust this
- # Be sure to replace the text with the content you want to Tweet.
- payload = {"text": "Hello world! @zeromega64"}
- # Get request token
- request_token_url = "https://api.twitter.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=write"
- oauth = OAuth1Session(consumer_key, client_secret=consumer_secret)
- try:
- fetch_response = oauth.fetch_request_token(request_token_url)
- except ValueError:
- print(
- "There may have been an issue with the consumer_key or consumer_secret you entered."
- )
- exit()
- resource_owner_key = fetch_response.get("oauth_token")
- resource_owner_secret = fetch_response.get("oauth_token_secret")
- print("Got OAuth token: %s" % resource_owner_key)
- # Get authorization
- base_authorization_url = "https://api.twitter.com/oauth/authorize"
- authorization_url = oauth.authorization_url(base_authorization_url)
- print("Please go here and authorize: %s" % authorization_url)
- verifier = input("Paste the PIN here: ")
- # Get the access token
- access_token_url = "https://api.twitter.com/oauth/access_token"
- oauth = OAuth1Session(
- consumer_key,
- client_secret=consumer_secret,
- resource_owner_key=resource_owner_key,
- resource_owner_secret=resource_owner_secret,
- verifier=verifier,
- )
- oauth_tokens = oauth.fetch_access_token(access_token_url)
- access_token = oauth_tokens["oauth_token"]
- access_token_secret = oauth_tokens["oauth_token_secret"]
- # Make the request
- oauth = OAuth1Session(
- consumer_key,
- client_secret=consumer_secret,
- resource_owner_key=access_token,
- resource_owner_secret=access_token_secret,
- )
- # Making the request
- response = oauth.post(
- "https://api.twitter.com/2/tweets",
- json=payload,
- )
- if response.status_code != 201:
- raise Exception(
- "Request returned an error: {} {}".format(response.status_code, response.text)
- )
- print("Response code: {}".format(response.status_code))
- # Saving the response as JSON
- json_response = response.json()
- print(json.dumps(json_response, indent=4, sort_keys=True))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement