Search code examples
pythontwittertweepy

Random publishing twitter images from directory


So i do not know what my exact problem is, i am an amateur programmer so i dont wholly know if i'm doing right or wrong. That's why I would really appreciate if anyone could help me just a bit. This is my code and I don't really know what i'm failing at cause it says it's a failure on the path:

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())

Solution

  • You appear to be missing indentation on your tweet_photos method. Without this indentation, the interpreter won't be able to tell where the method starts and ends.

    Additionally, you are attempting to iterate over a str. In this case, the value of x will be each individual character in this string. You can verify this by running the following code in the Python interpreter:

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

    Output:

    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
    

    By the looks of things, you may want to pass the value of this str to the getPathsFromDir method instead. Try this:

    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
    

    In theory this should work as intended, as long as your class also includes a listPaths method. If it doesn't, you'll need to modify to include this method, or change the call to this.listpaths to point to somewhere else.