使用随机图片与Twython

时间:2016-04-18 09:37:39

标签: python bots twython

我正在使用Twython制作一个从文件夹中发布随机图像的机器人,这是代码!

from twython import Twython
import glob
import random

app_key = "XXX"
app_secret = "XXX"
oauth_token = "XXX" 
oauth_token_secret = "XXX"
twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret)

def RandomImageTwitt(folder):
        #Takes the folder where your images are as input
        images = glob.glob(folder + "*")
        image_open = open(images[random.randint(0,len(images))-1])
        #Tweeting
        image_ids = twitter.upload_media(media=image_open)
        twitter.update_status(status='hello this is a status', media_ids=image_ids['media_id'])

 RandomImageTwitt("/home/Pi/Bots/Pictures/")

好的,当我使用python script.py时,它会返回此错误:

Traceback (most recent call last):
  File "script.py", line 20, in <module>
  RandomImageTwitt("/home/Pi/Bots/Pictures/")
File "script.py", line 14, in RandomImageTwitt
  image_open = open(images[random.randint(0,len(images))-1])
IndexError: list index out of range

我是Python的初学者,如果可以提供帮助,我的所有文件都会像这样存储:1.jpg,2.jpg,3.jpg ...每个文件都在jpg中,列表从1开始

谢谢!

1 个答案:

答案 0 :(得分:1)

确保images不为空。

顺便说一下,使用random.choice更好(不需要自己计算索引,更容易阅读):

image_open = open(random.choice(images))
如果序列为空,

random.choice也会引发IndexError