I am trying to make a Tweepy bot which randomly selects an image from a folder and tweets it with a corresponding caption from a text file, and repeats this on a set interval via sleep. I have not used python or any other coding language before so I am extremely unacquainted with how to accomplish this. So far I have this:
import tweepy
from time import sleep
import random
print('Twitter Bot')
CONSUMER_KEY = 'XXXXXXX'
CONSUMER_SECRET = 'XXXXXXX'
ACCESS_KEY = 'XXXXXXX'
ACCESS_SECRET = 'XXXXXXX'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
filename = open('tweets.txt','r')
file_lines = filename.readlines()
filename.close()
media_list = list()
response = api.media_upload('image.png')
media_list.append(response.media_id_string)
randomChoice = random.randrange(len(file_lines))
print (file_lines[randomChoice])
api.update_status(status=file_lines[randomChoice], media_ids=media_list)
As you can see all this does is select a random line as the tweet text, and a set image. However, I am trying to achieve either selecting a random image with corresponding text, or vice versa. That is: there should be a specific text line corresponding to each image, but I'm unsure how to go about this.
First store your information in a .json
file like this:
[
{
"text": "hi",
"image": "/image1.jpg"
},
{
"text": "hello",
"image": "/image2.jpg"
}
]
Then load it in Python as a list:
import json
with open('test.json', 'r') as f:
info = json.load(f)
And then the rest is just same as your code: random choose an item from the loaded list.