Python Twitter Bot to post images is not finding image

46 Views Asked by At

I am trying to create a python twitter bot that posts a random image from a folder on my desktop every eight hours, using the Tweepy api.simple_upload. However, I'm getting an error that says "FileNotFoundError: [Errno 2] No such file or directory: '8507_wildfive.jpg'". It's saying the file is not being found yet displaying the title, which I don't understand.

Here is the code:

import tweepy
import os
import time
import random

# Set up your Twitter API credentials
consumer_key = '~~~'
consumer_secret = '~~~'
access_token = '~~~'
access_token_secret = '~~~'

# Authenticate to the Twitter API
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

# Get a list of all the images in the specified folder
images = os.listdir("D:/Trevor/Pictures/Reference/Zimmerman")

# Set the interval for uploading images (in seconds)
interval = 8 * 60 * 60  # 8 hours

while True:
    # Select a random image from the list
    image = random.choice(images)

    # Upload the image to Twitter
    api.simple_upload(image)

    # Wait for the specified interval before uploading the next image
    time.sleep(interval)

The traceback I get is:

Traceback (most recent call last):
  File "D:\Trevor\Downloads\TweepyV2Images-main\ZbotV10.py", line 28, in <module>
    api.simple_upload(image)
  File "C:\Python38\lib\site-packages\tweepy\api.py", line 46, in wrapper
    return method(*args, **kwargs)
  File "C:\Python38\lib\site-packages\tweepy\api.py", line 3596, in simple_upload
    files = {'media': stack.enter_context(open(filename, 'rb'))}
FileNotFoundError: [Errno 2] No such file or directory: '8507_wildfive.jpg'
[Finished in 316ms]

Any help would be appreciated.

1

There are 1 best solutions below

0
Josh Brunton On

The os.listdir function doesn't return the full path, just relative to the directory it's called on.

For example, if there is a file a/b/c.txt and you call os.listdir("/a/b"), your output won't be ["/a/b/c.txt"], but just ["c.txt"].

To get the full path to the image, try:

image = "D:/Trevor/Pictures/Reference/Zimmerman/" + random.choice(images)