Search code examples
ruby-on-railsrubytwittertwitter-rest-api

Retrieve screen name from twitter account?


Is it possible to get a twitter account's username from an instance of the Twitter REST client? Specifically, I would like to get the name for the twitter account associated with the client's access tokens and secrets.

I searched through the twitter gem documentation on rubydoc and looked at the Twitter API user object documentation but wasn't able to solve the problem. I did try using client.attributes, client.to_h and client.screen_name, but received an unknown method error.

For context, I'm currently working on a twitter bot that auto-replies to hashtags when it is looped into a conversation. We want to prevent the bot from tweeting at itself, so we are currently hard-coding in the bot name as an account not to tweet at. It would be helpful if we could replace the hard-coded name with something like client.account_name.

Thanks for reading.


Solution

  • Taking a look at the documentation for the client object of the twitter gem says it has a user method (Methods included from Users section) [1]. The documentation for the user method states it returns a Twitter::User object of the currently authenticated user [2]. This class inherits from BasicUser which is where the screen_name method exists [3].

    client.user.screen_name
    
    1. http://www.rubydoc.info/gems/twitter/Twitter/REST/Client
    2. http://www.rubydoc.info/gems/twitter/Twitter/REST/Users#user-instance_method
    3. http://www.rubydoc.info/gems/twitter/Twitter/BasicUser