【问题标题】:Twitter image bot posts every 2 hoursTwitter 图片机器人每 2 小时发布一次
【发布时间】:2014-06-28 21:41:09
【问题描述】:

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

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()

【问题讨论】:

  • 运行时会给出什么错误信息。也添加一些信息
  • @cmrnrb - 您是否阅读过this answer 到您之前非常相似的问题?

标签: python python-2.7 twitter twython


【解决方案1】:

由于您之前的问题已被搁置,我再次发布此答案。

使用glob查找匹配前缀的文件,imghdr检查文件类型(twitter不支持所有图像文件),并确保在阅读时将图像序列号转换为int更新文件时输入和到字符串。文件更新需要先寻找到文件的开头,这假设序列号总是增加。

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。

【讨论】:

  • 当我运行这个时,glob 中的 name 似乎没有运行,什么都没有打印并且文本文件根本没有更新?谢谢
  • /0 中是否有匹配 glob 模式的文件,例如是否有名为“picture1.jpg”的文件?序列文件你初始化了吗,是在/0/pictures.txt吗?
  • 是的,我有图片,我有图片文件,其中只有数字“0”
  • 是否有名为/0/picture0.jpg/0/picture0.gif 等的文件?如果是,您的应用程序是否有权读取该文件?
  • 是的,这些文件都在那里,当我有其他代码之前,它能够读取和写入文件
猜你喜欢
  • 2020-09-16
  • 2017-11-19
  • 2020-06-12
  • 1970-01-01
  • 2019-09-14
  • 1970-01-01
  • 2017-08-13
  • 1970-01-01
  • 2018-04-02
相关资源
最近更新 更多