我已经获得了此代码,它基本上对Twitter进行身份验证并直接传输直接消息(一旦我发送/接收,就会打印发送/接收的消息)。
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'])
我的问题:如何修改此代码以显示发件人的用户名?像这样:@Jack: Hey there!
答案 0 :(得分:1)
简单而肮脏的方式(你可以用字符串格式做更好的事情)就像是
for msg in twitter_userstream.user():
print(msg)
if 'direct_message' in msg:
print ('@' + msg['direct_message']['screen_name'] + ': ' + msg['direct_message']['text'])
值得注意的是,Twitter的用户流将在6月份消失,因此您应该查看新的帐户活动API。 this announcement中的更多详细信息。