chat.py
1.68 KB
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
import json
import urllib.request
import urllib.parse
import urllib.error
from django.conf import settings
from floraconcierge.errors import ApiError
class Chat():
URL = getattr(settings, 'FLORACONCIERGE_CHAT_URL', 'http://floraconcierge.com/:chat/')
SECRET = getattr(settings, 'FLORACONCIERGE_CHAT_SECRET', None)
chat_id = None
chat_token = None
def __init__(self, chat=0, name='Unknown name', mail='Unknown email'):
if chat:
self.chat_id = chat
chat_data = self.response('check_id')
self.chat_token = chat_data['token']
else:
chat_data = self.response('register', {'name': name, 'email': mail})
self.chat_id = chat_data['chat_id']
self.chat_token = chat_data['token']
# def send(self, message):
# return self.response('send', {'message': message.encode('utf-8')})
#
# def get(self, last_id):
# return self.response('get', {'last_id': last_id})
#
# def last_id(self):
# return self.response('last_id')
def response(self, action, post=None):
params = {
'_secret': self.SECRET,
'_action': action,
}
if action != 'register':
params['_chat_id'] = self.chat_id
if action != 'check_id':
params['_secret'] = self.chat_token
url = self.URL + '?' + urllib.parse.urlencode(params)
req = urllib.request.Request(url, urllib.parse.urlencode(post) if post else None)
result = urllib.request.urlopen(req).read()
result = json.loads(result)
if result.get('error'):
raise ApiError(result.get('error'))
return result['result']