-
Notifications
You must be signed in to change notification settings - Fork 2
/
twitter.py
41 lines (33 loc) · 1 KB
/
twitter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# coding: UTF-8
import re
import tweepy
import logging
import traceback
import threading
import encoder
import kiritan
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_TOKEN = ''
ACCESS_SECRET = ''
# ツイートを拾ってencoderに投げる
class StreamListener(tweepy.StreamListener):
def on_status(self, status):
logging.info("Receive tweet from @%s" % status.user.screen_name)
text = re.sub(r'https://t.co/\w+', 'URL', "%s\n%s\n%s" % (status.user.name, status.user.screen_name, status.text))
encoder.enqueue(kiritan.talk(text))
def on_error(self, status_code):
logging.error("Twitter returns code %d" % status_code)
return False
# Streamリスナを起動
def __listen():
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
while True:
try:
stream = tweepy.Stream(auth=auth, listener=StreamListener())
stream.userstream()
except:
logging.error(traceback.format_exc())
def listen():
threading.Thread(target=__listen).start()