我正在用Python和Tweepy制作一个机器人,该机器人在被提及时会给出图像答复,但是他一直在回复相同的推文。我试图使用If来解决这个问题,但是没有用。
import tweepy
import os
import time
import random
os.chdir ('images')
#Keys to API
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret =''
#Auth to API
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
user = api.me()
print (user.name)
def reply_bot():
search = api.search(q='@KancolleSleep')
for tweet in search:
print (f'UserName: {tweet.user.screen_name}')
name = tweet.user.screen_name
message = []
message += (tweet.text)
message2 = (tweet.text)
if message2 != message:
print (f'Tweet: {tweet.text}')
media_ids = []
image1 = random.choice(os.listdir('.'))
file = api.media_upload(image1)
media_ids.append(file.media_id)
print (image1)
text = (f'@{name}')
api.update_status(status=text, media_ids=media_ids, in_reply_to_status_id=tweet.id)
else:
print ("Tweet already answered")
while True:
reply_bot()
time.sleep(15)
有一种有效的方法来防止这种情况发生吗?
答案 0 :(得分:2)
我假设每条推文都有一个ID。您可以只存储漫游器已回复的推文ID的列表,并针对每条新推文检查它是否已在列表中。
这里是一个示例:
already_answered = []
def reply_bot():
search = api.search(q='@KancolleSleep')
for tweet in search:
# add your code
if tweet.id not in already_answered:
# add your code
already_answered.append(tweet.id)
else:
print('tweet already answered')