首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Twitter图像机器人每2小时发布一次

Twitter图像机器人每2小时发布一次
EN

Stack Overflow用户
提问于 2014-06-28 12:31:14
回答 1查看 1.6K关注 0票数 0

这是一个twitter,每两小时调用一次,从文件夹中发布图片,文件被连续编号,当前编号存储在文本文件中,以便在运行之间保持不变。图像文件类型在.jpg和.gif之间有所不同,我不知道如何在我的代码的图片()函数中解释这一点。

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-06-28 13:41:09

既然你的上一个问题被搁置了,我再发一次这个答案。

使用格罗布查找与前缀匹配的文件,使用imghdr检查文件类型(twitter不支持所有图像文件),并确保在读取图像序列号时将其转换为int,并在更新文件时将其转换为字符串。文件更新要求首先查找文件的开头,这假定序列号将始终增加。

代码语言:javascript
复制
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)

您所需要做的就是添加代码将图像文件数据发送到twitter。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24466832

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档