forked from mitodl/release-script
/
bot.py
executable file
·1010 lines (894 loc) · 34 KB
/
bot.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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# pylint: disable=too-many-lines
"""Slack bot for managing releases"""
import asyncio
from collections import namedtuple
from datetime import datetime
import os
import sys
import logging
import json
import re
import requests
import pytz
from tornado.platform.asyncio import AsyncIOMainLoop
import websockets
from constants import (
FINISH_RELEASE_ID,
LIBRARY_TYPE,
TRAVIS_SUCCESS,
WEB_APPLICATION_TYPE,
)
from exception import (
InputException,
ReleaseException,
)
from finish_release import finish_release
from github import (
calculate_karma,
get_org_and_repo,
needs_review,
)
from release import (
create_release_notes,
init_working_dir,
release,
update_version,
)
from lib import (
get_release_pr,
get_unchecked_authors,
format_user_id,
load_repos_info,
match_user,
now_in_utc,
next_workday_at_10,
parse_date,
VERSION_RE,
upload_to_pypi,
)
from slack import get_channels_info
from wait_for_deploy import (
fetch_release_hash,
wait_for_deploy,
)
from version import get_version_tag
from wait_for_checked import wait_for_checkboxes
from wait_for_travis import wait_for_travis
from web import make_app
log = logging.getLogger(__name__)
CommandArgs = namedtuple('CommandArgs', ['channel_id', 'repo_info', 'args', 'loop', 'manager'])
Command = namedtuple('Command', ['command', 'parsers', 'command_func', 'description'])
Parser = namedtuple('Parser', ['func', 'description'])
def get_envs():
"""Get required environment variables"""
required_keys = (
'SLACK_ACCESS_TOKEN',
'BOT_ACCESS_TOKEN',
'GITHUB_ACCESS_TOKEN',
'SLACK_WEBHOOK_TOKEN',
'TIMEZONE',
'PORT',
'PYPI_USERNAME',
'PYPI_PASSWORD',
'PYPITEST_USERNAME',
'PYPITEST_PASSWORD',
)
env_dict = {key: os.environ.get(key, None) for key in required_keys}
missing_env_keys = [k for k, v in env_dict.items() if v is None]
if missing_env_keys:
raise Exception("Missing required env variable(s): {}".format(', '.join(missing_env_keys)))
return env_dict
# pylint: disable=too-many-instance-attributes,too-many-arguments,too-many-public-methods
class Bot:
"""Slack bot used to manage the release"""
def __init__(self, *, websocket, slack_access_token, github_access_token, timezone, repos_info):
"""
Create the slack bot
Args:
websocket (websockets.client.WebSocketClientProtocol): websocket for sending/receiving messages
slack_access_token (str): The OAuth access token used to interact with Slack
github_access_token (str): The Github access token used to interact with Github
timezone (tzinfo): The time zone of the team interacting with the bot
repos_info (list of RepoInfo): Information about the repositories connected to channels
"""
self.websocket = websocket
self.slack_access_token = slack_access_token
self.github_access_token = github_access_token
self.timezone = timezone
self.repos_info = repos_info
# Used for only websocket messages
self.message_count = 0
self.doof_boot = now_in_utc()
def lookup_users(self):
"""
Get users list from slack
"""
resp = requests.post("https://slack.com/api/users.list", data={
"token": self.slack_access_token
})
resp.raise_for_status()
return resp.json()['members']
def translate_slack_usernames(self, names):
"""
Try to match each full name with a slack username.
Args:
names (iterable of str): An iterable of full names
Returns:
iterable of str:
A iterable of either the slack name or a full name if a slack name was not found
"""
try:
slack_users = self.lookup_users()
return [match_user(slack_users, author) for author in names]
except Exception as exception: # pylint: disable=broad-except
sys.stderr.write("Error: {}".format(exception))
return names
def get_repo_info(self, channel_id):
"""
Get the repo info for a channel, or return None if no channel matches
Args:
channel_id (str): The channel id
"""
for repo_info in self.repos_info:
if repo_info.channel_id == channel_id:
return repo_info
return None
async def say(self, *, channel_id, text=None, attachments=None, message_type=None):
"""
Post a message in the Slack channel
Args:
channel_id (str): A channel id
text (str): A message
attachments (list of dict): Attachment information
message_type (str): The type of message
"""
attachments_dict = {"attachments": json.dumps(attachments)} if attachments else {}
text_dict = {"text": text} if text else {}
message_type_dict = {"type": message_type} if message_type else {}
resp = requests.post('https://slack.com/api/chat.postMessage', data={
"token": self.slack_access_token,
"channel": channel_id,
**text_dict,
**attachments_dict,
**message_type_dict,
})
resp.raise_for_status()
async def update_message(self, *, channel_id, timestamp, text=None, attachments=None):
"""
Update an existing message in slack
Args:
channel_id (str): The channel id
timestamp (str): The timestamp of the message to update
text (str): New text for the message
attachments (list of dict): New attachments for the message
"""
attachments_dict = {"attachments": json.dumps(attachments)} if attachments else {}
text_dict = {"text": text} if text else {}
resp = requests.post('https://slack.com/api/chat.update', data={
"token": self.slack_access_token,
"channel": channel_id,
"ts": timestamp,
**text_dict,
**attachments_dict,
})
resp.raise_for_status()
async def say_with_attachment(self, *, channel_id, title, text):
"""
Post a message in the Slack channel, putting the text in an attachment with markdown enabled
Args:
channel_id (channel_id): A channel id
title (str): A line of text before the main message
text (str): A message
"""
await self.say(
channel_id=channel_id,
text=title,
attachments=[{
"fallback": title,
"text": text,
"mrkdwn_in": ['text']
}]
)
async def typing(self, channel_id):
"""
Post a message in the Slack channel that Doof is typing something
Args:
channel_id (str): A channel id
"""
await self.websocket.send(json.dumps({
"id": self.message_count,
"type": "typing",
"channel": channel_id,
}))
self.message_count += 1
async def _library_release(self, command_args):
"""Do a library release"""
repo_info = command_args.repo_info
version = command_args.args[0]
repo_url = repo_info.repo_url
channel_id = repo_info.channel_id
release(
github_access_token=self.github_access_token,
repo_url=repo_url,
new_version=version,
)
org, repo = get_org_and_repo(repo_url)
status = await wait_for_travis(
github_access_token=self.github_access_token,
org=org,
repo=repo,
branch="release-candidate",
)
if status != TRAVIS_SUCCESS:
await self.say(
channel_id=channel_id,
text="Uh-oh, it looks like, uh, coffee break's over. During the release Travis had a {}.".format(
status,
)
)
return
finish_release(
github_access_token=self.github_access_token,
repo_url=repo_url,
version=version,
timezone=self.timezone
)
await self.say(
channel_id=channel_id,
text="My evil scheme {version} for {project} has been merged!".format(
version=version,
project=repo_info.name,
)
)
async def _web_application_release(self, command_args):
"""Do a web application release"""
repo_info = command_args.repo_info
version = command_args.args[0]
repo_url = repo_info.repo_url
channel_id = repo_info.channel_id
org, repo = get_org_and_repo(repo_url)
release(
github_access_token=self.github_access_token,
repo_url=repo_url,
new_version=version,
)
await self.say(
channel_id=channel_id,
text="Behold, my new evil scheme - release {version} for {project}! Now deploying to RC...".format(
version=version,
project=repo_info.name,
),
)
await wait_for_deploy(
github_access_token=self.github_access_token,
repo_url=repo_url,
hash_url=repo_info.rc_hash_url,
watch_branch="release-candidate",
)
unchecked_authors = get_unchecked_authors(
github_access_token=self.github_access_token,
org=org,
repo=repo,
)
slack_usernames = self.translate_slack_usernames(unchecked_authors)
pr = get_release_pr(
github_access_token=self.github_access_token,
org=org,
repo=repo,
)
await self.say(
channel_id=channel_id,
text="Release {version} for {project} was deployed! PR is up at {pr_url}."
" These people have commits in this release: {authors}".format(
version=version,
authors=", ".join(slack_usernames),
pr_url=pr.url,
project=repo_info.name,
)
)
await self.wait_for_checkboxes(repo_info, command_args.manager)
command_args.loop.create_task(self.delay_message(repo_info))
async def release_command(self, command_args):
"""
Start a new release and wait for deployment
Args:
command_args (CommandArgs): The arguments for this command
"""
repo_info = command_args.repo_info
repo_url = repo_info.repo_url
org, repo = get_org_and_repo(repo_url)
pr = get_release_pr(
github_access_token=self.github_access_token,
org=org,
repo=repo,
)
if pr:
raise ReleaseException("A release is already in progress: {}".format(pr.url))
if repo_info.project_type == LIBRARY_TYPE:
await self._library_release(command_args)
elif repo_info.project_type == WEB_APPLICATION_TYPE:
await self._web_application_release(command_args)
else:
raise Exception("Configuration error: unknown project type {}".format(repo_info.project_type))
async def wait_for_checkboxes_command(self, command_args):
"""
Poll the Release PR and wait until all checkboxes are checked off
Args:
command_args (CommandArgs): The arguments for this command
"""
await self.wait_for_checkboxes(command_args.repo_info, command_args.manager)
async def wait_for_checkboxes(self, repo_info, manager):
"""
Poll the Release PR and wait until all checkboxes are checked off
Args:
repo_info (RepoInfo): Information for a repo
manager (str): User id for the release manager
"""
channel_id = repo_info.channel_id
await self.say(
channel_id=channel_id,
text="Wait, wait. Time out. My evil plan for {project} isn't evil enough "
"until all the checkboxes are checked...".format(
project=repo_info.name,
)
)
org, repo = get_org_and_repo(repo_info.repo_url)
await wait_for_checkboxes(
github_access_token=self.github_access_token,
org=org,
repo=repo,
)
pr = get_release_pr(
github_access_token=self.github_access_token,
org=org,
repo=repo,
)
await self.say(
channel_id=channel_id,
text="All checkboxes checked off. Release {version} is ready for the Merginator {name}!".format(
name=format_user_id(manager),
version=pr.version
),
attachments=[
{
"fallback": "Finish the release",
"callback_id": FINISH_RELEASE_ID,
"actions": [
{
"name": "finish_release",
"text": "Finish the release",
"type": "button",
}
]
}
]
)
async def upload_to_pypitest(self, command_args):
"""
Upload package for version to pypitest server
Args:
command_args (CommandArgs): The arguments for this command
"""
await self._upload_to_pypi(command_args=command_args, testing=True)
async def upload_to_pypi(self, command_args):
"""
Upload package for version to pypi server
Args:
command_args (CommandArgs): The arguments for this command
"""
await self._upload_to_pypi(command_args=command_args, testing=False)
async def _upload_to_pypi(self, *, command_args, testing):
"""
Upload package for version to pypi server
Args:
command_args (CommandArgs): The arguments for this command
"""
repo_info = command_args.repo_info
version = command_args.args[0]
with init_working_dir(self.github_access_token, repo_info.repo_url, branch="v{}".format(version)):
upload_to_pypi(repo_info=repo_info, testing=testing)
await self.say(
channel_id=command_args.channel_id,
text='Successfully uploaded {version} to {pypi_server}.'.format(
version=version,
pypi_server="pypitest" if testing else "pypi",
),
)
async def finish_release(self, command_args):
"""
Merge the release candidate into the release branch, tag it, merge to master, and wait for deployment
Args:
command_args (CommandArgs): The arguments for this command
"""
repo_info = command_args.repo_info
channel_id = repo_info.channel_id
repo_url = repo_info.repo_url
org, repo = get_org_and_repo(repo_url)
pr = get_release_pr(
github_access_token=self.github_access_token,
org=org,
repo=repo,
)
if not pr:
raise ReleaseException("No release currently in progress for {project}".format(project=repo_info.name))
version = pr.version
finish_release(
github_access_token=self.github_access_token,
repo_url=repo_url,
version=version,
timezone=self.timezone
)
await self.say(
channel_id=channel_id,
text="Merged evil scheme {version} for {project}! Now deploying to production...".format(
version=version,
project=repo_info.name,
),
)
await wait_for_deploy(
github_access_token=self.github_access_token,
repo_url=repo_url,
hash_url=repo_info.prod_hash_url,
watch_branch="release",
)
await self.say(
channel_id=channel_id,
text="My evil scheme {version} for {project} has been released to production. "
"And by 'released', I mean completely...um...leased.".format(
version=version,
project=repo_info.name,
)
)
async def report_version(self, command_args):
"""
Report the version that is running in production
Args:
command_args (CommandArg): The arguments for this command
"""
repo_info = command_args.repo_info
channel_id = repo_info.channel_id
repo_url = repo_info.repo_url
commit_hash = fetch_release_hash(repo_info.prod_hash_url)
version = get_version_tag(self.github_access_token, repo_url, commit_hash)
await self.say(
channel_id=channel_id,
text="Wait a minute! My evil scheme is at version {version}!".format(version=version[1:])
)
async def commits_since_last_release(self, command_args):
"""
Have doof show the release notes since the last release
Args:
command_args (CommandArgs): The arguments for this command
"""
repo_info = command_args.repo_info
with init_working_dir(self.github_access_token, repo_info.repo_url):
last_version = update_version("9.9.9")
release_notes = create_release_notes(last_version, with_checkboxes=False)
await self.say_with_attachment(
channel_id=repo_info.channel_id,
title="Release notes since {}".format(last_version),
text=release_notes,
)
async def message_if_unchecked(self, repo_info):
"""
Send a message next morning if any boxes are not yet checked off
Args:
repo_info (RepoInfo): Information for a repo
"""
org, repo = get_org_and_repo(repo_info.repo_url)
unchecked_authors = get_unchecked_authors(
github_access_token=self.github_access_token,
org=org,
repo=repo,
)
if unchecked_authors:
slack_usernames = self.translate_slack_usernames(unchecked_authors)
await self.say(
channel_id=repo_info.channel_id,
text="What an unexpected surprise! "
"The following authors have not yet checked off their boxes for {project}: {names}".format(
names=", ".join(slack_usernames),
project=repo_info.name,
)
)
async def delay_message(self, repo_info):
"""
sleep until 10am next day, then message
Args:
repo_info (RepoInfo): The info for a repo
"""
now = datetime.now(tz=self.timezone)
tomorrow_at_10 = next_workday_at_10(now)
await asyncio.sleep((tomorrow_at_10 - now).total_seconds())
await self.message_if_unchecked(repo_info)
async def karma(self, command_args):
"""
Print out PR karma for each user
Args:
command_args (CommandArgs): The arguments for this command
"""
channel_id = command_args.channel_id
start_date = command_args.args[0]
title = "Pull request karma since {}".format(start_date)
await self.say_with_attachment(
channel_id=channel_id,
title=title,
text="\n".join(
"*{name}*: {karma}".format(name=name, karma=karma)
for name, karma in calculate_karma(
github_access_token=self.github_access_token,
begin_date=start_date,
end_date=now_in_utc().date(),
)
),
)
async def needs_review(self, command_args):
"""
Print out what PRs need review
Args:
command_args (CommandArgs): The arguments for this command
"""
channel_id = command_args.channel_id
title = "These PRs need review and are unassigned"
await self.say_with_attachment(
channel_id=channel_id,
title=title,
text="\n".join(
"*{repo}*: {title}\n{url}".format(
repo=repo,
title=title,
url=url,
) for repo, title, url in
needs_review(self.github_access_token)
)
)
async def uptime(self, command_args):
"""
Say how long the bot has been running
Args:
command_args (CommandArgs): The arguments for this command
"""
uptime = (now_in_utc() - self.doof_boot).total_seconds() / 60
await self.say(
channel_id=command_args.channel_id,
text=f"Awake for {int(uptime)} minutes. "
f"Oh, man. This had better be a dream because I don't like where this is going.",
)
async def hi(self, command_args):
"""
Say hi
Args:
command_args (CommandArgs): The arguments for this command
"""
channel_id = command_args.channel_id
await self.say(
channel_id=channel_id,
text="A Mongol army? Really? Uh, I must have had the dial set for"
" 'Hun.' Oh, well, you don't look a gift horde in the mouth, so... hello! "
)
async def help(self, command_args):
"""
List the commands the user can use
Args:
command_args (CommandArgs): The arguments for this command
"""
channel_id = command_args.channel_id
text = "\n".join("*{command}*{join}{parsers}: {description}".format(
command=command,
parsers=" ".join("*<{}>*".format(parser.description) for parser in parsers),
join=" " if parsers else "",
description=description,
) for command, parsers, _, description in sorted(self.make_commands()))
title = (
"Come on, Perry the Platypus. Let's go home. I talk to you enough, right? "
"Yeah, you're right. Maybe too much."
)
await self.say_with_attachment(
channel_id=channel_id,
title=title,
text=text,
)
def make_commands(self):
"""
Describe the commands which are available
Returns:
list of Command:
A list of all commands available to use
"""
return [
Command(
command='release notes',
parsers=[],
command_func=self.commits_since_last_release,
description="Release notes since last release",
),
Command(
command='start release',
parsers=[Parser(func=get_version_number, description='new version number')],
command_func=self.release_command,
description='Start a new release',
),
Command(
command='release',
parsers=[Parser(func=get_version_number, description='new version number')],
command_func=self.release_command,
description='Start a new release',
),
Command(
command='finish release',
parsers=[],
command_func=self.finish_release,
description='Finish a release',
),
Command(
command='wait for checkboxes',
parsers=[],
command_func=self.wait_for_checkboxes_command,
description='Wait for committers to check off their boxes',
),
Command(
command='upload to pypi',
parsers=[Parser(func=get_version_number, description='new version number')],
command_func=self.upload_to_pypi,
description='Upload package to pypi',
),
Command(
command='upload to pypitest',
parsers=[Parser(func=get_version_number, description='new version number')],
command_func=self.upload_to_pypitest,
description='Upload package to pypitest',
),
Command(
command='hi',
parsers=[],
command_func=self.hi,
description='Say hi to doof',
),
Command(
command='karma',
parsers=[Parser(func=parse_date, description='beginning date')],
command_func=self.karma,
description='Show pull request karma from a given date until today',
),
Command(
command='what needs review',
parsers=[],
command_func=self.needs_review,
description='List pull requests which need review and are unassigned',
),
Command(
command='uptime',
parsers=[],
command_func=self.uptime,
description='Shows how long this bot has been running'
),
Command(
command='version',
parsers=[],
command_func=self.report_version,
description='Show the version of the latest merged release',
),
Command(
command='help',
parsers=[],
command_func=self.help,
description='Show available commands',
),
]
# pylint: disable=too-many-locals
async def run_command(self, *, manager, channel_id, words, loop):
"""
Run a command
Args:
manager (str): The user id for the person giving the command
channel_id (str): The channel id
words (list of str): the words making up a command
loop (asyncio.events.AbstractEventLoop): The asyncio event loop
"""
await self.typing(channel_id)
commands = self.make_commands()
for command, parsers, command_func, _ in commands:
command_words = command.split()
if has_command(command_words, words):
args = words[len(command_words):]
if len(args) != len(parsers):
await self.say(
channel_id=channel_id,
text="Careful, careful. I expected {expected_num} words but you said {actual_num}.".format(
expected_num=len(parsers),
actual_num=len(args),
)
)
return
parsed_args = []
for arg, parser in zip(args, parsers):
try:
parsed_args.append(parser.func(arg))
except: # pylint: disable=bare-except
log.exception("Parser exception")
await self.say(
channel_id=channel_id,
text=(
"Oh dear! You said `{word}` but I'm having trouble"
" figuring out what that means.".format(
word=arg,
)
)
)
return
repo_info = self.get_repo_info(channel_id)
await command_func(
CommandArgs(
repo_info=repo_info,
channel_id=channel_id,
args=parsed_args,
loop=loop,
manager=manager,
)
)
return
# No command matched
await self.say(
channel_id=channel_id,
text="You're both persistent, I'll give ya that, but the security system "
"is offline and there's nothing you or your little dog friend can do about it!"
" Y'know, unless, one of you happens to be really good with computers."
)
async def handle_message(self, *, manager, channel_id, words, loop):
"""
Handle the message
Args:
manager (str): The user id for the person giving the command
channel_id (str): The channel id
words (list of str): the words making up a command
loop (asyncio.events.AbstractEventLoop): The asyncio event loop
"""
try:
await self.run_command(
manager=manager,
channel_id=channel_id,
words=words,
loop=loop
)
except (InputException, ReleaseException) as ex:
log.exception("A BotException was raised:")
await self.say(channel_id=channel_id, text="Oops! {}".format(ex))
except: # pylint: disable=bare-except
log.exception("Exception found when handling a message")
await self.say(
channel_id=channel_id,
text="No! Perry the Platypus, don't do it! "
"Don't push the self-destruct button. This one right here.",
)
async def handle_webhook(self, *, webhook_dict, loop):
"""
Handle a webhook coming from Slack. The payload has already been verified at this point.
Args:
webhook_dict (dict): The dict from Slack containing the webhook information
loop (asyncio.events.AbstractEventLoop): The asyncio event loop
"""
channel_id = webhook_dict['channel']['id']
user_id = webhook_dict['user']['id']
callback_id = webhook_dict['callback_id']
timestamp = webhook_dict['message_ts']
original_text = webhook_dict['original_message']['text']
if callback_id == FINISH_RELEASE_ID:
repo_info = self.get_repo_info(channel_id)
await self.update_message(
channel_id=channel_id,
timestamp=timestamp,
text=original_text,
attachments=[{
"title": "Merging..."
}],
)
try:
await self.finish_release(CommandArgs(
channel_id=channel_id,
repo_info=repo_info,
args=[],
loop=loop,
manager=user_id,
))
except:
await self.update_message(
channel_id=channel_id,
timestamp=timestamp,
text=original_text,
attachments=[{
"title": "Error merging release"
}],
)
raise
else:
log.warning("Unknown callback id: %s", callback_id)
def get_version_number(text):
"""
return version number at the end of the message
Args:
text (str): The word containing the version number
Returns:
str: The version if it parsed correctly
"""
pattern = re.compile(VERSION_RE)
if pattern.match(text):
return text
else:
raise InputException("Invalid version number")
def has_command(command_words, input_words):
"""
Check if words start the message
Args:
command_words (list of str):
words making up the command we are looking for
input_words (list of str):
words making up the content of the message
Returns:
bool:
True if this message is the given command
"""
command_words = [word.lower() for word in command_words]
input_words = [word.lower() for word in input_words]
return command_words == input_words[:len(command_words)]
def main():
"""main function for bot command"""
envs = get_envs()
channels_info = get_channels_info(envs['SLACK_ACCESS_TOKEN'])
repos_info = load_repos_info(channels_info)
try:
port = int(envs['PORT'])
except ValueError:
raise Exception("PORT is invalid")
resp = requests.post("https://slack.com/api/rtm.connect", data={
"token": envs['BOT_ACCESS_TOKEN'],
})
resp.raise_for_status()
doof_id = resp.json()['self']['id']
async def connect_to_message_server(loop):
"""Setup connection with websocket server"""
async with websockets.connect(resp.json()['url']) as websocket:
bot = Bot(
websocket=websocket,
slack_access_token=envs['SLACK_ACCESS_TOKEN'],
github_access_token=envs['GITHUB_ACCESS_TOKEN'],
timezone=pytz.timezone(envs['TIMEZONE']),
repos_info=repos_info,
)
app = make_app(token=envs['SLACK_WEBHOOK_TOKEN'], bot=bot, loop=loop)
app.listen(port)
while True:
message = await websocket.recv()
print(message)
message = json.loads(message)
if message.get('type') != 'message':
continue
if message.get('subtype') == 'message_changed':
# A user edits their message
# content = message.get('message', {}).get('text')
content = None
else:
content = message.get('text')
if content is None:
continue
channel_id = message.get('channel')
all_words = content.strip().split()
if len(all_words) > 0:
message_handle, *words = all_words
if message_handle in ("<@{}>".format(doof_id), "@doof"):
print("handling...", words, channel_id)
loop.create_task(
bot.handle_message(
manager=message['user'],
channel_id=channel_id,
words=words,
loop=loop,
)
)
loop = asyncio.get_event_loop()