-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmsging_api.py
537 lines (395 loc) · 14.9 KB
/
msging_api.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
import os
import json
import uuid
import requests
import jwt
from jwt.algorithms import RSAAlgorithm
import time
from datetime import datetime as dt
import base64
import hashlib
import hmac
from dotenv import load_dotenv
class AccessToken:
def __init__(self):
load_dotenv(override=True)
self.base_domain = 'https://api.line.me'
self.data_domain = 'https://api-data.line.me'
self.auth_uri = f'{self.base_domain}/oauth2/v2.1'
self.short_auth_uri = f'{self.base_domain}/v2/oauth'
self.channel_id = os.environ['channel_id']
self.client_secret = os.environ['client_secret']
def encode_jwt(self, token_exp=60*60*24*30):
private_key = {
'alg':os.environ['alg'],
'd':os.environ['d'],
'dp':os.environ['dp'],
'dq':os.environ['dq'],
'e':os.environ['e'],
'kty':os.environ['kty'],
'n':os.environ['n'],
'p':os.environ['p'],
'q':os.environ['q'],
'qi':os.environ['qi'],
'use':os.environ['use']
}
headers = {
'alg':'RS256',
'typ':'JWT',
'kid':os.environ['kid']
}
payload = {
'iss':self.channel_id,
'sub':self.channel_id,
'aud':'https://api.line.me/',
'exp':int(time.time())+(60*30),
'token_exp':token_exp
}
key = RSAAlgorithm.from_jwk(private_key)
JWT = jwt.encode(payload, key, algorithm='RSA256', headers=headers, json_encoder=None)
return JWT
def issue_access_token(self, JWT):
uri = f'{self.auth_uri}/token'
headers = {
'Content-Type':'application/x-www-form-urlencoded'
}
data = {
'grant_type':'client_credentials',
'client_assertion_type':'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
'client_assertion':JWT
}
r = requests.post(url=uri, headers=headers, data=data)
r_json = r.json()
if not 'error' in r_json:
return r_json
else:
status_code = r.status_code
r_json['status_code'] = r.status_code
return r_json
def verify_access_token(self, access_token):
uri = f'{self.auth_uri}/verify?access_token={access_token}'
r = requests.get(url=uri)
r_json = r.json()
if not 'error' in r_json:
return r_json
else:
status_code = r.status_code
r_json['status_code'] = status_code
return r_json
def get_valid_access_token(self, JWT):
uri = f'{self.auth_uri}/tokens/kid?client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer&client_assertion={JWT}'
r = requests.get(url=uri)
r_json = r.json()
if not 'error' in r_json:
return r_json
else:
status_code = r.status_code
r_json['status_code'] = status_code
return r_json
def revoke_access_token(self, access_token):
uri = f'{self.auth_uri}/revoke'
data = {
'client_id':self.channel_id,
'client_secret':self.client_secret,
'access_token':access_token
}
r = requests.post(url=uri, data = data)
def issue_short_access_token(self):
uri = f'{self.short_auth_uri}/accessToken'
headers = {
'Content-Type':'application/x-www-form-urlencoded'
}
data = {
'grant_type':'client_credentials',
'client_id':self.channel_id,
'client_secret':self.client_secret
}
r = requests.post(url=uri, headers=headers, data=data)
r_json = r.json()
if 'error' not in r_json:
return r_json
else:
status_code = r.status_code
r_json['status_code'] = status_code
return r_json
def verify_short_access_token(self, access_token):
uri = f'{self.short_auth_uri}/verify'
headers = {
'Content-Type':'application/x-www-form-urlencoded'
}
data = {
'access_token':access_token
}
r = requests.post(url=uri, headers=headers, data=data)
r_json = r.json()
if 'error' not in r_json:
return r_json
else:
status_code = r.status_code
r_json['status_code'] = status_code
return r_json
def revoke_short_access_token(self, access_token):
uri = f'{self.short_auth_uri}/revoke'
headers = {
'Content-Type':'application/x-www-form-urlencoded'
}
data = {
'access_token':access_token
}
r = requests.post(url=uri, headers=headers, data=data)
class VerifySignature(AccessToken):
def __init__(self):
super().__init__()
def verify_signature(self, l_signature, data):
client_secret = self.client_secret
hash_ = hmac.new(client_secret.encode('utf-8'), data, hashlib.sha256).digest()
b_signature = base64.b64encode(hash_)
signature = b_signature.decode('utf-8')
if l_signature == signature:
return True
else:
return False
class Message(AccessToken):
def __init__(self):
super().__init__()
self.msg_uri = f'{self.base_domain}/v2/bot/message'
def _gen_retry_key(self):
retry_key = str(uuid.uuid4())
return retry_key
def send_messages(self, access_token, messages, send_type, retry_key=False, reply_token=None, to=None, narrows=None):
uri = f'{self.msg_uri}/{send_type}'
headers = {
'Content-Type':'application/json',
'Authorization':f'Bearer {access_token}'
}
data = {
'messages':messages
}
if retry_key:
x_line_retry_key = self._gen_retry_key()
headers['X-Line-Retry-Key'] = x_line_retry_key
if reply_token:
data['replyToken'] = reply_token
if to:
data['to'] = to
if narrows:
data['recipient'] = narrows['recipient']
data['filter'] = narrows['filter']
data['limit'] = narrows['limit']
r = requests.post(url=uri, headers=headers, data=json.dumps(data))
r_json = r.json()
if not 'error' in r_json:
return r_json
else:
status_code = r.status_code
r_json['status_code'] = r.status_code
return r_json
class Richmenu(AccessToken):
def __init__(self):
super().__init__()
self.base_richmenu_uri = f'{self.base_domain}/v2/bot/richmenu'
self.data_richmenu_uri = f'{self.data_domain}/v2/bot/richmenu'
def create_richmenu(self, access_token, data):
uri = f'{self.base_richmenu_uri}'
headers = {
'Authorization':f'Bearer {access_token}',
'Content-Type':'application/json'
}
r = requests.post(url=uri, headers=headers, data=json.dumps(data))
r_json = r.json()
if not 'error' in r_json:
richmenu_id = r_json['richMenuId']
return richmenu_id
else:
status_code = r.status_code
r_json['status_code'] = r.status_code
return r_json
def upload_richmenu(self, access_token, richmenu_id, f_path):
uri = f'{self.data_richmenu_uri}/{richmenu_id}/content'
headers = {
'Authorization':f'Bearer {access_token}',
'Content-Type':'image/jpeg'
}
with open(f_path, 'rb') as f:
data = f.read()
r = requests.post(url=uri, headers=headers, data=data)
def download_richmenu(self, access_token, richmenu_id, dl_path):
uri = f'{self.data_richmenu_uri}/{richmenu_id}/content'
headers = {
'Authorization':f'Bearer {access_token}'
}
r = requests.get(url=uri, headers=headers)
status_code = r.status_code
if status_code == 200:
now = dt.now()
t_stamp = now.strftime('%Y%m%d%H%M%S')
with open(f'{dl_path}/richmenu_{t_stamp}.jpg', 'wb') as f:
f.write(r.content)
def get_richmenu_array(self, access_token):
uri = f'{self.base_richmenu_uri}/list'
headers = {
'Authorization':f'Bearer {access_token}'
}
r = requests.get(url=uri, headers=headers)
r_json = r.json()
if 'error' not in r_json:
richmenus = r_json['richmenus']
return richmenus
else:
status_code = r.status_code
r_json['status_code'] = r.status_code
return r_json
def get_richmenu(self, access_token, richmenu_id):
uri = f'{self.base_richmenu_uri}/{richmenu_id}'
headers = {
'Authorization':f'Bearer {access_token}'
}
r = requests.get(url=uri, headers=headers)
r_json = r.json()
if not 'error' in r_json:
return r_json
else:
status_code = r.status_code
r_json['status_code'] = r.status_code
return r_json
def delete_richmenu(self, access_token, richmenu_id):
uri = f'{self.base_richmenu_uri}/{richmenu_id}'
headers = {
'Authorization':f'Bearer {access_token}'
}
r = requests.delete(url=uri, headers=headers)
status_code = r.status_code
if status_code != 200:
r_json = r.json()
r_json['status_code'] = status_code
return r_json
def default_richmenu(self, access_token, richmenu_id):
uri = f'{self.base_domain}/v2/bot/user/all/richmenu/{richmenu_id}'
headers = {
'Authorization':f'Bearer {access_token}'
}
r = requests.post(url=uri, headers=headers)
status_code = r.status_code
if status_code != 200:
r_json = r.json()
r_json['status_code'] = status_code
return r_json
def create_richmenu_alias(self, access_token, richmenu_id, richmenu_alias):
uri = f'{self.base_domain}/v2/bot/richmenu/alias'
headers = {
'Authorization':f'Bearer {access_token}',
'Content-Type':'application/json'
}
data = {
'richMenuAliasId':richmenu_alias,
'richMenuId':richmenu_id
}
r = requests.post(url=uri, headers=headers, data=json.dumps(data))
status_code = r.status_code
if status_code != 200:
r_json = r.json()
r_json['status_code'] = status_code
return r_json
def link_richmenu(self, access_token, user_id, richmenu_id):
uri = f'{self.base_domain}/v2/bot/user/{user_id}/richmenu/{richmenu_id}'
headers = {
'Authorization':f'Bearer {access_token}'
}
r = requests.post(url=uri, headers=headers)
status_code = r.status_code
if status_code != 200:
r_json = r.json()
r_json['status_code'] = status_code
return r_json
def delete_richmenu_alias(self, access_token, richmenu_alias):
uri = f'{self.base_domain}/v2/bot/richmenu/alias/{richmenu_alias}'
headers = {
'Authorization':f'Bearer {access_token}'
}
r = requests.delete(url=uri, headers=headers)
status_code = r.status_code
if status_code != 200:
r_json = r.json()
r_json['status_code'] = status_code
return r_json
def update_richmenu_alias(self, access_token, richmenu_id, richmenu_alias):
uri = f'{self.base_domain}/v2/bot/richmenu/alias/{richmenu_alias}'
headers = {
'Authorization':f'Bearer {access_token}',
'Content-Type':'application/json'
}
data = {
'richMenuId':richmenu_id
}
r = requests.post(url=uri, headers=headers, data=json.dumps(data))
status_code = r.status_code
if status_code != 200:
r_json = r.json()
r_json['status_code'] = status_code
return r_json
def get_richmenu_alias(self, access_token, richmenu_alias):
uri = f'{self.base_domain}/v2/bot/richmenu/alias/{richmenu_alias}'
headers = {
'Authorization':f'Bearer {access_token}'
}
r = requests.get(url=uri, headers=headers)
status_code = r.status_code
r_json = r.json()
if status_code != 200:
r_json['status_code'] = status_code
return r_json
else:
return r_json
def get_richmenu_alias_list(self, access_token):
uri = f'{self.base_domain}/v2/bot/richmenu/alias/list'
headers = {
'Authorization':f'Bearer {access_token}'
}
r = requests.get(url=uri, headers=headers)
status_code = r.status_code
r_json = r.json()
if status_code != 200:
r_json['status_code'] = status_code
return r_json
else:
alias_list = r_json['aliases']
return alias_list
class GetUserData(AccessToken):
def __init__(self):
super().__init__()
self.base_prof_uri = f'{self.base_domain}/v2/bot/profile'
def get_user_prof(self, access_token, user_id):
uri = f'{self.base_prof_uri}/{user_id}'
headers = {
'Authorization':f'Bearer {access_token}'
}
r = requests.get(url=uri, headers=headers)
status_code = r.status_code
r_json = r.json()
if status_code != 200:
r_json['status_code'] = status_code
return r_json
return r_json
def get_users_list(self, access_token, limit):
user_ids = list()
uri = f'{self.base_domain}/v2/bot/followers/ids'
headers = {
'Authorization':f'Bearer {access_token}'
}
data = {
'limit':limit
}
while True:
r = requests.get(url=uri, headers=headers, data=json.dumps(data))
status_code = r.status_code
r_json = r.json()
if status_code != 200:
r_json['status_code'] = status_code
return r_json
user_ids.append(r_json['userIds'])
if 'next' in r_json:
start_id = r_json['next']
data['start'] = start_id
else:
break
return user_ids