Monday 15 March 2021

Way to print Twitter handle in json via Python with requests module?

I'm making a Twitter bot to search Twitter for specific keywords and phrases from recent Tweets. I've been using this document as a guide, which uses the Python requests module.

import requests
import json

BEARER_TOKEN = "XYZ"

#define search twitter function
def search_twitter(query, tweet_fields, bearer_token = BEARER_TOKEN):
    headers = {"Authorization": "Bearer {}".format(bearer_token)}

    url = "https://api.twitter.com/2/tweets/search/recent?query={}&{}".format(
        query, tweet_fields
    )
    response = requests.request("GET", url, headers=headers)

    print(response.status_code)

    if response.status_code != 200:
        raise Exception(response.status_code, response.text)
    return response.json()

#search term
query = "new music"
#twitter fields to be returned by api call
tweet_fields = "tweet.fields=text,author_id,created_at"

#twitter api call
json_response = search_twitter(query=query, tweet_fields=tweet_fields, bearer_token=BEARER_TOKEN)
#pretty printing
print(json.dumps(json_response, indent=4, sort_keys=True))

Everything works fine when I run it in the terminal, but I can't seem to find a way to print each Tweet's associated Twitter handle. I can't find the specific documentation/syntax.

I know I have to edit this line of code to include the Twitter handle:

tweet_fields = "tweet.fields=text,author_id,created_at"

Simply put, I also want to print the actual Twitter handle associated with these Tweets. Any and all information would be deeply appreciated.


New code including expansions:

import requests
import json
#its bad practice to place your bearer token directly into the script (this is just done for illustration purposes)
BEARER_TOKEN = "XYZ"
#define search twitter function
def search_twitter(query, tweet_fields, expansions, bearer_token = BEARER_TOKEN):
    headers = {"Authorization": "Bearer {}".format(bearer_token)}

    url = "https://api.twitter.com/2/tweets/search/recent?query={}&{}".format(
        query, tweet_fields, expansions
    )
    response = requests.request("GET", url, headers=headers)

    print(response.status_code)

    if response.status_code != 200:
        raise Exception(response.status_code, response.text)
    return response.json()

#search term
query = "new music"
#twitter fields to be returned by api call
# twitter fields to be returned by api call
tweet_fields = "tweet.fields=author_id,created_at"
expansions = "expansions=author_id"

# twitter api call
json_response = search_twitter(query=query, tweet_fields=tweet_fields, expansions=expansions, bearer_token=BEARER_TOKEN)
#pretty printing
print(json.dumps(json_response, indent=4, sort_keys=True))


from Way to print Twitter handle in json via Python with requests module?

No comments:

Post a Comment