|
| 1 | +import requests |
| 2 | +import os |
| 3 | +import json |
| 4 | + |
| 5 | +# To set your enviornment variables in your terminal run the following line: |
| 6 | +# export 'BEARER_TOKEN'='<your_bearer_token>' |
| 7 | +bearer_token = os.environ.get("BEARER_TOKEN") |
| 8 | + |
| 9 | + |
| 10 | +def create_url(): |
| 11 | + # Tweet fields are adjustable. |
| 12 | + # Options include: |
| 13 | + # attachments, author_id, context_annotations, |
| 14 | + # conversation_id, created_at, entities, geo, id, |
| 15 | + # in_reply_to_user_id, lang, non_public_metrics, organic_metrics, |
| 16 | + # possibly_sensitive, promoted_metrics, public_metrics, referenced_tweets, |
| 17 | + # source, text, and withheld |
| 18 | + tweet_fields = "tweet.fields=lang,author_id" |
| 19 | + # Be sure to replace list-id with any List ID |
| 20 | + id = "list-id" |
| 21 | + url = "https://api.twitter.com/2/lists/{}/tweets".format(id) |
| 22 | + return url, tweet_fields |
| 23 | + |
| 24 | + |
| 25 | +def bearer_oauth(r): |
| 26 | + """ |
| 27 | + Method required by bearer token authentication. |
| 28 | + """ |
| 29 | + |
| 30 | + r.headers["Authorization"] = f"Bearer {bearer_token}" |
| 31 | + r.headers["User-Agent"] = "v2ListTweetsLookupPython" |
| 32 | + return r |
| 33 | + |
| 34 | + |
| 35 | +def connect_to_endpoint(url, tweet_fields): |
| 36 | + response = requests.request( |
| 37 | + "GET", url, auth=bearer_oauth, params=tweet_fields) |
| 38 | + print(response.status_code) |
| 39 | + if response.status_code != 200: |
| 40 | + raise Exception( |
| 41 | + "Request returned an error: {} {}".format( |
| 42 | + response.status_code, response.text |
| 43 | + ) |
| 44 | + ) |
| 45 | + return response.json() |
| 46 | + |
| 47 | + |
| 48 | +def main(): |
| 49 | + url, tweet_fields = create_url() |
| 50 | + json_response = connect_to_endpoint(url, tweet_fields) |
| 51 | + print(json.dumps(json_response, indent=4, sort_keys=True)) |
| 52 | + |
| 53 | + |
| 54 | +if __name__ == "__main__": |
| 55 | + main() |
0 commit comments