skip to Main Content

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.

2

Answers


  1. 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)
    
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search