Twitter图片机器人每两小时发布一次

0 投票
1 回答
1693 浏览
提问于 2025-04-18 11:25

这是一个推特图片机器人,每两小时会自动发一张图片,图片来自一个文件夹。这些图片的文件名是连续编号的,当前使用的编号会保存在一个文本文件里,这样每次运行时都能保持一致。图片的格式有.jpg和.gif,我不知道该怎么在我的代码中的picture()函数里处理这个问题。

import os
from twython import Twython 
from twython import TwythonStreamer

APP_KEY = ''
APP_SECRET = ''
OAUTH_TOKEN = ''
OAUTH_TOKEN_SECRET = ''

f = open('pictures.txt', 'r+')
z = f.read()

def picture():
    picture = open('/0/' + 'picture' + str(z))
    f.write(str(z)+'\n')
    global z
    z += 1
    promote(picture)
    f.write(z)
    f.close


def promote(photo):
    twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    twitter.update_status_with_media(status='', media=photo)

picture()

1 个回答

0

因为你之前的问题被搁置了,所以我再次发布这个回答。

可以使用 glob 来查找以特定前缀开头的文件,使用 imghdr 来检查文件类型(因为推特不支持所有的图片文件)。在读取图片序列号时,记得把它转换成整数,更新文件时再把它转换成字符串。更新文件时需要先把光标移动到文件的开头,并且假设序列号是一直递增的。

import imghdr
from glob import glob

SUPPORTED_IMG_TYPES = 'gif jpeg png'.split()
IMG_SEQ_FILE = '/0/pictures.txt'
GLOB_PATTERN = '/0/picture%d.*'

def send_to_twitter(filename):
    print "sent %s to twitter" % filename
    return True

with open(IMG_SEQ_FILE, 'r+') as f:
    seq = int(f.readline().strip())
    for name in glob(GLOB_PATTERN % seq):
        img_type = imghdr.what(name)
        if img_type in SUPPORTED_IMG_TYPES:
            if send_to_twitter(name):
                f.seek(0)
                seq += 1
                f.write(str(seq))
                break
        else:
            if not img_type:
               print "%s is not an image file" % name
            else:
               print "%s unsupported image type: %s" % (name, img_type)

你只需要添加你的代码来将图片文件的数据发送到推特。

撰写回答