This repository has been archived by the owner on Jul 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 247
/
__init__.py
667 lines (516 loc) · 23 KB
/
__init__.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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
# Copyright 2015 Oktay Sancak
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import requests
from slacker.utils import get_item_id_by_name
API_BASE_URL = 'https://slack.com/api/{api}'
DEFAULT_TIMEOUT = 10
__all__ = ['Error', 'Response', 'BaseAPI', 'API', 'Auth', 'Users', 'Groups',
'Channels', 'Chat', 'IM', 'IncomingWebhook', 'Search', 'Files',
'Stars', 'Emoji', 'Presence', 'RTM', 'Team', 'Reactions', 'Pins',
'UserGroups', 'UserGroupsUsers', 'MPIM', 'OAuth', 'Slacker']
class Error(Exception):
pass
class Response(object):
def __init__(self, body):
self.raw = body
self.body = json.loads(body)
self.successful = self.body['ok']
self.error = self.body.get('error')
class BaseAPI(object):
def __init__(self, token=None, timeout=DEFAULT_TIMEOUT):
self.token = token
self.timeout = timeout
def _request(self, method, api, **kwargs):
if self.token:
kwargs.setdefault('params', {})['token'] = self.token
response = method(API_BASE_URL.format(api=api),
timeout=self.timeout,
**kwargs)
response.raise_for_status()
response = Response(response.text)
if not response.successful:
raise Error(response.error)
return response
def get(self, api, **kwargs):
return self._request(requests.get, api, **kwargs)
def post(self, api, **kwargs):
return self._request(requests.post, api, **kwargs)
class API(BaseAPI):
def test(self, error=None, **kwargs):
if error:
kwargs['error'] = error
return self.get('api.test', params=kwargs)
class Auth(BaseAPI):
def test(self):
return self.get('auth.test')
class Users(BaseAPI):
def info(self, user):
return self.get('users.info', params={'user': user})
def list(self, presence=False):
return self.get('users.list', params={'presence': int(presence)})
def set_active(self):
return self.post('users.setActive')
def get_presence(self, user):
return self.get('users.getPresence', params={'user': user})
def set_presence(self, presence):
assert presence in Presence.TYPES, 'Invalid presence type'
return self.post('users.setPresence', data={'presence': presence})
def get_user_id(self, user_name):
members = self.list().body['members']
return get_item_id_by_name(members, user_name)
class Groups(BaseAPI):
def create(self, name):
return self.post('groups.create', data={'name': name})
def create_child(self, channel):
return self.post('groups.createChild', data={'channel': channel})
def info(self, channel):
return self.get('groups.info', params={'channel': channel})
def list(self, exclude_archived=None):
return self.get('groups.list',
params={'exclude_archived': exclude_archived})
def history(self, channel, latest=None, oldest=None, count=None,
inclusive=None):
return self.get('groups.history',
params={
'channel': channel,
'latest': latest,
'oldest': oldest,
'count': count,
'inclusive': inclusive
})
def invite(self, channel, user):
return self.post('groups.invite',
data={'channel': channel, 'user': user})
def kick(self, channel, user):
return self.post('groups.kick',
data={'channel': channel, 'user': user})
def leave(self, channel):
return self.post('groups.leave', data={'channel': channel})
def mark(self, channel, ts):
return self.post('groups.mark', data={'channel': channel, 'ts': ts})
def rename(self, channel, name):
return self.post('groups.rename',
data={'channel': channel, 'name': name})
def archive(self, channel):
return self.post('groups.archive', data={'channel': channel})
def unarchive(self, channel):
return self.post('groups.unarchive', data={'channel': channel})
def open(self, channel):
return self.post('groups.open', data={'channel': channel})
def close(self, channel):
return self.post('groups.close', data={'channel': channel})
def set_purpose(self, channel, purpose):
return self.post('groups.setPurpose',
data={'channel': channel, 'purpose': purpose})
def set_topic(self, channel, topic):
return self.post('groups.setTopic',
data={'channel': channel, 'topic': topic})
class Channels(BaseAPI):
def create(self, name):
return self.post('channels.create', data={'name': name})
def info(self, channel):
return self.get('channels.info', params={'channel': channel})
def list(self, exclude_archived=None):
return self.get('channels.list',
params={'exclude_archived': exclude_archived})
def history(self, channel, latest=None, oldest=None, count=None,
inclusive=None):
return self.get('channels.history',
params={
'channel': channel,
'latest': latest,
'oldest': oldest,
'count': count,
'inclusive': inclusive
})
def mark(self, channel, ts):
return self.post('channels.mark',
data={'channel': channel, 'ts': ts})
def join(self, name):
return self.post('channels.join', data={'name': name})
def leave(self, channel):
return self.post('channels.leave', data={'channel': channel})
def invite(self, channel, user):
return self.post('channels.invite',
data={'channel': channel, 'user': user})
def kick(self, channel, user):
return self.post('channels.kick',
data={'channel': channel, 'user': user})
def rename(self, channel, name):
return self.post('channels.rename',
data={'channel': channel, 'name': name})
def archive(self, channel):
return self.post('channels.archive', data={'channel': channel})
def unarchive(self, channel):
return self.post('channels.unarchive', data={'channel': channel})
def set_purpose(self, channel, purpose):
return self.post('channels.setPurpose',
data={'channel': channel, 'purpose': purpose})
def set_topic(self, channel, topic):
return self.post('channels.setTopic',
data={'channel': channel, 'topic': topic})
def get_channel_id(self, channel_name):
channels = self.list().body['channels']
return get_item_id_by_name(channels, channel_name)
class Chat(BaseAPI):
def post_message(self, channel, text, username=None, as_user=None,
parse=None, link_names=None, attachments=None,
unfurl_links=None, unfurl_media=None, icon_url=None,
icon_emoji=None):
# Ensure attachments are json encoded
if attachments:
if isinstance(attachments, list):
attachments = json.dumps(attachments)
return self.post('chat.postMessage',
data={
'channel': channel,
'text': text,
'username': username,
'as_user': as_user,
'parse': parse,
'link_names': link_names,
'attachments': attachments,
'unfurl_links': unfurl_links,
'unfurl_media': unfurl_media,
'icon_url': icon_url,
'icon_emoji': icon_emoji
})
def update(self, channel, ts, text):
self.post('chat.update',
data={'channel': channel, 'ts': ts, 'text': text})
def delete(self, channel, ts):
self.post('chat.delete', data={'channel': channel, 'ts': ts})
class IM(BaseAPI):
def list(self):
return self.get('im.list')
def history(self, channel, latest=None, oldest=None, count=None,
inclusive=None):
return self.get('im.history',
params={
'channel': channel,
'latest': latest,
'oldest': oldest,
'count': count,
'inclusive': inclusive
})
def mark(self, channel, ts):
return self.post('im.mark', data={'channel': channel, 'ts': ts})
def open(self, user):
return self.post('im.open', data={'user': user})
def close(self, channel):
return self.post('im.close', data={'channel': channel})
class MPIM(BaseAPI):
def open(self, users):
if isinstance(users, (tuple, list)):
users = ','.join(users)
return self.post('mpim.open', data={'user': users})
def close(self, channel):
return self.post('mpim.close', data={'channel': channel})
def mark(self, channel, ts):
return self.post('mpim.mark', data={'channel': channel, 'ts': ts})
def list(self):
return self.get('mpim.list')
def history(self, channel, latest=None, oldest=None, inclusive=False,
count=None, unreads=False):
return self.get('mpim.history',
params={
'channel': channel,
'latest': latest,
'oldest': oldest,
'inclusive': int(inclusive),
'count': count,
'unreads': int(unreads)
})
class Search(BaseAPI):
def all(self, query, sort=None, sort_dir=None, highlight=None, count=None,
page=None):
return self.get('search.all',
params={
'query': query,
'sort': sort,
'sort_dir': sort_dir,
'highlight': highlight,
'count': count,
'page': page
})
def files(self, query, sort=None, sort_dir=None, highlight=None,
count=None, page=None):
return self.get('search.files',
params={
'query': query,
'sort': sort,
'sort_dir': sort_dir,
'highlight': highlight,
'count': count,
'page': page
})
def messages(self, query, sort=None, sort_dir=None, highlight=None,
count=None, page=None):
return self.get('search.messages',
params={
'query': query,
'sort': sort,
'sort_dir': sort_dir,
'highlight': highlight,
'count': count,
'page': page
})
class Files(BaseAPI):
def list(self, user=None, ts_from=None, ts_to=None, types=None,
count=None, page=None):
return self.get('files.list',
params={
'user': user,
'ts_from': ts_from,
'ts_to': ts_to,
'types': types,
'count': count,
'page': page
})
def info(self, file_, count=None, page=None):
return self.get('files.info',
params={'file': file_, 'count': count, 'page': page})
def upload(self, file_, content=None, filetype=None, filename=None,
title=None, initial_comment=None, channels=None):
with open(file_, 'rb') as f:
if isinstance(channels, (tuple, list)):
channels = ','.join(channels)
return self.post('files.upload',
data={
'content': content,
'filetype': filetype,
'filename': filename,
'title': title,
'initial_comment': initial_comment,
'channels': channels
},
files={'file': f})
def delete(self, file_):
return self.post('files.delete', data={'file': file_})
class Stars(BaseAPI):
def list(self, user=None, count=None, page=None):
return self.get('stars.list',
params={'user': user, 'count': count, 'page': page})
class Emoji(BaseAPI):
def list(self):
return self.get('emoji.list')
class Presence(BaseAPI):
AWAY = 'away'
ACTIVE = 'active'
TYPES = (AWAY, ACTIVE)
def set(self, presence):
assert presence in Presence.TYPES, 'Invalid presence type'
return self.post('presence.set', data={'presence': presence})
class RTM(BaseAPI):
def start(self):
return self.get('rtm.start')
class Team(BaseAPI):
def info(self):
return self.get('team.info')
def access_logs(self, count=None, page=None):
return self.get('team.accessLogs',
params={'count': count, 'page': page})
class Reactions(BaseAPI):
def add(self, name, file_=None, file_comment=None, channel=None,
timestamp=None):
# One of file, file_comment, or the combination of channel and timestamp
# must be specified
assert (file_ or file_comment) or (channel and timestamp)
return self.post('reactions.add',
data={
'name': name,
'file': file_,
'file_comment': file_comment,
'channel': channel,
'timestamp': timestamp,
})
def get(self, file_=None, file_comment=None, channel=None, timestamp=None,
full=None):
return super(Reactions, self).get('reactions.get',
params={
'file': file_,
'file_comment': file_comment,
'channel': channel,
'timestamp': timestamp,
'full': full,
})
def list(self, user=None, full=None, count=None, page=None):
return super(Reactions, self).get('reactions.list',
params={
'user': user,
'full': full,
'count': count,
'page': page,
})
def remove(self, name, file_=None, file_comment=None, channel=None,
timestamp=None):
# One of file, file_comment, or the combination of channel and timestamp
# must be specified
assert (file_ or file_comment) or (channel and timestamp)
return self.post('reactions.remove',
data={
'name': name,
'file': file_,
'file_comment': file_comment,
'channel': channel,
'timestamp': timestamp,
})
class Pins(BaseAPI):
def add(self, channel, file_=None, file_comment=None, timestamp=None):
# One of file, file_comment, or timestamp must also be specified
assert file_ or file_comment or timestamp
return self.post('pins.add',
data={
'channel': channel,
'file': file_,
'file_comment': file_comment,
'timestamp': timestamp,
})
def remove(self, channel, file_=None, file_comment=None, timestamp=None):
# One of file, file_comment, or timestamp must also be specified
assert file_ or file_comment or timestamp
return self.post('pins.remove',
data={
'channel': channel,
'file': file_,
'file_comment': file_comment,
'timestamp': timestamp,
})
def list(self, channel):
return self.get('pins.list', params={'channel': channel})
class UserGroupsUsers(BaseAPI):
def list(self, usergroup, include_disabled=None):
if isinstance(include_disabled, bool):
include_disabled = int(include_disabled)
return self.get('usergroups.users.list', params={
'usergroup': usergroup,
'include_disabled': include_disabled,
})
def update(self, usergroup, users, include_count=None):
if isinstance(users, (tuple, list)):
users = ','.join(users)
if isinstance(include_count, bool):
include_count = int(include_count)
return self.post('usergroups.users.update', data={
'usergroup': usergroup,
'users': users,
'include_count': include_count,
})
class UserGroups(BaseAPI):
def __init__(self, *args, **kwargs):
super(UserGroups, self).__init__(*args, **kwargs)
self._users = UserGroupsUsers(*args, **kwargs)
@property
def users(self):
return self._users
def list(self, include_disabled=None, include_count=None, include_users=None):
if isinstance(include_disabled, bool):
include_disabled = int(include_disabled)
if isinstance(include_count, bool):
include_count = int(include_count)
if isinstance(include_users, bool):
include_users = int(include_users)
return self.get('usergroups.list', params={
'include_disabled': include_disabled,
'include_count': include_count,
'include_users': include_users,
})
def create(self, name, handle=None, description=None, channels=None,
include_count=None):
if isinstance(channels, (tuple, list)):
channels = ','.join(channels)
if isinstance(include_count, bool):
include_count = int(include_count)
return self.post('usergroups.create', data={
'name': name,
'handle': handle,
'description': description,
'channels': channels,
'include_count': include_count,
})
def update(self, usergroup, name=None, handle=None, description=None,
channels=None, include_count=None):
if isinstance(channels, (tuple, list)):
channels = ','.join(channels)
if isinstance(include_count, bool):
include_count = int(include_count)
return self.post('usergroups.update', data={
'usergroup': usergroup,
'name': name,
'handle': handle,
'description': description,
'channels': channels,
'include_count': include_count,
})
def disable(self, usergroup, include_count=None):
if isinstance(include_count, bool):
include_count = int(include_count)
return self.post('usergroups.disable', data={
'usergroup': usergroup,
'include_count': include_count,
})
def enable(self, usergroup, include_count=None):
if isinstance(include_count, bool):
include_count = int(include_count)
return self.post('usergroups.enable', data={
'usergroup': usergroup,
'include_count': include_count,
})
class OAuth(BaseAPI):
def access(self, client_id, client_secret, code, redirect_uri=None):
return self.post('oauth.access',
data={
'client_id': client_id,
'client_secret': client_secret,
'code': code,
'redirect_uri': redirect_uri
})
class IncomingWebhook(object):
def __init__(self, url=None, timeout=DEFAULT_TIMEOUT):
self.url = url
self.timeout = timeout
def post(self, data):
"""
Posts message with payload formatted in accordance with
this documentation https://api.slack.com/incoming-webhooks
"""
if not self.url:
raise Error('URL for incoming webhook is undefined')
return requests.post(self.url, data=json.dumps(data),
timeout=self.timeout)
class Slacker(object):
oauth = OAuth(timeout=DEFAULT_TIMEOUT)
def __init__(self, token, incoming_webhook_url=None,
timeout=DEFAULT_TIMEOUT):
self.im = IM(token=token, timeout=timeout)
self.api = API(token=token, timeout=timeout)
self.rtm = RTM(token=token, timeout=timeout)
self.auth = Auth(token=token, timeout=timeout)
self.chat = Chat(token=token, timeout=timeout)
self.team = Team(token=token, timeout=timeout)
self.pins = Pins(token=token, timeout=timeout)
self.mpim = MPIM(token=token, timeout=timeout)
self.users = Users(token=token, timeout=timeout)
self.files = Files(token=token, timeout=timeout)
self.stars = Stars(token=token, timeout=timeout)
self.emoji = Emoji(token=token, timeout=timeout)
self.search = Search(token=token, timeout=timeout)
self.groups = Groups(token=token, timeout=timeout)
self.channels = Channels(token=token, timeout=timeout)
self.presence = Presence(token=token, timeout=timeout)
self.reactions = Reactions(token=token, timeout=timeout)
self.usergroups = UserGroups(token=token, timeout=timeout)
self.incomingwebhook = IncomingWebhook(url=incoming_webhook_url,
timeout=timeout)