Twitter用户对象Python请求

2 投票
1 回答
52 浏览
提问于 2025-04-14 17:15

我有一个基本的付费Twitter计划。我正在尝试用以下代码获取用户信息:

import requests
import json
import config

bearer_token = config.bearer_token
url = "https://api.twitter.com/2/users"

params = {'ids': '[4919451, 14151086]',
          'user.fields':'name,description,location,public_metrics,username,created_at,'
               }


def bearer_oauth(r):
    """
    Method required by bearer token authentication.
    """

    r.headers["Authorization"] = f"Bearer {bearer_token}"
    r.headers["User-Agent"] = "v2UserLookupPython"
    return r


def connect_to_endpoint(url,params):
    response = requests.request("GET", url, auth=bearer_oauth, params=params)
    print(response.status_code)
    if response.status_code != 200:
        raise Exception(
            "Request returned an error: {} {}".format(
                response.status_code, response.text
            )
        )
    return response.json()


def main():
    url = create_url()
    json_response = connect_to_endpoint(url,params)
    json_response = flatten(json_response)
    d = json.dumps(json_response, indent=4, sort_keys=True)
    return d
    
    
if __name__ == "__main__":
    main()

但是我遇到了这个错误:

异常:请求返回了一个错误:400 {"errors":[{"parameters":{"ids":["4919451, 14151086"]},"message":"`ids`查询参数的值[ 14151086]无效"},{"parameters":{"user.fields":["name,description,location,public_metrics,username,created_at,"]},"message":"`user.fields`查询参数的值[]不在允许的范围内[connection_status,created_at,description,entities,id,location,most_recent_tweet_id,name,pinned_tweet_id,profile_image_url,protected,public_metrics,receives_your_dm,subscription_type,url,username,verified,verified_type,withheld]"}],"title":"请求无效","detail":"你的请求中有一个或多个参数无效。","type":"https://api.twitter.com/2/problems/invalid-request"}

你能帮我改进connect_to_endpoint这个函数,让它正常工作吗?提前感谢你的回答。

1 个回答

1

根据你收到的错误信息,你需要修正你的请求内容。你传入的 ids 应该是一个用逗号分隔的字符串,而不是看起来像列表的字符串([id,id])——也就是说,[] 这两个符号需要去掉。这个在 Twitter API 文档 中有说明:

ID:一个用逗号分隔的用户ID列表。一次请求最多可以包含100个。确保逗号和字段之间没有空格。

另外,user_fields 似乎多了一个 ,(在值字符串的末尾),这让API期待另一个字段名,但实际上没有,所以你会收到空字段名的错误。

一旦你修正了请求内容,API 应该会更顺利地工作:

params = {
    'ids': '4919451,14151086',
    'user.fields': 'name,description,location,public_metrics,username,created_at'
}

撰写回答