Search code examples
pythontwitter

Display DM sender's username (Twitter)


I've got this code, where it basically authenticates to Twitter and streams Direct Messages directly (as soon as I send/receive, the message sent/received gets printed).

from twitter import *
import os

APP_KEY,APP_SECRET = 'appkey123', 'appsecret123'


MY_TWITTER_CREDS = os.path.expanduser('my_app_credentials')
if not os.path.exists(MY_TWITTER_CREDS):
    oauth_dance("crypto sentiments", APP_KEY, APP_SECRET,
                MY_TWITTER_CREDS)

oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS)

auth = OAuth(
    consumer_key=APP_KEY,
    consumer_secret=APP_SECRET,
    token=oauth_token,
    token_secret=oauth_secret
)

twitter_userstream = TwitterStream(auth=auth, domain='userstream.twitter.com')
for msg in twitter_userstream.user():
    print(msg)
    if 'direct_message' in msg:
        print (msg['direct_message']['text'])

My question: How can I modify this code so it displays the username of the sender? Like so: @Jack: Hey there!


Solution

  • Simple and dirty way (you could do something far nicer with the string formatting) would be something like

    for msg in twitter_userstream.user():
    print(msg)
    if 'direct_message' in msg:
        print ('@' + msg['direct_message']['screen_name'] + ': ' + msg['direct_message']['text'])
    

    It is worth noting that Twitter's user streams will be going away in June, so you should look at the new Account Activity API instead. More details in this announcement.