파이썬에서 트위터 날리기 tweepy

Posted at 2011/03/31 17:11// Posted in python/py-sns

tweepy 를 사용해서 트위터 OAuth 로그인을 한 다음 타임 라인을 보는 예제입니다~


USERNAME = "아이디"
PASSWORD = "비밀번호"

import tweepy

import re
roToken = re.compile("<\w+|>|/>|</\w+>|\w+|=|\"[^\"]+\"")

def GetTagAttrd(tokens, beginTag, endTag, curIndex, endIndex):
itokens = []
try:
curIndex = tokens.index(beginTag, curIndex)
except ValueError:
return curIndex, None

if curIndex >= endIndex:
return endIndex, None

while tokens[curIndex] != endTag:
itokens.append(tokens[curIndex])
curIndex += 1

return curIndex, dict(zip(itokens[1::3], [val[1:-1] for val in itokens[3::3]]))

from urllib import *
from urllib2 import *

def Main():
CONSUMER_KEY = '트위터_앱_키'
CONSUMER_SECRET = '트위터_앱_시크릿'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
aurl = auth.get_authorization_url()
data = urlopen(aurl).read()
lines = data.splitlines()
tokens = []
for line in lines:
tokens += roToken.findall(line)

curIndex, formd = GetTagAttrd(tokens, "<form", ">", 0, len(tokens))
endIndex = tokens.index("</form>", curIndex)
actionURL = formd["action"]

valued = {}
while True:
curIndex, inputd = GetTagAttrd(tokens, "<input", "/>", curIndex, endIndex)
if inputd:
if inputd["type"] == "hidden":
valued[inputd["name"]] = inputd["value"]
elif inputd["type"] == "text":
valued[inputd["name"]] = USERNAME
elif inputd["type"] == "password":
valued[inputd["name"]] = PASSWORD
elif inputd["type"] == "submit":
valued["submit"] = inputd["value"]
else:
print inputd
else:
break

params = urlencode(valued)
req = Request(actionURL, params)
res = urlopen(req)
data = res.read()
lines = data.splitlines()
tokens = []
for index, line in enumerate(lines):
if "div" in line and "oauth_pin" in line:
index += 1
break

verifier = lines[index].strip()
auth.get_access_token(verifier)

api = tweepy.API(auth)

if 0:
api.update_status(u"~tweepy test")
else:
for s in api.user_timeline():
print s.text.encode("utf8")

Main()
이올린에 북마크하기(0) 이올린에 추천하기(0)
2011/03/31 17:11 2011/03/31 17:11