使用Tweepy的自动直接消息响应

2022-04-18 00:00:00 python tweepy twitter wrapper

问题描述

我目前正在使用python中的tweepy包作为DM侦听器。我希望在收到发送者的消息后给他们发送回复。我有以下信息:

class StdOutListener( StreamListener ):
    def __init__( self ):
        self.tweetCount = 0

    def on_connect( self ):
        print("Connection established!!")

    def on_disconnect( self, notice ):
        print("Connection lost!! : ", notice)

    def on_data( self, status ):
        status = str(status)
        try:
            json_acceptable_string = status.replace('\','')
            #string to dict
            status=json.loads(json_acceptable_string)
            if 'direct_message' in status.keys():
                print '
'
                print status[u'direct_message'][u'sender_screen_name'] +' sent: '+ status[u'direct_message'][u'text']
                message=str(status[u'direct_message'][u'text'])
                api.send_direct_message(screen_name=str(status[u'direct_message'][u'sender_screen_name']),text='Out of office now - will respond to you asap')
                print 'auto response submitted'
            else:
                #not direct message flow
                pass
        except:
            #not important flows - couldn't convert to json/not correct flow in stream
            pass
        return True

def main():
    global api
    try:
        auth = OAuthHandler(consumer_key, consumer_secret)
        auth.secure = True
        auth.set_access_token(access_token, access_token_secret)
        api = API(auth)
        print(api.me().name)
        stream = Stream(auth, StdOutListener())
        stream.userstream()

    except BaseException as e:
        print("Error in main()", e)

if __name__ == '__main__':
    main()

出于某种原因,我可以看到用户的print语句以及他们发送的内容,但当它到达Send_DIRECT_MESSAGE方法时挂起。 奇怪的是,如果我自己发消息,我会在消息循环的过程中收到一连串的消息。这是因为它是on_data()吗?如何使此功能适用于其他发件人?

更新:已解析-重新生成令牌并添加条件以检查发件人,实际上是将我自己列入黑名单。


解决方案

更新:已解析-重新生成令牌并添加条件以检查发件人,实际上是将我自己列入黑名单。

相关文章