从目录中随机发布Twitter图片

时间:2019-03-18 22:55:59

标签: python twitter tweepy

所以我不知道我的确切问题是什么,我是一名业余程序员,所以我不完全知道我在做对还是错。因此,如果有人可以帮助我,我将非常感激。 这是我的代码,我真的不知道我在失败什么,因为它说这是路径上的失败:

import tweepy
from time import sleep
folderpath= "E:\Fotosprueba"
def tweepy_creds():
    consumer_key = 'x'
    consumer_secret = 'x'
    access_token = 'x'
    access_token_secret = 'x'

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    return tweepy.API(auth)

def getPathsFromDir(dir, EXTS="extensions=,png,jpg,jpeg,gif,tif,tiff,tga,bmp"):
    return this.listPaths('E:\Fotosprueba', EXTS)

def tweet_photos(api):
imagePaths = "E:\Fotosprueba"
for x in imagePaths:
    status = "eeeee macarena"
    try:
        api.update_with_media(filename=x,status=status)
        print ("Tweeted!")
        sleep(10)
    except Exception as e:
        print ("encountered error! error deets: %s"%str(e))
        break

if __name__ == "__main__":
    tweet_photos(tweepy_creds())

1 个答案:

答案 0 :(得分:0)

您似乎在tweet_photos方法上缺少缩进。没有这种缩进,解释器将无法分辨该方法的开始和结束位置。

此外,您正在尝试遍历str。在这种情况下,x的值将是此字符串中的每个单独字符。您可以通过在Python解释器中运行以下代码来验证这一点:

imagePaths = "E:\Fotosprueba"
for x in imagePaths:
  print(x)

输出:

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
E
:
\
F
o
t
o
s
p
r
u
e
b
a

从外观上看,您可能希望将此str的值传递给getPathsFromDir方法。试试这个:

def getPathsFromDir(dir, EXTS="extensions=,png,jpg,jpeg,gif,tif,tiff,tga,bmp"):
    return this.listPaths(dir, EXTS) # This now uses the value of dir


def tweet_photos(api):
    imagePaths = "E:\Fotosprueba"
    # This now passes imagepaths to the getPathsFromDir method, 
    # and *should* return a list of files.
    for x in getPathsFromDir(imagePaths): 
        status = "eeeee macarena"
        try:
            api.update_with_media(filename=x,status=status)
            print ("Tweeted!")
            sleep(10)
        except Exception as e:
            print ("encountered error! error deets: %s"%str(e))
            break

从理论上讲,只要您的班级还包含一个listPaths方法,它就可以按预期工作。如果不是,则需要进行修改以包括此方法,或者将调用更改为this.listpaths以指向其他位置。