使用推文ID作为文件名

时间:2013-09-25 15:01:49

标签: python twitter

我正在尝试整理一个脚本,该脚本将为特定关键字观看Twitter,拍照,然后回复带有图片的初始推文。为了保持一切顺利,我想使用初始推文的唯一ID作为图片的文件名。我想我很接近,但我无法弄清楚如何让它发挥作用。这是代码:

import sys
import tweepy
import time
import threading
import subprocess

consumer_key="X"
consumer_secret="X"
access_key = "X"
access_secret = "X" 

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)

class Timer(threading.Thread):
    def __init__(self, seconds):
        self.runTime = seconds
        threading.Thread.__init__(self)
    def run(self):
        time.sleep(self.runTime)

class CountDownTimer(Timer):
    def run(self):
        counter = self.runTime
        for sec in range(self.runTime):
            print counter
            time.sleep(1.0)
            counter -= 1

class CountDownExec(CountDownTimer):
    def __init__(self, seconds, action):
        self.action = action
        CountDownTimer.__init__(self, seconds)
    def run(self):
        CountDownTimer.run(self)
        self.action()

def takePicture():
    new_tweet = CustomStreamListener(status_info)
    subprocess.Popen(['raspistill', '-o', '{}.jpg'.format(new_tweet.id), '-t', '0'])

c = CountDownExec(5, takePicture)

class CustomStreamListener(tweepy.StreamListener):
    def __init__(self,status):
       self.id = status.id
    def on_status(self, status):
       print status.user.id
       print status.user.screen_name
       print status.id
       print status.text
       c.start()

    def on_error(self, status_code):
        print >> sys.stderr, 'Encountered error with status code:', status_code
        return True # Don't kill the stream

    def on_timeout(self):
        print >> sys.stderr, 'Timeout...'
        return True # Don't kill the stream

sapi = tweepy.streaming.Stream(auth, CustomStreamListener())
sapi.filter(track=['#hashtag @username'])

2 个答案:

答案 0 :(得分:1)

您的CustomStreamListener类有一个__init__方法,该方法带有status个参数,但在行中

sapi = tweepy.streaming.Stream(auth, CustomStreamListener())

你创建CustomStreamListener的实例而不传递该参数,因此它会引发错误

__init__() takes exactly 2 arguments (1 given)

这意味着__init__得到self参数,而不是另一个(status)。

要解决这个问题,你必须在类的实例化上传递status个参数!

答案 1 :(得分:0)

...关闭

subprocess.Popen(['raspistill', '-o', '{0}.jpg'.format(new_tweet.id), '-t', '0'])

使用string.format()时,需要在花括号内提供位置编号。