【问题标题】:How to use tweepy for Twitter API v2 in getting user id by username?如何使用 tweepy for Twitter API v2 通过用户名获取用户 ID?
【发布时间】:2022-01-20 20:08:34
【问题描述】:

我正在尝试从 geeksforgeeks 复制此 sn-p,但它使用 Twitter API v1.1 的 oauth,而我使用 API v2。

# the screen name of the user
screen_name = "PracticeGfG"

# fetching the user
user = api.get_user(screen_name)

# fetching the ID
ID = user.id_str

print("The ID of the user is : " + ID)

OUTPUT:
The ID of the user is: 4802800777.

这是我的:

import os
import tweepy

API_KEY = os.getenv('API_KEY')
API_KEY_SECRET = os.getenv('API_KEY_SECRET')
BEARER_TOKEN = os.getenv('BEARER_TOKEN')
ACCESS_TOKEN = os.getenv('ACCESS_TOKEN')
ACCESS_TOKEN_SECRET = os.getenv('ACCESS_TOKEN_SECRET')

screen_name = 'nytimes'

client = tweepy.Client(consumer_key=API_KEY, consumer_secret=API_KEY_SECRET, access_token=ACCESS_TOKEN, access_token_secret=ACCESS_TOKEN_SECRET)

user = client.get_user(screen_name)
id = user.id_str

print(id)

当我运行我的时,它返回此错误:

TypeError: get_user() 接受 1 个位置参数,但给出了 2 个。

你能告诉我我错过了什么吗?先谢谢了。

【问题讨论】:

    标签: python twitter tweepy twitterapi-python


    【解决方案1】:

    get_userfollowing signature

    Client.get_user(*, id, username, user_auth=False, expansions, tweet_fields, user_fields)
    

    注意** 用于强制调用者使用命名参数。例如,这不起作用。

    >>> def add(first, *, second):
    ...     print(first, second)
    ...
    >>> add(1, 2)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: add() takes 1 positional argument but 2 were given
    

    但这会

    >>> add(1, second=2)
    1 2
    

    所以要回答你的问题,你应该像这样调用get_user 方法。

    client.get_user(username=screen_name)
    

    【讨论】:

    • 我觉得方法是对的,但是返回401错误。这肯定不是密钥和令牌不正确的问题,因为我有另一个运行良好的项目使用相同的凭据。但我知道现在这超出了问题的范围。谢谢。
    【解决方案2】:

    我相信 client.get_user(username=screen_name) 返回一个类,所以这个函数对我有用:

    def return_twitterid(screen_name):
        print("The screen name is: " + screen_name)
        twitterid = client.get_user(username=screen_name)
        print(type(twitterid)) #to confirm the type of object
        print(f"The Twitter ID is {twitterid.data.id}.")
        return
    

    【讨论】:

      猜你喜欢
      • 2019-03-28
      • 2017-08-24
      • 2018-03-07
      • 2022-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 2016-07-29
      相关资源
      最近更新 更多