forked from devconcert/LINE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
347 lines (272 loc) · 9.13 KB
/
models.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# -*- coding: utf-8 -*-
"""
line.models
~~~~~~~~~~~
:copyright: (c) 2014 by Taehoon Kim.
:license: BSD, see LICENSE for more details.
"""
import json
import shutil
import requests
import tempfile
from time import time
from datetime import datetime
from curve.ttypes import Message, ContentType
class LineMessage:
"""LineMessage wrapper"""
def __init__(self, client, message):
self._client = client
self._message = message
self.id = message.id
self.text = message.text
self.hasContent = message.hasContent
self.contentType = message.contentType
self.contentPreview = message.contentPreview
self.contentMetadata = message.contentMetadata
self.sender = client.getContactOrRoomOrGroupById(message._from)
self.receiver = client.getContactOrRoomOrGroupById(message.to)
# toType
# 0: User
# 1: Room
# 2: Group
self.toType = message.toType
self.createdTime = datetime.fromtimestamp(message.createdTime/1000)
def __repr__(self):
try:
ContentTypeText = ContentType._VALUES_TO_NAMES[self.contentType]
except KeyError:
#print "*** Unknow Content Type", self.contentType
ContentTypeText = self.contentType
return 'LineMessage (contentType=%s, sender=%s, receiver=%s, msg="%s")' % (
ContentTypeText,
self.sender,
self.receiver,
self.text
)
class LineBase(object):
_messageBox = None
def sendMessage(self, text):
"""Send a message
:param text: text message to send
"""
try:
message = Message(to=self.id, text=text.encode('utf-8'))
self._client.sendMessage(message)
return True
except Exception as e:
raise e
def sendSticker(self,
stickerId = "13",
stickerPackageId = "1",
stickerVersion = "100",
stickerText="[null]"):
"""Send a sticker
:param stickerId: id of sticker
:param stickerPackageId: package id of sticker
:param stickerVersion: version of sticker
:param stickerText: text of sticker (default='[null]')
"""
try:
message = Message(to=self.id, text="")
message.contentType = ContentType.STICKER
message.contentMetadata = {
'STKID': stickerId,
'STKPKGID': stickerPackageId,
'STKVER': stickerVersion,
'STKTXT': stickerText,
}
self._client.sendMessage(message)
return True
except Exception as e:
raise e
def sendImage(self, path):
"""Send a image
:param path: local path of image to send
"""
message = Message(to=self.id, text=None)
message.contentType = ContentType.IMAGE
message.contentPreview = None
message.contentMetadata = None
message_id = self._client.sendMessage(message).id
files = {
'file': open(path, 'rb'),
}
params = {
'name': 'media',
'oid': message_id,
'size': len(open(path, 'rb').read()),
'type': 'image',
'ver': '1.0',
}
data = {
'params': json.dumps(params)
}
r = self._client.post_content('https://os.line.naver.jp/talk/m/upload.nhn', data=data, files=files)
if r.status_code != 201:
raise Exception('Upload image failure.')
#r.content
return True
def sendImageWithURL(self, url):
"""Send a image with given image url
:param url: image url to send
"""
path = '%s/pythonLine.data' % tempfile.gettempdir()
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(path, 'w') as f:
shutil.copyfileobj(r.raw, f)
else:
raise Exception('Download image failure.')
try:
self.sendImage(path)
except Exception as e:
raise e
def getRecentMessages(self, count=1):
"""Get recent messages
:param count: count of messages to get
"""
if self._messageBox:
messages = self._client.getRecentMessages(self._messageBox, count)
return messages
else:
self._messageBox = self._client.getMessageBox(self.id)
messages = self._client.getRecentMessages(self._messageBox, count)
return messages
def __lt__(self, other):
return self.id < other.id
class LineGroup(LineBase):
"""LineGroup wrapper
Attributes:
creator contact of group creator
members list of contact of group members
invitee list of contact of group invitee
>>> group = LineGroup(client, client.groups[0])
"""
id = None
name = None
is_joined = True
creator = None
members = []
invitee = []
def __init__(self, client, group=None, is_joined=True):
"""LineGroup init
:param client: LineClient instance
:param group: Group instace
:param is_joined: is a user joined or invited to a group
"""
self._client = client
self._group = group
self.id = group.id
self.name = group.name
self.is_joined = is_joined
try:
self.creator = LineContact(client, group.creator)
except:
self.creator = None
self.members = []
for member in group.members:
self.members.append(LineContact(client, member))
self.invitee = []
if group.invitee:
for member in group.invitee:
self.invitee.append(LineContact(client, member))
def acceptGroupInvitation(self):
if not self.is_joined:
self._client.acceptGroupInvitation(self)
return True
else:
raise Exception('You are already in group')
return False
def leave(self):
"""Leave group"""
if self.is_joined:
try:
self.leaveGroup(self)
return True
except:
return False
else:
raise Exception('You are not joined to group')
return False
def getMemberIds(self):
"""Get member ids of group"""
ids = [member.id for member in self.members]
return ids
def __repr__(self):
"""Name of Group and number of group members"""
if self.is_joined:
return '<LineGroup %s #%s>' % (self.name, len(self.members))
else:
return '<LineGroup %s #%s (invited)>' % (self.name, len(self.members))
class LineRoom(LineBase):
"""Chat room wrapper
Attributes:
contacts : Contact list of chat room
"""
def __init__(self, client, room):
"""LineContact init
:param client: LineClient instance
:param room: Room instace
"""
self._client = client
self._room = room
self.id = room.mid
self.contacts = []
for contact in room.contacts:
self.contacts.append(LineContact(client, contact))
def leave(self):
"""Leave room"""
try:
self.leaveRoom(self)
return True
except:
return False
def invite(self, contact):
"""Invite into group
:param contact: LineContact instance to invite
"""
def getContactIds(self):
"""Get contact ids of room"""
ids = [contact.id for contact in self.contacts]
return ids
def __repr__(self):
return '<LineRoom %s>' % (self.contacts)
class LineContact(LineBase):
"""LineContact wrapper
Attributes:
name display name of contact
statusMessage status message of contact
"""
def __init__(self, client, contact):
"""LineContact init
:param client: LineClient instance
:param contact: Conatct instace
"""
self._client = client
self._contact = contact
self.id = contact.mid
self.name = contact.displayName
self.statusMessage = contact.statusMessage
@property
def profileImage(self):
"""Link for profile image"""
return "http://dl.profile.line.naver.jp" + self._contact.picturePath
@property
def rooms(self):
"""Rooms that contact participates"""
rooms = []
for room in self._client.rooms:
if self.id in room.getContactIds():
rooms.append(room)
return rooms
@property
def groups(self):
"""Groups that contact participates"""
groups = []
for group in self._client.groups:
if self.id in group.getMemberIds():
groups.append(room)
return groups
def __repr__(self):
#return '<LineContact %s (%s)>' % (self.name, self.id)
return '<LineContact %s>' % (self.name)