我使用 Tweepy 用 python 编写了一个 twitterbot。这是我的代码:
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
filename = open ('Shakespeare.txt', 'r')
tweettext = filename.readlines()
filename.close()
randomChoice = random.randrange(len(tweettext))
print (tweettext[randomChoice])
api.update_status(status=tweettext[randomChoice])
每当我在树莓派上通过 SSH 运行它时,它都能完美运行 - 我的推文会更新我的 Twitter feed。我的问题是:我想在每条随机推文中添加莎士比亚的图片(始终是同一张图片)。
一种解决方案是:
file = open('Your_image.png', 'rb')
data = file.read()
r = api.request('statuses/update_with_media', {'status':'Your tweet'}, {'media[]':data})
print(r.status_code)
但是,我不知道如何将其合并到我现有的代码中。如有任何建议,我们将不胜感激。
我还想随机化我的图片上传。这是我发现的从/home/pi 中选择随机图像的代码:
'def get_random_image_from_folder(folder):
media_list = list()
for dirpath, dirnames, files in os.walk(folder):
for f in files:
media_list.append(os.path.join(dirpath, f))
media = random.choice(media_list)
return media, len(media_list)'
我的问题是:如何编写 API 状态更新代码?我输入的代码在这里:
'api.update_status(status=tweettext[randomChoice], media=random.choice(media_list))'
但是,这会产生以下错误:
'回溯(最近一次调用最后一次): 文件“Shakebot.py”,第 30 行,位于 api.update_status(status=tweettext[randomChoice], media=random.choice(media_list)) NameError:名称“media_list”未定义'
我不明白,因为“media_list”是在图像位置定义的。
最佳答案
update_with_media
已弃用 .
您应该使用 media_upload
( Twitter docs ;Tweepy 文档已过时,但您可以检查 github repo 处的代码),这将返回一个 media_id_string 作为上传响应的一部分,然后您可以发送包含文本和列表以及 media_id_string (或字符串,您最多可以附加 4 个图像)的推文。
这是使用 media_upload
的代码:
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
filename = open ('Shakespeare.txt', 'r')
tweettext = filename.readlines()
filename.close()
media_list = list()
response = api.media_upload('Your_image.png')
media_list.append(response.media_id_string)
randomChoice = random.randrange(len(tweettext))
print (tweettext[randomChoice])
api.update_status(status=tweettext[randomChoice], media_ids=media_list)
关于python - 带有附加图像的随机推文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41286249/