Python Tweepy Bot 从 json 文件中随机发布图像和相应的文本标题

Python Tweepy Bot that randomly tweets image and a corresponding text caption from a json file

我正在尝试创建一个 Twitter 机器人,它每 30 分钟从 json 文件中发送随机标题和相应的图像。到目前为止我有:

import tweepy
from time import sleep
import random

import json
with open('test.json', 'r') as f:
    info = json.load(f)

print('Twitter Bot')

CONSUMER_KEY = 'XXXXXX'
CONSUMER_SECRET = 'XXXXXX'
ACCESS_KEY = 'XXXXXX'
ACCESS_SECRET = 'XXXXXX'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)


randomChoice = random.randrange(len(info))
print (info[randomChoice])
api.update_status(status=info[randomChoice])

Json 文件:

    [
  {
    "text": "hi",
    "image": "/image1.jpg"
  },
  {
    "text": "hello",
    "image": "/image2.jpg"
  }
]

但推文只显示:{'text': 'hello', 'image': '/image2.jpg'}。我怎样才能让它只显示图像和文字?另外,我如何设置它以便每 30 分钟发生一次?我是编程新手,非常感谢提供的任何帮助!

你需要这样的东西:

api.update_with_media(info[randomChoice]['image'], 
                      status=info[randomChoice]['text'])

但是,您需要确定:

  1. 图像文件在当前工作目录中,或者
  2. 您提供图像文件的完整路径。

要每 30 分钟处理一次 运行,您可以使用 the schedule module:

import schedule
import time

def job():
    print("I'm working...")
    # your tweepy code here 

schedule.every(30).minutes.do(job)

while True:
    schedule.run_pending()
    time.sleep(1)