2011/01/12 21:37:17
googlemapに円を描き入れる
入れてみた。ついでに常に地図の中心から5kmの範囲を示すようにした(twitterで地図の中心から5kmの範囲のtweetをサーチしているので)
最近毎朝アクセスして、昨晩雪が降って道路が凍結してないか確認している。富士と御殿場は天気がかなり違うのでこっちが晴れててもあっちは雪降ってるとかよくある。
Google Maps APIがなかなか楽しい。
入れてみた。ついでに常に地図の中心から5kmの範囲を示すようにした(twitterで地図の中心から5kmの範囲のtweetをサーチしているので)
最近毎朝アクセスして、昨晩雪が降って道路が凍結してないか確認している。富士と御殿場は天気がかなり違うのでこっちが晴れててもあっちは雪降ってるとかよくある。
Google Maps APIがなかなか楽しい。
埋め込みテスト
urlのパラメータを渡すようにする必要があるのと、違うドメインだとinvalidされるっぽい(テスト環境だとinvalid URL)
勉強会とかでオフィシャルハッシュタグがある場合に、「タグ付きのtweetがプレゼンしているスクリーンに出ればいいのに」と思ったりしたことはありませんか?
僕はあります。
なので、引数に任意の文字列を渡すとフィルタリングした結果をGrowlに通知するようなものを作ってみた。
$ python tw_stream.py "#worldcup"

参考にしたのは以下のサイト
コード
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!'
RのtwitterクライアントであるtwitteRを使ってみた。
library(twitteR)
sess <- initSession(user,password)
friendsTimeline(session=sess) # タイムライン表示
tweet("rtest", session=sess) # tweet
お手軽感は高い。
あらすじ
2010年春、しゃべるを職場に入れてみたところ、ちょっと後ろ向きな発言をする人たちに人気が出てしまい、ネガな雰囲気のただようブラックマイクロブログになりかけていた。
これじゃいかんということで、ポジな発言を紛れ込ませることにしたのであった。
しゃべるのAPIはtwitter互換なのでpython-twitterのハードコードされているurlをしゃべるのそれに変えてやればpythonモジュールがあっという間に出来上がり。ついでにshovel.pyってすればimport shovelで呼べる。
あとはfeedparserでtwitterのポジティブフィードを解析して、一日一回くらいイントラtwitterに注入すればいいわけだ。
import feedparser
import re,os
shuzo_tweet = re.compile("^(shuzo_matsuoka:\ @[^\ ]+ |shuzo_matsuoka:\ )")
d = feedparser.parse("http://twitter.com/statuses/user_timeline/63097969.rss")
stweet = [shuzo_tweet.sub('',e['title']) for e in d['entries']]
import shovel
api = shovel.Api(username='xxx', password='xxx')
users = api.GetFollowers()
followers = [u.screen_name for u in users]
for u,m in zip(followers,stweet):
message = "@%s %s" % (u,m)
api.PostUpdate(message)
これで、とりあえずフォロワーに熱いメッセージが送られるようになったが、そのうちちゃんとしたボットを作りたい。
とか前向きなreplyするやつ(謎)。
python-twitpicというものがあった。twitpicはデイレクトリになってて__init__.pyとかあるけど、直接twitpic.pyをimportする方向で。
#!/Usr/bin/env python
# -*- encoding:utf-8 -*-
import twitpic
twit = twitpic.TwitPicAPI('xxxx', 'xxxx')
twitpic_url = twit.upload('twitter.png', message='test from python', post_to_twitter=True)
print twitpic_url
数行で画像投稿しつつtwitterにもpostできる。
PythonでOAuthを試したかったのでtweepyを使ってみた。
easy_installじゃなくてgitから
git clone git://github.com/joshthecoder/tweepy.git
まずはBasic認証
>>> import tweepy >>> auth = tweepy.BasicAuthHandler("user", "password") >>> api = tweepy.API(auth) >>> api.update_status('hello from tweepy(Basic)') <tweepy.models.Status object at 0x13c8db0>
http://twitter.com/kzfm/status/9330123865
続いてOAuth。consumer_token,consumer_secretはあらかじめtwitterから取得しておく。
>>> import tweepy >>> consumer_token = "xxxxxxxxxxxxxx" >>> consumer_secret = "xxxxxxxxxxxxxxxx" >>> auth = tweepy.OAuthHandler(consumer_token, consumer_secret) >>> redirect_url = auth.get_authorization_url() >>> redirect_url
redirect_urlのURLにブラウザでアクセスして許可すると7桁の数字が表示されるのでそれを入力
>>> verifier = '1234567' >>> auth.get_access_token(verifier) <tweepy.oauth.OAuthToken object at 0x1393510> >>> key = auth.access_token.key >>> secret = auth.access_token.secret >>> auth = tweepy.OAuthHandler(consumer_token, consumer_secret) >>> auth.set_access_token(key, secret) >>> oauthapi = tweepy.API(auth) >>> oauthapi.update_status('hello from tweepy(OAuth)') <tweepy.models.Status object at 0x1397b50>
http://twitter.com/kzfm/status/9330367673
wsgioauthもいいかもとか思い始めたでござる。
ダイレクトメッセージを送れるかどうかで判断するみたいなつぶやきが流れてたので。
setでごにょれば良かろうと。
import twitter
api = twitter.Api(username='user',password='pass')
friends = set([u.name for u in api.GetFriends()])
followers = set([u.name for u in api.GetFollowers()])
print "follow and followed: " + ",".join(list(friends.intersection(followers)))
print "not follow but followed: " + ",".join(list(followers.difference(friends)))
print "follow but not followed: " + ",".join(list(friends.difference(followers)))
おは(ようを)あり(がとう)ではなくて おは(が)あり(ました)
つまり
isOha? :: Str -> Bool
なスクリプト。
#!/usr/bin/env python
# -*- encoding:utf-8 -*-
import twitter
api = twitter.Api(username='user',password='pass')
oha = [r.user.screen_name for r in api.GetReplies() \
if r.text.encode('utf-8').find('おは') > -1]
thx = "@" + " @".join(oha) + "おはありです"
status = api.PostUpdate(thx.decode('utf-8'))
pypiにあるtwitterじゃなくてpython-twitterを使いたかったので、既にインストールされてたtwitterモジュールはpythonモジュールのアンインストール - kokiyaの日記を参考に消した。
> library("RCurl")
> opts <- curlOptions(header = FALSE,
+ userpwd = "[user]:[pass]", netrc = FALSE)
> tweet <- function(status){
+ method <- "http://twitter.com/statuses/update.xml?status="
+ encoded_status <- URLencode(status)
+ request <- paste(method,encoded_status,sep = "")
+ postForm(request,.opts = opts)
+ }
> xx<-rnorm(2)
> tweet(paste(xx,collapse="|"))
SVMかなんかを利用して分類結果をつぶやくボットをつくっても面白いかも。