Tweepy Streaming Direct Messages

时间:2016-11-15 03:33:47

标签: python tweepy twitter-streaming-api

我一直在使用Tweepy和Python 2.7来传输推文,一切都运行正常,但是当我向帐户发送直接消息时,on_direct_message()方法没有被调用。我已经更新了我的权限,甚至尝试使用on_data()方法,但它似乎无法检测到直接消息。

import tweepy

CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_KEY = ''
ACCESS_SECRET = ''
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True)

followed_accounts = ['account', 'account']
followed_ids = []

for account in followed_accounts:
    followed_ids.append(str(api.get_user(screen_name=account).id))


class StdOutListener(tweepy.StreamListener):

    def on_direct_message(self, status):

        author = status.author.screen_name
        api.send_direct_message(screen_name=author, text='response')

        return True

    def on_status(self, status):

        author = status.author.screen_name
        statusID = status.id

        print status.text + "\n"

        api.update_status('response')
        api.send_direct_message(screen_name='my username', text='Just sent a Tweet')

        return True

    def on_data(self, status):
        print 'Entered on_data()'
        print status

        return True

    def on_error(self, status_code):
        print "Error Code: " + str(status_code)
        if status_code == 420:
            return False
        else:
            return True

    def on_timeout(self):
        print('Timeout...')
        return True

if __name__ == '__main__':
    listener = StdOutListener()
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)

    stream = tweepy.Stream(auth, listener)
    stream.filter(follow=followed_ids)

向帐户发送直接消息不会出错,并且帐户会在Twitter上正确接收消息。

0 个答案:

没有答案