Created
April 25, 2011 08:59
-
-
Save PyYoshi/940295 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
from tweepy import OAuthHandler, Stream, StreamListener, TweepError, API | |
import urllib | |
from wsgiref.simple_server import make_server | |
import threading | |
import ConfigParser | |
import webbrowser | |
import os | |
import sys | |
CONSUMER_KEY = "" | |
CONSUMER_SECRET = "" | |
CALLBACK_URL = "http://127.0.0.1:8923/login/" | |
SETTINGS_FILE = "settings.ini" | |
SETTINGS_FILE_PATH = os.path.join(os.path.dirname(__file__), SETTINGS_FILE) | |
auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET, CALLBACK_URL) | |
config = ConfigParser.ConfigParser() | |
#クラス | |
class UserStream(Stream): | |
def userstream(self, count=None, follow=None, track=None, async=False, locations=None, secure=True): | |
self.parameters = {"delimited": "length", } | |
self.headers['Content-type'] = "application/x-www-form-urlencoded" | |
if self.running: | |
raise TweepError('Stream object already connected!') | |
self.scheme = "https" | |
self.url = '/2/user.json' | |
self.host='userstream.twitter.com' | |
if count: | |
self.url += '&count=%s' % count | |
if follow: | |
self.parameters['follow'] = ','.join(map(str, follow)) | |
if track: | |
self.parameters['track'] = ','.join(map(str, track)) | |
if locations and len(locations) > 0: | |
assert len(locations) % 4 == 0 | |
self.parameters['locations'] = ','.join(['%.2f' % l for l in locations]) | |
self.body = urllib.urlencode(self.parameters) | |
self._start(async) | |
class CustomeStreamListener(StreamListener): | |
def on_status(self, status): | |
""" | |
ステータス取得時のイベントハンドラ | |
""" | |
screen_name = status.user.screen_name | |
text = status.text | |
dispText = screen_name + ': ' + text | |
print dispText.encode('utf-8') | |
def get_atoken(env,res): | |
if env['PATH_INFO']=='/login/': | |
if env['REQUEST_METHOD']=='GET': | |
QUERY_STRING = env['QUERY_STRING'] | |
if QUERY_STRING: | |
tmp = QUERY_STRING.split('&') | |
oauth_token = tmp[0].split('=')[1] | |
oauth_verifier = tmp[1].split('=')[1] | |
#魔法の1行(笑 | |
threading.Thread(target=httpd.shutdown).start() | |
auth.set_request_token(auth.request_token.key, auth.request_token.secret) | |
try: | |
auth.get_access_token(oauth_verifier) | |
config.add_section('TOKENS') | |
config.set('TOKENS', 'ACCESS_TOKEN', auth.access_token.key) | |
config.set('TOKENS', 'ACCESS_SECRET_TOKEN', auth.access_token.secret) | |
#設定の書き出し | |
fp = open(SETTINGS_FILE_PATH, 'w') | |
config.write(fp) | |
fp.close() | |
print 'Authenticated Successfully!' | |
res('200 OK',[('Content-type','text/html')]) | |
html = """ | |
<html> | |
<head> | |
<title>Authenticated Successfully!</title> | |
</head> | |
<body> | |
Authenticated Successfully! | |
</body> | |
</html> | |
""" | |
return html | |
except TweepError: | |
print 'Error! Failed to get access token.' | |
res('401 Unauthorized',[('Content-type','text/html')]) | |
html = """ | |
<html> | |
<head> | |
<title>Unauthorized!</title> | |
</head> | |
<body> | |
Unauthorized! | |
</body> | |
</html> | |
""" | |
return html | |
#ログイン | |
def login(): | |
pass | |
def userstream(atoken, astoken): | |
try: | |
auth.set_access_token(atoken, astoken) | |
stream = UserStream(auth, CustomeStreamListener(api=API(auth_handler=auth))) | |
stream.timeout = None | |
stream.userstream() | |
except TweepError: | |
print 'Error! Failed to login.' | |
#ログアウト | |
def logout(): | |
try: | |
os.remove(SETTINGS_FILE_PATH) | |
except : | |
pass | |
def main(): | |
try: | |
config.read(SETTINGS_FILE_PATH) | |
atoken = config.get('TOKENS', 'ACCESS_TOKEN') | |
astoken = config.get('TOKENS', 'ACCESS_SECRET_TOKEN') | |
except ConfigParser.NoSectionError: | |
atoken = None | |
astoken = None | |
if atoken != None: | |
if astoken != None: | |
userstream(atoken, astoken) | |
else: | |
try: | |
auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET, CALLBACK_URL) | |
redirect_url = auth.get_authorization_url() | |
#ここの処理は認証用URLをウェブブラウザで開くようにしている。適宜要変更 | |
try: | |
if webbrowser.open(redirect_url) == False: | |
raise webbrowser.Error | |
except webbrowser.Error: | |
sys.exit(1) | |
httpd = make_server('',8923,get_atoken) | |
httpd.serve_forever() | |
except TweepError: | |
print 'Error! Failed to get request token.' | |
if __name__ == '__main__': | |
try: | |
main() | |
except KeyboardInterrupt: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment