[英]Tweepy: problem retrieving username informations with twitter v2 api
[英]How to use tweepy for Twitter API v2 in getting user id by username?
I'm trying to replicate this snippet from geeksforgeeks, except that it uses the oauth for Twitter API v1.1 while I the 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 個。
你能告訴我我錯過了什么嗎? 提前謝謝。
get_user
具有以下簽名。
Client.get_user(*, id, username, user_auth=False, expansions, tweet_fields, user_fields)
注意*
。 *
用於強制調用者使用名為 arguments。 例如,這不起作用。
>>> 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)
我相信 client.get_user(username=screen_name) 返回一個 class 所以這個 function 對我有用:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.