koleben’s blog

モノ・時間・情報からの自由になりたい。スローでイージーな暮らしを目指して

GoogleAppEngineでTwitter bot

GoogleAppEngineでTwitter botを作ってみました。

…といっても作ったレベルではありません、またちょっとググったらまんまソースコードで案内してくれてました。
oAuthのところがうまく動かなかったのでちょっと変更しただけです。

Twitterのサイトでアプリ登録をします。

ここで、consumer keyとconsumer key secretをコピーしときます。

Access tokenとAccess token secretを取得します。

このスクリプトAccess tokenとAccess token secretがわかります。
Botなのでいちいちユーザー認証をする必要はありませんので。

#!/opt/local/bin/perl
use strict;
use warnings;
use utf8;
use Net::Twitter;
my $consumer_key = '[コンシューマーキー]';
my $consumer_key_secret = '[コンシューマーキーシークレット]';
my $nt = Net::Twitter->new(
traits          => ['API::REST', 'OAuth'],
consumer_key    => $consumer_key,
consumer_secret => $consumer_key_secret,
);
print 'access this url by bot account : '.$nt->get_authorization_url."\n";
print 'input verifier PIN : ';
my $verifier = <STDIN>;
chomp $verifier;
my $token = $nt->request_token;
my $token_secret = $nt->request_token_secret;
$nt->request_token($token);
$nt->request_token_secret($token_secret);
my($at, $ats) = $nt->request_access_token(verifier => $verifier);
print "Access token : ".$at."\n";
print "Access token secret : ".$ats."\n";

main.py

main.pyのソースコードです。
data.txtからテキストを読んで日付と一致するテキストをつぶやきます。
twitter.pyのバージョンは0.8です。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import cgi
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import logging, cgi,time
import datetime
import twitter
from datetime import datetime
class PostStatus(webapp.RequestHandler):
def get(self):
api = twitter.Api(
consumer_key='[コンシューマーキー]',
consumer_secret='[コンシューマーキーシークレット]',
access_token_key='[アクセストークンキー]',
access_token_secret='[アクセストークンキーシークレット]',
input_encoding=None,
request_headers=None,
cache=None,
shortner=None,
base_url=None,
use_gzip_compression=False,
debugHTTP=False
)
f = open('./data.txt')
today = datetime.now()
textbuf = ""
while 1:
line = f.readline()
if not line: break
datetext, text = line.split(',')
mon, day = datetext.split('/')
msg = text
if  int(mon) == today.month and int(day) == today.day :
#msg = text+" "+str(today.second)
msg = text;
status = api.PostUpdate(msg)
break
self.response.out.write('<html><head><title>twit</title></head><body>twit:'+msg+'</body></html>')
application = webapp.WSGIApplication([('/', PostStatus)], debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()