hagino3000's blog

平成アーカイブス (更新停止)

Twitter検索の結果をGrowlで表示するインタラクティブプレゼンテーションツールをPythonで書いた

GrowlをONにしたままプレゼンをするのが流行ってるそうなので、それ用のスクリプトを書いた。明日のPython Hack-a-thon#2の公式ハッシュタグは#moriyoshiなので、#moriyoshiの検索結果を30秒毎に表示します。

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import os
import sys
from StringIO import StringIO
import urllib
from PIL import Image
import Growl
import twython
import time
from setting import Setting

imageSet = set([])
tweetIdSet = set([])

#### search keyword ######
keyword = "#moriyoshi"

def p(text):
  print(text)

def getImagePath(userName, url):
  #p(url)
  result = os.getcwd() + '/imageCache/' + userName + '.jpg'
  if (userName in imageSet):
    return result
  else:
    try:
      imageData = urllib.urlopen(url).read()
      imagePil = Image.open(StringIO(imageData))
      imagePil.thumbnail((64, 64))
      imagePil.convert('RGB')
      imagePil.save(result)
      imageSet.add(userName)
    except:
      return ""
    return result


def growl(g, tweet):
  imagePath = getImagePath(tweet['userName'], tweet['iconUrl'])
  if imagePath:
    icon = Growl.Image.imageFromPath(imagePath)
  else:
    icon = ""

  g.notify(
      noteType='Tweet', 
      title=tweet['userName'], 
      description=tweet['text'], 
      icon=icon,
      sticky=False)

def getTweets():
  p('start getTweets')
  twitter = twython.setup(authtype="Basic",
      username=Setting.userName,
      password=Setting.password)
  search_results = twitter.searchTwitter(keyword, rpp="50")

  results = []

  for tw in search_results["results"]:
    text = tw['text']
    userName = tw['from_user']
    iconUrl = tw["profile_image_url"]
    status_id = str(tw["id"])
    
    if (status_id in tweetIdSet):
      continue
    else:
      tweetIdSet.add(status_id)
      results.append({'text':text, 'userName':userName, 'iconUrl':iconUrl});

  return results



# setup growl
p('start()')
g = Growl.GrowlNotifier(
    applicationName='Twitter', notifications=['Tweet'])
g.register()

while 1:
  tweets = getTweets()
  for tw in tweets:
    growl(g, tw)
  time.sleep(30)

p('end()')


設定ファイル含めたものはbitbucketに上げてあります。
http://bitbucket.org/hagino_3000/growltweet/src/


Pythonは全く書けないので、上のコードはかなり恥しい出来だと思うのですがどうなんでしょう。あと、Keynoteのスライド再生中にGrowlが見えなくなるのであんまり意味ないかもしれません。(Growlを見える様にできる?)