python - 如何通过 Python 使用 requests 模块以 json 格式打印 Twitter 句柄?

标签 python json api twitter python-requests

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

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 句柄的方法。我找不到具体的文档/语法。

我知道我必须编辑这行代码以包含 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))

最佳答案

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

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

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

这会请求一 strip 有默认字段(textid 始终包含在内,因此您不必专门请求它们)以及 author_id 的推文created_at 值,然后请求在响应中扩展 author_id 又名 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,因为您将获得数据 (推文对象),然后 includes (用户对象 + 您可能请求的任何其他扩展),如果同一个用户在推文列表中出现多次,则只会返回一次在 includes 中 - 在本例中,匹配 author_id 值以查找关联推文的用户名

关于python - 如何通过 Python 使用 requests 模块以 json 格式打印 Twitter 句柄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66529553/

相关文章:

REST 风格的 API : How to organize nested resources

c++ - c++最值得 "standard"的数据库库是什么?

python - 加载自定义 gstreamer 插件会引发 gst.ElementNotFoundError

python - celery worker 错误 : ImportError no module named celery

python - 拆分列表中的每个项目

python - 仅检测一类物体的神经网络

java - 从 XAgent 创建 Json

ios - TableView 重新加载过早

使用 https url 的 Javascript JSON 解析

javascript - 如何通过添加 for 循环来遍历 data.games 来重写搜索函数,并在搜索时添加它显示的分数?