Drkcore

25 06 2010 Python twitter Tweet

Twitter Streaming APIをtweepyでGrowlに通知する

勉強会とかでオフィシャルハッシュタグがある場合に、「タグ付きのtweetがプレゼンしているスクリーンに出ればいいのに」と思ったりしたことはありませんか?

僕はあります。

なので、引数に任意の文字列を渡すとフィルタリングした結果をGrowlに通知するようなものを作ってみた。

$ python tw_stream.py "#worldcup"

twitter growl

参考にしたのは以下のサイト

  • PythonでGrowlを叩く
  • joshthecoder / tweepy-examples
  • Twitter to Growl Agent in Python
  • pythonでtwitterのStreaming APIを使ってみた

コード

import sys,os
import tweepy
import Growl
import simplejson
import urllib2
import hashlib
from pit import Pit

class StreamListener(tweepy.StreamListener):
    def __init__(self):
        self.g = Growl.GrowlNotifier(applicationName='TwitterWatcher', notifications=['Watch'])
        self.g.register()
        self.image_dir = os.path.join(os.path.expanduser('~'),".tw_growl")

        if not os.path.exists(self.image_dir):
            os.makedirs(self.image_dir)

    def get_icon(self,url):
        fname = "%s.%s" % (hashlib.md5(url).hexdigest(),url.split('.')[-1])
        cached_image = os.path.join(self.image_dir,fname)
        image = None
        if os.path.exists(cached_image):
            image = Growl.Image.imageFromPath(cached_image)
        else:
            f = open(cached_image,'wb')
            f.write(urllib2.urlopen(url).read())
            f.close()
            image = Growl.Image.imageFromPath(cached_image)
        return image

    def on_data(self, data):
        data = simplejson.loads(data)
        image = self.get_icon(data['user']['profile_image_url'])
        self.g.notify(
            noteType='Watch', 
            title=data['user']['screen_name'], 
            description=data['text'], 
            icon=image,
            #description=image,
            sticky=False)

def main():
    conf   = Pit.get('twitter.com')
    user   = conf['username']
    passwd = conf['password']

    stream = tweepy.Stream(user, passwd, StreamListener())
    stream.filter(track=[sys.argv[1]])

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print '\nGoodbye!'

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021