创建一个Twitter机器人,该机器人在提及时会响应某些短语

时间:2019-05-24 04:05:33

标签: python tweepy

正如标题所述,我正在尝试创建一个Twitter机器人,以响应用户的提及,这些提及包含短语“正在测试”和“正在测试成功”。我遇到的问题是写入文件以存储用户的Twitter ID,因此它不会一遍又一遍地回复相同的推文。

我尝试使用Streaming类提供帮助,但无济于事。

    import tweepy
    import keys
    import time

# Authentication for account with imported keys
    auth = tweepy.OAuthHandler(keys.consumer_key, keys.consumer_secret,)
    auth.set_access_token(keys.access_token, keys.access_token_secret,)
    api = tweepy.API(auth)
    user = api.me()
    print('Authorizing...\nLogging in!')
    print(user.name)

    name_of_file = 'id_storage.txt'

# Functions for writing to an empty text file to store the IDs.
    def retrieve_last_seen_id(file_name):
        f = open(file_name, 'r')
        last_seen_id = int(f.read().strip())
        f.close()
        return last_seen_id


    def store_last_seen_id(last_seen_id, file_name):
        f = open(file_name, 'w')
        f.write(str(last_seen_id))
        f.close()
        return

# Tweet moded extended is for showing full tweets.
    def reply_to_tweets():
        print('Searching through mentions...')
        last_seen_id = retrieve_last_seen_id(name_of_file)
        mentions = api.mentions_timeline(last_seen_id, 
    tweet_mode='extended')
        for mention in reversed(mentions):
            if 'testing' in mention.full_text():
                print('Found tweet...\n' + 'MENTION ID: ' + str(mention.id))
                print('Replying back to tweet...')
                api.update_status('@{} Test #1 Successful'.format(mention.user.screen_name))
                last_seen_id = mention.id
                store_last_seen_id(last_seen_id, name_of_file)

# Script runs every 20 seconds
    while True:
        reply_to_tweets()
        time.sleep(20)

0 个答案:

没有答案