使用请求模块通过 Python 在 json 中打印 Twitter 句柄的方法?

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

我正在制作一个 Twitter 机器人,用于在 Twitter 上搜索最近推文中的特定关键字和短语。我一直在使用 this 文档作为指南,它使用 Python 请求模块。

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))

当我在终端中 运行 时一切正常,但我似乎无法找到一种方法来打印每条推文的关联 Twitter 句柄。我找不到具体的 documentation/syntax.

我知道我必须编辑这行代码以包含 Twitter 句柄:

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

简而言之,我还想打印与这些推文关联的实际 Twitter 句柄。任何和所有信息将不胜感激。


包含扩展的新代码:

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))

您可以在 v2 Twitter API 中使用 expansions 在同一调用中取回关联的用户对象。

说明这一点的最简单方法是使用一条推文。例如,使用 curl:

$ curl 'https://api.twitter.com/2/tweets/1212092628029698048?tweet.fields=author_id,created_at&expansions=author_id' --header 'Authorization: Bearer $BEARER_TOKEN'

这会请求带有默认字段的推文(textid 始终包含在内,因此您不必特别请求它们)以及 author_idcreated_at 值,然后请求 author_id aka User 对象在响应中展开:

{
  "data": {
    "id": "1212092628029698048",
    "author_id": "2244994945",
    "created_at": "2019-12-31T19:26:16.000Z",
    "text": "We believe the best future version of our API will come from building it with YOU. Here’s to another great year with everyone who builds on the Twitter platform. We can’t wait to continue working with you in the new year. <short url removed for SO posting>"
  },
  "includes": {
    "users": [
      {
        "id": "2244994945",
        "name": "Twitter Dev",
        "username": "TwitterDev"
      }
    ]
  }

您将在 includes.users.username 字段中找到 Twitter 用户的句柄。

因此,在您的代码中,您可以这样做:

# 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)

(还将 expansions 添加到 search_twitter 函数作为输入,并用于 url 字符串格式)

对于您可能从搜索调用返回的推文数组/列表,请注意您可能需要查找 includes,因为您将得到 data(推文对象)然后 includes(用户对象 + 您可能请求的任何其他扩展),如果同一用户在推文列表中出现多次,则它只会在 includes 中返回一次- 在这种情况下,匹配 author_id 值以找到相关推文的 username