forked from Charcoal-SE/SmokeDetector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatcommands.py
2246 lines (1887 loc) · 86.9 KB
/
chatcommands.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
# coding=utf-8
# noinspection PyUnresolvedReferences
from chatcommunicate import add_room, block_room, CmdException, command, get_report_data, is_privileged, message, \
tell_rooms, tell_rooms_with, get_message
# noinspection PyUnresolvedReferences
from globalvars import GlobalVars
import findspam
# noinspection PyUnresolvedReferences
from datetime import datetime
from apigetpost import api_get_post, PostData
import datahandling
from datahandling import *
from metasmoke import Metasmoke
from blacklists import load_blacklists, Blacklist
from parsing import *
from spamhandling import check_if_spam, handle_spam
from gitmanager import GitManager
import threading
import random
import requests
import sys
import os
import time
import collections
from html import unescape
from ast import literal_eval
# noinspection PyCompatibility
import regex
from helpers import exit_mode, only_blacklists_changed, only_modules_changed, log, expand_shorthand_link, \
reload_modules, chunk_list
from classes import Post
from classes.feedback import *
from tasks import Tasks
# TODO: Do we need uid == -2 check? Turn into "is_user_valid" check
#
#
# System command functions below here
# This "null" command is just bypass for the "unrecognized command" message,
# so that pingbot can respond instead.
@command(aliases=['ping-help', 'groups'])
def null():
return None
# --- Blacklist Functions --- #
# noinspection PyIncorrectDocstring,PyMissingTypeHints
@command(str, whole_msg=True, privileged=True)
def addblu(msg, user):
"""
Adds a user to site whitelist
:param msg: ChatExchange message
:param user:
:return: A string
"""
uid, val = get_user_from_list_command(user)
if int(uid) > -1 and val != "":
message_url = "https://chat.{}/transcript/{}?m={}".format(msg._client.host, msg.room.id, msg.id)
add_blacklisted_user((uid, val), message_url, "")
return "User blacklisted (`{}` on `{}`).".format(uid, val)
elif int(uid) == -2:
raise CmdException("Error: {}".format(val))
else:
raise CmdException("Invalid format. Valid format: `!!/addblu profileurl` *or* `!!/addblu userid sitename`.")
# noinspection PyIncorrectDocstring,PyMissingTypeHints
@command(str)
def isblu(user):
"""
Check if a user is blacklisted
:param user:
:return: A string
"""
uid, val = get_user_from_list_command(user)
if int(uid) > -1 and val != "":
if is_blacklisted_user((uid, val)):
return "User is blacklisted (`{}` on `{}`).".format(uid, val)
else:
return "User is not blacklisted (`{}` on `{}`).".format(uid, val)
elif int(uid) == -2:
raise CmdException("Error: {}".format(val))
else:
raise CmdException("Invalid format. Valid format: `!!/isblu profileurl` *or* `!!/isblu userid sitename`.")
# noinspection PyIncorrectDocstring,PyUnusedLocal
@command(str, privileged=True)
def rmblu(user):
"""
Removes user from site blacklist
:param user:
:return: A string
"""
uid, val = get_user_from_list_command(user)
if int(uid) > -1 and val != "":
if remove_blacklisted_user((uid, val)):
return "User removed from blacklist (`{}` on `{}`).".format(uid, val)
else:
return "User is not blacklisted."
elif int(uid) == -2:
raise CmdException("Error: {}".format(val))
else:
raise CmdException("Invalid format. Valid format: `!!/rmblu profileurl` *or* `!!/rmblu userid sitename`.")
# --- Whitelist functions --- #
# noinspection PyIncorrectDocstring,PyUnusedLocal,PyMissingTypeHints
@command(str, privileged=True)
def addwlu(user):
"""
Adds a user to site whitelist
:param user:
:return: A string
"""
uid, val = get_user_from_list_command(user)
if int(uid) > -1 and val != "":
add_whitelisted_user((uid, val))
return "User whitelisted (`{}` on `{}`).".format(uid, val)
elif int(uid) == -2:
raise CmdException("Error: {}".format(val))
else:
raise CmdException("Invalid format. Valid format: `!!/addwlu profileurl` *or* `!!/addwlu userid sitename`.")
# noinspection PyIncorrectDocstring,PyUnusedLocal,PyMissingTypeHints
@command(str)
def iswlu(user):
"""
Checks if a user is whitelisted
:param user:
:return: A string
"""
uid, val = get_user_from_list_command(user)
if int(uid) > -1 and val != "":
if is_whitelisted_user((uid, val)):
return "User is whitelisted (`{}` on `{}`).".format(uid, val)
else:
return "User is not whitelisted (`{}` on `{}`).".format(uid, val)
elif int(uid) == -2:
raise CmdException("Error: {}".format(val))
else:
raise CmdException("Invalid format. Valid format: `!!/iswlu profileurl` *or* `!!/iswlu userid sitename`.")
# noinspection PyIncorrectDocstring,PyMissingTypeHints
@command(str, privileged=True)
def rmwlu(user):
"""
Removes a user from site whitelist
:param user:
:return: A string
"""
uid, val = get_user_from_list_command(user)
if int(uid) != -1 and val != "":
if remove_whitelisted_user((uid, val)):
return "User removed from whitelist (`{}` on `{}`).".format(uid, val)
else:
return "User is not whitelisted."
elif int(uid) == -2:
raise CmdException("Error: {}".format(val))
else:
raise CmdException("Invalid format. Valid format: `!!/rmwlu profileurl` *or* `!!/rmwlu userid sitename`.")
# noinspection PyIncorrectDocstring
@command(str)
def blacklist(_):
"""
Returns a string which explains the usage of the new blacklist commands.
:return: A string
"""
raise CmdException("The `!!/blacklist` command has been deprecated. "
"Please use `!!/blacklist-website`, `!!/blacklist-username`, "
"`!!/blacklist-keyword`, or perhaps `!!/watch-keyword`. "
"Remember to escape dots in URLs using \\.")
def minimally_validate_content_source(msg):
"""
Raises a CmdException if the msg.content and msg.content_source don't match to the first space (i.e. same command).
"""
# If the chat message has been edited or deleted, then content_source can be invalid, or
# even a completely different command. Checking that it's for the same command covers the deleted
# message case and that we don't use arguments intended for a different command. This is, however,
# not a full re-validation. It just covers the most common case, and the definite problem of using
# the arguments intended for one command with another one.
# For more information, see the discussion starting with:
# https://chat.stackexchange.com/transcript/11540?m=54465107#54465107
if msg.content.split(" ")[0] != msg.content_source.split(" ")[0]:
raise CmdException("There was a problem with this command. Was the chat message edited or deleted?")
def get_pattern_from_content_source(msg):
"""
Returns a string containing the raw chat message content, except for the !!/command .
:return: A string
"""
try:
return msg.content_source.split(" ", 1)[1]
except IndexError:
# If there's nothing after the space, then raise an error. The chat message may have been edited or deleted,
# but the deleted case is normally handled in minimally_validate_content_source(), which should be called first.
# For more information, see the discussion starting with:
# https://chat.stackexchange.com/transcript/11540?m=54465107#54465107
raise CmdException("An invalid pattern was provided, please check your command. Was the command edited?")
def check_blacklist(string_to_test, is_username, is_watchlist, is_phone):
# Test the string and provide a warning message if it is already caught.
if is_username:
question = Post(api_response={'title': 'Valid title', 'body': 'Valid body',
'owner': {'display_name': string_to_test, 'reputation': 1, 'link': ''},
'site': "", 'IsAnswer': False, 'score': 0})
answer = Post(api_response={'title': 'Valid title', 'body': 'Valid body',
'owner': {'display_name': string_to_test, 'reputation': 1, 'link': ''},
'site': "", 'IsAnswer': True, 'score': 0})
else:
question = Post(api_response={'title': 'Valid title', 'body': string_to_test,
'owner': {'display_name': "Valid username", 'reputation': 1, 'link': ''},
'site': "", 'IsAnswer': False, 'score': 0})
answer = Post(api_response={'title': 'Valid title', 'body': string_to_test,
'owner': {'display_name': "Valid username", 'reputation': 1, 'link': ''},
'site': "", 'IsAnswer': True, 'score': 0})
question_reasons, _ = findspam.FindSpam.test_post(question)
answer_reasons, _ = findspam.FindSpam.test_post(answer)
# Filter out duplicates
reasons = list(set(question_reasons) | set(answer_reasons))
# Filter out watchlist results
filter_out = ["potentially bad ns", "potentially bad asn", "potentially problematic",
"potentially bad ip"]
if not is_watchlist:
filter_out.append("potentially bad keyword")
# Ignore "Mostly non-latin body/answer" for phone number watches
if is_phone:
filter_out.extend(["mostly non-latin", "phone number detected", "messaging number detected"])
# Filter out some reasons which commonly find the things added to the watch/blacklists
# If these are detected, then the user should almost always -force. Showing them gets people too used
# to just automatically using -force. Maybe a better UX strategy would be to have other reasons shown in bold.
filter_out.extend(["pattern-matching email", "pattern-matching website", "bad keyword with email",
"bad ns for domain", "bad ip for hostname"])
if filter_out:
reasons = [reason for reason in reasons if all([x not in reason.lower() for x in filter_out])]
return reasons
def format_blacklist_reasons(reasons):
# Capitalize
reasons = [reason.capitalize() for reason in reasons]
# Join
if len(reasons) < 3:
reason_string = " and ".join(reasons)
else:
reason_string = ", and ".join([", ".join(reasons[:-1]), reasons[-1]])
return reason_string
def sub_to_unchanged(reg_exp, replace, text, max_passes=10, count=0, flags=0):
"""
Applies a regex substitution as many times as is needed to no longer make a change.
:param regex:
:param replace:
:param text:
:param max_passes:
:param count:
:param flags:
:return: A string
"""
prev_text = ""
max_passes = max_passes + 1 if max_passes else max_passes
while (text and text != prev_text and max_passes != 1):
prev_text = text
text = regex.sub(reg_exp, replace, text, count=count, flags=flags)
max_passes -= 1
return text
def get_test_text_from_regex(pattern):
"""
Converts regex text supplied in a command to text which can be tested for double-dipping
:param A string:
:return: A string
"""
# Handle a specific common pattern that's now matched by a watch for obfuscated gmail.com.
pattern = pattern.replace(r"(?:[\W_]*+(?:at[\W_]*+)?gmail(?:[\W_]*+(?:dot[\W_]*+)?com)?)?", "@gmail.com")
pattern = regex.sub(r"(?<!\\)\(\?\#[^\)]*\)", "", pattern) # Remove comments: comments can have no nested ()
pattern = regex.sub(r"(?<!\\)\[\\W_\][*?+]*", "-", pattern) # Replace typical sets
pattern = regex.sub(r"(?<!\\)\[\\da-f\]\{4,\}+?", "0123", pattern) # Replace typical sets
pattern = regex.sub(r"(?<!\\)\[\\da-f\][*?+]*", "0", pattern) # Replace typical sets
pattern = regex.sub(r"(?<!\\)\[\^a-z0-9-\][*?+]*", "_", pattern) # Replace typical sets
# Replace common named sets
pattern = pattern.replace(r"\W", "-").replace(r"\w", "a").replace(r"\.", ".").replace(r"\d", "8")
pattern = pattern.replace(r"\s", " ").replace(r"\S", "b").replace(r"\n", "\n").replace(r"\r", "\r")
pattern = regex.sub(r"(?<!\\)\$", "", pattern) # Remove end assertion
pattern = regex.sub(r"(?<![\\\[])\^", "", pattern) # Remove start assertion
pattern = regex.sub(r"(?<!\\)\\[Bb]", "", pattern) # Remove wordbreak assertion
pattern = regex.sub(r"(?<!\\)\[(?!\^|\\)(.)(?:[^\]]|(?<=\\)])*\]", r"\1", pattern) # Replace positive sets
# Remove optional groups (still want to test this text)
# pattern = sub_to_unchanged(r"\((?:\?:|(?!\?))(?:[^\(\)]|(?<=\\)[()])*\)(?:[*?][+?]?|\{0?,\d+\}[+?]?)",
# "", pattern)
# Remove optional characters
pattern = regex.sub(r"(?:\\.|(?<!\\)[^+*}()[\]])(?:[*?][+?]?|\{0?,\d+\}[+?]?)", "", pattern)
# Remove lookarounds.
pattern = sub_to_unchanged(r"\(\?<?[!=](?:[^\(\)]|(?<=\\)[()])*\)", "", pattern)
# Remove () and (?:) from non-optional groupings
pattern = sub_to_unchanged(r"\((?:\?:|(?!\?))((?:[^\(\)]|(?<=\\)[()])*)\)(?![*?][+?]?|\{0?,\d+\}[+?]?)",
r"\1", pattern)
# Remove optional groups (still want to test this text)
# pattern = sub_to_unchanged(r"\((?:\?:|(?!\?))(?:[^\(\)]|(?<=\\)[()])*\)(?:[*?][+?]?|\{0?,\d+\}[+?]?)",
# "", pattern)
# drop flags: https://regex101.com/r/smAiks/1/
pattern = sub_to_unchanged(r"(?<!\\)\(\?[a-zA-Z-]+(?::((?:[^\(\)]|(?<=\\)[()])*))?\)", r"\1", pattern)
pattern = regex.sub(r"(?<!\\)(?:(?<!(?<!\\)\()[+*?][+?]?|\{\d*(?:,\d*)?\}[+?]?)", "", pattern) # Common quantifiers
# Remove () and (?:) from groupings
pattern = sub_to_unchanged(r"\((?:\?:|(?!\?))((?:[^\(\)]|(?<=\\)[()])*)\)", r"\1", pattern)
# Remove lookarounds (again).
pattern = sub_to_unchanged(r"\(\?<?[!=](?:[^\(\)]|(?<=\\)[()])*\)", "", pattern)
return pattern
def do_blacklist(blacklist_type, msg, force=False):
"""
Adds a string to the website blacklist and commits/pushes to GitHub
:param raw_pattern:
:param blacklist_type:
:param msg:
:param force:
:return: A string
"""
minimally_validate_content_source(msg)
chat_user_profile_link = "https://chat.{host}/users/{id}".format(host=msg._client.host,
id=msg.owner.id)
append_force_to_do = "; append `-force` if you really want to do that."
pattern = get_pattern_from_content_source(msg)
has_unescaped_dot = ""
if "number" not in blacklist_type:
# Test for . without \., but not in comments.
test_for_unescaped_dot = regex.sub(r"(?<!\\)\(\?\#[^\)]*\)", "", pattern) # remove comments
# Remove character sets, where . doesn't need to be escaped.
test_for_unescaped_dot = regex.sub(r"(?<!\\)\[(?:[^\]]|(?<=\\)\])*\]", "", test_for_unescaped_dot)
if regex.search(r"(?<!\\)\.", test_for_unescaped_dot):
has_unescaped_dot = 'The regex contains an unescaped "`.`"; in most cases, it should be "`\\.`"'
try:
r = regex.compile(findspam.format_with_city_list(pattern))
# r = regex.compile(pattern, city=findspam.city_list, ignore_unused=True)
except regex._regex_core.error:
raise CmdException("An invalid pattern was provided, please check your command.")
if r.search(GlobalVars.valid_content) is not None:
raise CmdException("That pattern is probably too broad, refusing to commit.")
if not force:
if "number" in blacklist_type or \
regex.match(r'(?:\[a-z_]\*)?(?:\(\?:)?\d+(?:[][\\W_*()?:]+\d+)+(?:\[a-z_]\*)?$', pattern):
is_phone = True
else:
is_phone = False
is_watchlist = bool("watch" in blacklist_type)
concretized_pattern = get_test_text_from_regex(pattern)
for username in False, True:
reasons = check_blacklist(
concretized_pattern, is_username=username, is_watchlist=is_watchlist, is_phone=is_phone)
if reasons:
has_unescaped_dot = "; in addition, " + has_unescaped_dot.lower() if has_unescaped_dot else ""
raise CmdException(
"That pattern looks like it's already caught by " +
format_blacklist_reasons(reasons) + has_unescaped_dot + append_force_to_do)
if has_unescaped_dot:
raise CmdException(has_unescaped_dot + append_force_to_do)
metasmoke_down = False
try:
code_permissions = is_code_privileged(msg._client.host, msg.owner.id)
except (requests.exceptions.ConnectionError, ValueError, TypeError):
code_permissions = False # Because we need the system to assume that we don't have blacklister privs.
metasmoke_down = True
_status, result = GitManager.add_to_blacklist(
blacklist=blacklist_type,
item_to_blacklist=pattern,
username=msg.owner.name,
chat_profile_link=chat_user_profile_link,
code_permissions=code_permissions,
metasmoke_down=metasmoke_down
)
if not _status:
raise CmdException(result)
if code_permissions and only_blacklists_changed(GitManager.get_local_diff()):
try:
if not GlobalVars.on_branch:
# Restart if HEAD detached
log('warning', "Pulling local with HEAD detached, checkout deploy", f=True)
exit_mode("checkout_deploy")
GitManager.pull_local()
GlobalVars.reload()
findspam.FindSpam.reload_blacklists()
tell_rooms_with('debug', GlobalVars.s_norestart_blacklists)
time.sleep(2)
return None
except Exception:
pass
return result
# noinspection PyIncorrectDocstring
@command(str, whole_msg=True, privileged=True, give_name=True, aliases=["blacklist-keyword",
"blacklist-website",
"blacklist-username",
"blacklist-number",
"blacklist-keyword-force",
"blacklist-website-force",
"blacklist-username-force",
"blacklist-number-force"])
def blacklist_keyword(msg, pattern, alias_used="blacklist-keyword"):
"""
Adds a pattern to the blacklist and commits/pushes to GitHub
:param msg:
:param pattern:
:return: A string
"""
parts = alias_used.split("-")
return do_blacklist(parts[1], msg, force=len(parts) > 2)
# noinspection PyIncorrectDocstring
@command(str, whole_msg=True, privileged=True, give_name=True,
aliases=["watch-keyword", "watch-force", "watch-keyword-force",
"watch-number", "watch-number-force"])
def watch(msg, pattern, alias_used="watch"):
"""
Adds a pattern to the watched keywords list and commits/pushes to GitHub
:param msg:
:param pattern:
:return: A string
"""
return do_blacklist("watch_number" if "number" in alias_used else "watch_keyword",
msg, force=alias_used.split("-")[-1] == "force")
@command(str, whole_msg=True, privileged=True, give_name=True, aliases=["unwatch"])
def unblacklist(msg, item, alias_used="unwatch"):
"""
Removes a pattern from watchlist/blacklist and commits/pushes to GitHub
:param msg:
:param pattern:
:return: A string
"""
if alias_used == "unwatch":
blacklist_type = "watch"
elif alias_used == "unblacklist":
blacklist_type = "blacklist"
else:
raise CmdException("Invalid blacklist type.")
minimally_validate_content_source(msg)
metasmoke_down = False
try:
code_privs = is_code_privileged(msg._client.host, msg.owner.id)
except (requests.exceptions.ConnectionError, ValueError):
code_privs = False
metasmoke_down = True
pattern = get_pattern_from_content_source(msg)
_status, result = GitManager.remove_from_blacklist(
rebuild_str(pattern), msg.owner.name, blacklist_type,
code_privileged=code_privs, metasmoke_down=metasmoke_down)
if not _status:
raise CmdException(result)
if only_blacklists_changed(GitManager.get_local_diff()):
try:
if not GlobalVars.on_branch:
# Restart if HEAD detached
log('warning', "Pulling local with HEAD detached, checkout deploy", f=True)
exit_mode("checkout_deploy")
GitManager.pull_local()
GlobalVars.reload()
findspam.FindSpam.reload_blacklists()
tell_rooms_with('debug', GlobalVars.s_norestart_blacklists)
time.sleep(2)
return None
except Exception:
pass
return result
@command(int, privileged=True, whole_msg=True)
def approve(msg, pr_id):
code_permissions = is_code_privileged(msg._client.host, msg.owner.id)
if not code_permissions:
raise CmdException("You need blacklist manager privileges to approve pull requests")
# Forward this, because checks are better placed in gitmanager.py
try:
message_url = "https://chat.{}/transcript/{}?m={}".format(msg._client.host, msg.room.id, msg.id)
chat_user_profile_link = "https://chat.{}/users/{}".format(
msg._client.host, msg.owner.id)
comment = "[Approved]({}) by [{}]({}) in {}\n\n![Approved with SmokeyApprove]({})".format(
message_url, msg.owner.name, chat_user_profile_link, msg.room.name,
# The image of (blacklisters|approved) from PullApprove
"https://camo.githubusercontent.com/7d7689a88a6788541a0a87c6605c4fdc2475569f/68747470733a2f2f696d672e"
"736869656c64732e696f2f62616467652f626c61636b6c6973746572732d617070726f7665642d627269676874677265656e")
message = GitManager.merge_pull_request(pr_id, comment)
if only_blacklists_changed(GitManager.get_local_diff()):
try:
if not GlobalVars.on_branch:
# Restart if HEAD detached
log('warning', "Pulling local with HEAD detached, checkout deploy", f=True)
exit_mode("checkout_deploy")
GitManager.pull_local()
GlobalVars.reload()
findspam.FindSpam.reload_blacklists()
tell_rooms_with('debug', GlobalVars.s_norestart_blacklists)
time.sleep(2)
return None
except Exception:
pass
return message
except Exception as e:
raise CmdException(str(e))
@command(privileged=True, aliases=["remote-diff"])
def remotediff():
will_require_full_restart = "SmokeDetector will require a full restart to pull changes: " \
"{}".format(str(not only_blacklists_changed(GitManager.get_remote_diff())))
return "{}\n\n{}".format(GitManager.get_remote_diff(), will_require_full_restart)
# --- Joke Commands --- #
@command(whole_msg=True)
def blame(msg):
unlucky_victim = msg._client.get_user(random.choice(msg.room.get_current_user_ids()))
return "It's [{}](https://chat.{}/users/{})'s fault.".format(
unlucky_victim.name, msg._client.host, unlucky_victim.id)
@command(str, whole_msg=True, aliases=["blame\u180E"])
def blame2(msg, x):
base = {"\u180E": 0, "\u200B": 1, "\u200C": 2, "\u200D": 3, "\u2060": 4, "\u2063": 5, "\uFEFF": 6}
try:
user = sum([(len(base)**i) * base[char] for i, char in enumerate(reversed(x))])
unlucky_victim = msg._client.get_user(user)
return "It's [{}](https://chat.{}/users/{})'s fault.".format(
unlucky_victim.name, msg._client.host, unlucky_victim.id)
except (KeyError, requests.exceptions.HTTPError):
unlucky_victim = msg.owner
return "It's [{}](https://chat.{}/users/{})'s fault.".format(
unlucky_victim.name, msg._client.host, unlucky_victim.id)
# noinspection PyIncorrectDocstring
@command()
def brownie():
"""
Returns a string equal to "Brown!" (This is a joke command)
:return: A string
"""
return "Brown!"
COFFEES = ['Espresso', 'Macchiato', 'Ristretto', 'Americano', 'Latte', 'Cappuccino', 'Mocha', 'Affogato', 'jQuery']
# noinspection PyIncorrectDocstring
@command(str, whole_msg=True, arity=(0, 1))
def coffee(msg, other_user):
"""
Returns a string stating who the coffee is for (This is a joke command)
:param msg:
:param other_user:
:return: A string
"""
if other_user is None:
return "*brews a cup of {} for @{}*".format(random.choice(COFFEES), msg.owner.name.replace(" ", ""))
else:
other_user = regex.sub(r'^@*|\b\s.{1,}', '', other_user)
return "*brews a cup of {} for @{}*".format(random.choice(COFFEES), other_user)
# noinspection PyIncorrectDocstring
@command()
def lick():
"""
Returns a string when a user says 'lick' (This is a joke command)
:return: A string
"""
return "*licks ice cream cone*"
TEAS = ['earl grey', 'green', 'chamomile', 'lemon', 'darjeeling', 'mint', 'jasmine', 'passionfruit']
# noinspection PyIncorrectDocstring
@command(str, whole_msg=True, arity=(0, 1))
def tea(msg, other_user):
"""
Returns a string stating who the tea is for (This is a joke command)
:param msg:
:param other_user:
:return: A string
"""
if other_user is None:
return "*brews a cup of {} tea for @{}*".format(random.choice(TEAS), msg.owner.name.replace(" ", ""))
else:
other_user = regex.sub(r'^@*|\b\s.{1,}', '', other_user)
return "*brews a cup of {} tea for @{}*".format(random.choice(TEAS), other_user)
# noinspection PyIncorrectDocstring
@command()
def wut():
"""
Returns a string when a user asks 'wut' (This is a joke command)
:return: A string
"""
return "Whaddya mean, 'wut'? Humans..."
"""
@command(aliases=["zomg_hats"])
def hats():
wb_start = datetime(2018, 12, 12, 0, 0, 0)
wb_end = datetime(2019, 1, 2, 0, 0, 0)
now = datetime.utcnow()
return_string = ""
if wb_start > now:
diff = wb_start - now
hours, remainder = divmod(diff.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
daystr = "days" if diff.days != 1 else "day"
hourstr = "hours" if hours != 1 else "hour"
minutestr = "minutes" if minutes != 1 else "minute"
secondstr = "seconds" if seconds != 1 else "second"
return_string = "WE LOVE HATS! Winter Bash will begin in {} {}, {} {}, {} {}, and {} {}.".format(
diff.days, daystr, hours, hourstr, minutes, minutestr, seconds, secondstr)
elif wb_end > now:
diff = wb_end - now
hours, remainder = divmod(diff.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
daystr = "days" if diff.days != 1 else "day"
hourstr = "hours" if hours != 1 else "hour"
minutestr = "minutes" if minutes != 1 else "minute"
secondstr = "seconds" if seconds != 1 else "second"
return_string = "Winter Bash won't end for {} {}, {} {}, {} {}, and {} {}. GO EARN SOME HATS!".format(
diff.days, daystr, hours, hourstr, minutes, minutestr, seconds, secondstr)
return return_string
"""
# --- Block application from posting functions --- #
# noinspection PyIncorrectDocstring
@command(int, int, whole_msg=True, privileged=True, arity=(1, 2))
def block(msg, block_time, room_id):
"""
Blocks posts from application for a period of time
:param msg:
:param block_time:
:param room_id:
:return: None
"""
time_to_block = block_time if 0 < block_time < 14400 else 900
which_room = "globally" if room_id is None else "in room {} on {}".format(room_id, msg._client.host)
block_message = "Reports blocked for {} second(s) {}.".format(time_to_block, which_room)
tell_rooms(block_message, ((msg._client.host, msg.room.id), "debug", "metatavern"), ())
block_room(room_id, msg._client.host, time.time() + time_to_block)
# noinspection PyIncorrectDocstring,PyUnusedLocal
@command(int, int, whole_msg=True, privileged=True, arity=(1, 2))
def unblock(msg, room_id):
"""
Unblocks posting to a room
:param msg:
:param room_id:
:return: None
"""
block_room(room_id, msg._client.host, -1)
which_room = "globally" if room_id is None else "in room {} on {}".format(room_id, msg._client.host)
unblock_message = "Reports unblocked {}.".format(which_room)
tell_rooms(unblock_message, ((msg._client.host, msg.room.id), "debug", "metatavern"), ())
# --- Administration Commands --- #
ALIVE_MSG = [
'Yup', 'You doubt me?', 'Of course', '... did I miss something?', 'plz send teh coffee',
'Watching this endless list of new questions *never* gets boring', 'Kinda sorta',
'You should totally drop that and use jQuery', r'¯\\_(ツ)\_/¯', '... good question',
]
# noinspection PyIncorrectDocstring
@command(aliases=["live"])
def alive():
"""
Returns a string indicating the process is still active
:return: A string
"""
return random.choice(ALIVE_MSG)
# noinspection PyIncorrectDocstring
@command(int, privileged=True, arity=(0, 1), aliases=["errlogs", "errlog", "errorlog"])
def errorlogs(count):
"""
Shows the most recent lines in the error logs
:param count:
:return: A string
"""
return fetch_lines_from_error_log(count or 2)
@command(whole_msg=True, aliases=["ms-status", "ms-down", "ms-up", "ms-down-force", "ms-up-force"], give_name=True)
def metasmoke(msg, alias_used):
if alias_used in {"metasmoke", "ms-status"}:
status_text = [
"metasmoke is up. Current failure count: {} ({id})".format(GlobalVars.MSStatus.get_failure_count(),
id=GlobalVars.location),
"metasmoke is down. Current failure count: {} ({id})".format(GlobalVars.MSStatus.get_failure_count(),
id=GlobalVars.location),
]
if GlobalVars.MSStatus.is_up():
# True = 1 and False = 0 is a legacy feature
# Better not to use them
return status_text[0]
else:
return status_text[1]
# The next aliases/functionalities require privilege
if not is_privileged(msg.owner, msg.room):
raise CmdException(GlobalVars.not_privileged_warning)
to_up = "up" in alias_used
forced = "force" in alias_used
Metasmoke.AutoSwitch.reset_switch() # If manually switched, reset the internal counter
Metasmoke.AutoSwitch.enable_autoswitch(not forced)
if to_up:
Metasmoke.set_ms_up()
else:
Metasmoke.set_ms_down()
return "Metasmoke status is now: **{}**;".format("up" if to_up else "down") +\
" Auto status switch: **{}abled**.".format("dis" if forced else "en")
# noinspection PyIncorrectDocstring
@command(aliases=["commands", "help"])
def info():
"""
Returns the help text
:return: A string
"""
return "I'm " + GlobalVars.chatmessage_prefix +\
", a bot that detects spam and offensive posts on the network and"\
" posts alerts to chat."\
" [A command list is available here](https://charcoal-se.org/smokey/Commands)."
# noinspection PyIncorrectDocstring
@command(str, whole_msg=True, arity=(0, 1))
def welcome(msg, other_user):
"""
Returns the welcome text
:param msg:
:param other_user:
:return: A string
"""
w_msg = ("Welcome to {room}{user}! I'm {me}, a bot that detects spam and offensive posts on the network, "
"and posts alerts to chat. You can find more about me on the "
"[Charcoal website](https://charcoal-se.org/).")
if other_user is None:
raise CmdException(w_msg.format(room=msg.room.name, user="", me=GlobalVars.chatmessage_prefix))
else:
other_user = regex.sub(r'^@*|\b\s.{1,}', '', other_user)
raise CmdException(w_msg.format(room=msg.room.name, user=" @" + other_user, me=GlobalVars.chatmessage_prefix))
# noinspection PyIncorrectDocstring
@command()
def location():
"""
Returns the current location the application is running from
:return: A string with current location
"""
return GlobalVars.location
# noinspection PyIncorrectDocstring,PyProtectedMember
@command(privileged=True)
def master():
"""
Forces a system exit with exit code = 8
:return: None
"""
exit_mode("checkout_deploy")
# noinspection PyIncorrectDocstring,PyProtectedMember
@command(privileged=True, aliases=["pull-force"])
def pull(alias_used='pull'):
"""
Pull an update from GitHub
:return: String on failure, None on success
"""
remote_diff = GitManager.get_remote_diff()
if (not alias_used == "pull-force") and only_blacklists_changed(remote_diff):
GitManager.pull_remote()
findspam.FindSpam.reload_blacklists()
GlobalVars.reload()
tell_rooms_with('debug', GlobalVars.s_norestart_blacklists)
return
request = requests.get('https://api.github.com/repos/{}/git/refs/heads/deploy'.format(
GlobalVars.bot_repo_slug))
latest_sha = request.json()["object"]["sha"]
request = requests.get(
'https://api.github.com/repos/{}/commits/{}/statuses'.format(
GlobalVars.bot_repo_slug, latest_sha))
states = []
for ci_status in request.json():
state = ci_status["state"]
states.append(state)
if "success" in states:
if only_modules_changed(remote_diff):
GitManager.pull_remote()
reload_modules()
GlobalVars.reload()
tell_rooms_with('debug', GlobalVars.s_norestart_findspam)
return
else:
exit_mode('pull_update', code=3)
elif "error" in states or "failure" in states:
raise CmdException("CI build failed! :( Please check your commit.")
elif "pending" in states or not states:
raise CmdException("CI build is still pending, wait until the build has finished and then pull again.")
@command(whole_msg=True, privileged=True, give_name=True, aliases=['pull-sync', 'pull-sync-force'])
def sync_remote(msg, alias_used='pull-sync'):
"""
Force a branch sync from origin/master with [git branch -M]
:param msg:
:return: A string containing a response message
"""
if not is_code_privileged(msg._client.host, msg.owner.id):
raise CmdException("You don't have blacklist manager privileges to run this command.")
if 'force' not in alias_used:
raise CmdException("This command is deprecated, append `-force` if you really need to do that.")
return GitManager.sync_remote()[1]
@command(whole_msg=True, privileged=True, give_name=True, aliases=['pull-sync-hard',
'pull-sync-hard-force',
'pull-sync-hard-reboot',
'pull-sync-hard-reboot-force'])
def sync_remote_hard(msg, alias_used='pull-sync-hard'):
"""
Force a branch sync from origin/master and origin/deploy
:param msg:
:return: A string containing a response message or None
"""
if not is_code_privileged(msg._client.host, msg.owner.id):
raise CmdException("You don't have blacklist manager privileges, which are required to run this command.")
git_response = GitManager.sync_remote_hard()[1]
# Not enough information is passed to commands to send an actual reply. Thus, the reboot
# is scheduled to happen later and we return the results of the GitManager function, which
# is the text that's sent as a reply to the user.
if 'reboot' in alias_used:
Tasks.later(reboot, msg, original_msg=msg, alias_used="reboot", after=5)
return git_response + " Automatically rebooting in a few seconds."
return git_response + " You'll probably want to !!/reboot now."
@command(privileged=True, give_name=True, aliases=[
"gitstatus", "git-status", "git-help", "git-merge-abort", "git-reset"
])
def git(alias_used="git"):
if alias_used == "git":
raise CmdException("Bad alias. Try another command")
if alias_used == "git-help":
return "Available commands: git-help, git-status, git-merge-abort, git-reset"
alias_used = alias_used.replace("-", "")
if alias_used == "gitstatus":
return GitManager.current_git_status()
elif alias_used == "gitmergeabort":
return GitManager.merge_abort()
elif alias_used == "gitreset":
return GitManager.reset_head()
# noinspection PyIncorrectDocstring,PyProtectedMember
@command(whole_msg=True, privileged=True, give_name=True, aliases=["restart", "reload"])
def reboot(msg, alias_used="reboot"):
"""
Forces a system exit with exit code = 5
:param msg:
:return: None
"""
if alias_used in {"reboot", "restart"}:
tell_rooms("{}: Goodbye, cruel world".format(GlobalVars.location),
("debug", (msg._client.host, msg.room.id)), ())
time.sleep(3)
exit_mode("reboot")
elif alias_used in {"reload"}:
reload_modules()
tell_rooms_with('debug', GlobalVars.s_norestart_findspam)
time.sleep(3)
else:
raise RuntimeError("Invalid alias!")
# noinspection PyIncorrectDocstring,PyMissingTypeHints
@command(whole_msg=True)
def amiprivileged(msg):
"""
Tells user whether or not they have privileges
:param msg:
:return: A string
"""
if is_privileged(msg.owner, msg.room):
return "\u2713 You are a privileged user."
return "\u2573 " + GlobalVars.not_privileged_warning
# noinspection PyIncorrectDocstring,
@command(whole_msg=True, aliases=["amicodeprivileged", "amiblacklisterprivileged", "amiblacklistmanagerprivileged"])
def amiblacklistprivileged(msg):
"""
Tells user whether or not they have blacklister privileges
:param msg:
:return: A string
"""
update_code_privileged_users_list()
if is_code_privileged(msg._client.host, msg.owner.id):
return "\u2713 You are a blacklist manager privileged user."
return "\u2573 No, you are not a blacklist manager privileged user."
# noinspection PyIncorrectDocstring
@command()
def apiquota():
"""
Report how many API hits remain for the day
:return: A string
"""
GlobalVars.apiquota_rw_lock.acquire()
current_apiquota = GlobalVars.apiquota
GlobalVars.apiquota_rw_lock.release()
return "The current API quota remaining is {}.".format(current_apiquota)