-
Notifications
You must be signed in to change notification settings - Fork 0
/
lingr.py
106 lines (91 loc) · 2.78 KB
/
lingr.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson
import urllib
import urllib2
class Lingr(object):
__URL_BASE__ = 'http://lingr.com/api/'
__URL_BASE_OBSERVE__ = 'http://lingr.com:8080/api/'
def __init__(self, user, password):
self.user = user
self.password = password
self.counter = 0
def create_session(self):
data = self.post('session/create', {
'user': self.user,
'password': self.password
})
if data:
self.session = data['session']
self.nickname = data['nickname']
return data
def get_rooms(self):
data = self.get('user/get_rooms', {
'session': self.session
})
if data:
self.rooms = data['rooms']
return data
def subscribe(self, room=None, reset='true'):
if not room:
room = ','.join(self.rooms)
data = self.post('room/subscribe', {
'session': self.session,
'room': room,
'reset': reset
})
if data:
self.counter = data['counter']
return data
def observe(self):
data = self.get('event/observe', {
'session': self.session,
'counter': self.counter
})
if 'counter' in data:
self.counter = data['counter']
return data
def say(self, room, text):
data = self.post('room/say', {
'session': self.session,
'room': room,
'nickname': self.nickname,
'text': text
})
return data
def post(self, path, params):
r = self.get_opener().open(self.get_url(path),
urllib.urlencode(params))
return self.loads(r.read())
def get(self, path, params):
full_url = self.get_url(path) + '?' + urllib.urlencode(params)
r = self.get_opener().open(full_url)
return self.loads(r.read())
def loads(self, json):
data = simplejson.loads(json)
if data['status'] == 'ok':
return data
else:
print 'error'
print data
return None
def get_url(self, path):
url = self.__URL_BASE__
if path == 'event/observe':
url = self.__URL_BASE_OBSERVE__
return url + path
def get_opener(self):
opener = urllib2.build_opener()
opener.addheaders = [
('User-agent', 'lingrpy(https://github.com/narusemotoki/lingrpy)')
]
return opener
def stream(self):
self.create_session()
self.get_rooms()
self.subscribe()
while True:
obj = self.observe()
if 'events' in obj:
for event in obj['events']:
yield event