#!/usr/bin/env python # From: https://github.com/twitterdev/Twitter-API-v2-sample-code/blob/main/Manage-Tweets/delete_tweet.py from requests_oauthlib import OAuth1Session import os import json # In your terminal please set your environment variables by running the following lines of code. # export 'API_KEY'='' # export 'API_SECRET_KEY'='' consumer_key = os.environ.get("API_KEY") consumer_secret = os.environ.get("API_SECRET_KEY") # Be sure to replace tweet-id-to-delete with the id of the Tweet you wish to delete. The authenticated user must own the list in order to delete id = "1547963178700533760" # 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." ) 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.delete("https://api.twitter.com/2/tweets/{}".format(id)) if response.status_code != 200: 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_response)