skip to Main Content

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.

2

Answers


  1. 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
    Login or Signup to reply.
  2. You say

    I would like to get the name for the twitter account associated with the client’s access tokens and secrets

    and

    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.

    If I understand you correctly, you want to find out which application was used to send a tweet – so you can filter it out?

    In each tweet, you will find an attribute called source. This shows which app the user sent the tweet with.

    For example,

    "created_at": "Sun Mar 11 11:25:05 +0000 2018",
    "source": "u003ca href="http://twitter.com/download/android" rel="nofollow"u003eTwitter for Androidu003c/au003e",
    "in_reply_to_status_id_str": "972414342166654976",
    

    That Tweet was sent using Twitter for Android’s API keys.

    And in this example:

    "source": "u003ca href="http://shkspr.mobi/blog/tag/solar/" rel="nofollow"u003eEdent's Solar Panelsu003c/au003e",
    "in_reply_to_status_id": null,
    

    The Tweet was sent from my personal API key.

    Give your API key a unique name and URL. When you retrieve Tweets, check the source parameter, and don’t reply to any which have been sent using your access token and secret.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search