5

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.

And here's mine:

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)

When I run mine, it returns this error:

TypeError: get_user() takes 1 positional argument but 2 were given.

Can you give me hints in what did I miss? Thanks ahead.

Dwight
  • 53
  • 1
  • 3

2 Answers2

5

get_user have the following signature.

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

Notice the *. * is used to force the caller to use named arguments. For example, This won't work.

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

But this will

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

So to answer your question you should call the get_user method like this.

client.get_user(username=screen_name)
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46
  • 2
    I think the method is right, but it returns a 401 error. It's not surely an issue of incorrect keys and tokens since I have another project that's running fine which uses the very same credentials. But I know it's out of the scope of the question now. Thanks. – Dwight Jan 08 '22 at 13:01
  • When I try user = api.get_user(username="atwitternameuser") , I get Unexpected parameter: username – G.Lebret Jul 31 '23 at 12:32
4

I believe that client.get_user(username=screen_name) returns a class so this function works for me:

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
ITCrowd
  • 43
  • 5