forked from Charcoal-SE/SmokeDetector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatcommands.py
2834 lines (2427 loc) · 119 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, CmdExceptionLongReply, command, get_report_data, \
is_privileged, message, \
tell_rooms, tell_rooms_with, get_message, is_self
# 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, GitHubManager
import threading
import random
import requests
import sys
import os
import time
import collections
import subprocess
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, remove_regex_comments, regex_compile_no_cache, log_current_exception, \
get_se_api_default_params, get_se_api_default_params_questions_answers_posts_add_site, get_se_api_url_for_route
from classes import Post
from classes.feedback import *
from classes.dns import dns_resolve
from tasks import Tasks
import dns.resolver
from dns.exception import DNSException
import number_homoglyphs
import phone_numbers
# 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 blacklist
: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 "The user has been removed from the user-blacklist (`{}` on `{}`).".format(uid, val)
else:
return "The user is not blacklisted. Perhaps they have already been removed from the blacklist. Please " \
"see: [Blacklists, watchlists, and the user-whitelist: User-blacklist and user-whitelist]" \
"(https://github.com/Charcoal-SE/SmokeDetector/wiki/Commands#user-blacklist-and-user-whitelist) " \
"for more information about when users are added to or removed from the user-blacklist, which is" \
"primarily done with `tpu` and `fp` feedback."
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:
msg_parts = msg.content_source.split(" ", 1)
if msg_parts[0] == "sdc":
return msg_parts[1].split(" ", 1)[1]
else:
return msg_parts[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", "mostly punctuation marks"])
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 get_number_bisect(msg, pattern):
fake_command = '!!/bisect-number ' + pattern
Fake_Message = collections.namedtuple('Fake_Message', ['content', 'content_source', 'owner', 'room'])
fake_message = Fake_Message(fake_command, fake_command, msg.owner, msg.room)
return bisect_number('', original_msg=fake_message)
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
"""
def get_normalized_on_list(list_type, extra=''):
return 'A normalized version, `{}`, of that pattern'.format(normalized_format_escaped) + \
' is already on the number {}list{extra}. You can use'.format(list_type, extra=extra) + \
' `!!/bisect-number {}`'.format(pattern) + \
' to determine which entries on the number lists match that pattern, which' + \
' would tell you: ' + get_number_bisect(msg, pattern)
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` to the command word(s) if you really want to add the pattern you provided."
pattern = get_pattern_from_content_source(msg)
is_watchlist = bool("watch" in blacklist_type)
blacklist_or_watchlist = 'watchlist' if is_watchlist else 'blacklist'
text_before_pattern = ''
text_after_pattern = ''
other_issues = []
if '\u202d' in pattern:
other_issues.append("The pattern contains an invisible U+202D whitespace character.")
if regex.search(r"^\s+", pattern):
other_issues.append("The pattern starts with whitespace.")
if regex.search(r"blogspot\\.", pattern):
other_issues.append("The pattern is for a blogspot domain, but keeps the top level domain (TLD; e.g. `.com`)."
" [For Blogspot, we prefer the TLD to not be included in"
" watchlist/blacklist entries](//chat.stackexchange.com/transcript/message/61694731).")
without_comments = remove_regex_comments(pattern)
if "number" not in blacklist_type:
# Test for . without \., but not in comments.
# Remove character sets, where . doesn't need to be escaped.
test_for_unescaped_dot = regex.sub(r"(?<!\\)\[(?:[^\]]|(?<=\\)\])*\]", "", without_comments)
if regex.search(r"(?<!\\)\.", test_for_unescaped_dot):
other_issues.append('The regex contains an unescaped "`.`", which should be "`\\.`" in most cases.')
try:
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 you really want to add this pattern, you will need to manually submit a PR.")
else:
# When it's a blacklist command, blacklist_type only provides the type of blacklist, not the full command.
blacklist_command = 'blacklist-' + blacklist_type if not is_watchlist \
and 'blacklist' not in blacklist_type else blacklist_type
blacklist_command = blacklist_command.replace("_", "-")
exact_match_text = 'In order for a "number" to make an exact match, the pattern must '
without_comments, comments = phone_numbers.split_processed_and_comments(pattern)
full_entry_list, processed_as_set, normalized = phone_numbers.process_numlist([pattern])
text_after_pattern = ' normalized numbers: ' + str(normalized)
full_entry = full_entry_list[pattern]
processed = full_entry[0]
deobfuscated_processed = phone_numbers.deobfuscate(processed)
normalized_deobfuscated = phone_numbers.normalize(deobfuscated_processed)
pattern_matches_number_regex = phone_numbers.matches_number_regex(without_comments)
deobfuscated_matches_number_regex = phone_numbers.matches_number_regex(deobfuscated_processed)
digit_between_text = "between {} and {} digits".format(phone_numbers.NUMBER_REGEX_MINIMUM_DIGITS,
phone_numbers.NUMBER_REGEX_MAXIMUM_DIGITS)
number_regex_requires = "Patterns for the number" + \
" detections must match the `NUMBER_REGEX` in phone_numbers.py, at least" + \
" when deobfuscated. In order to do so," + \
" it needs to have " + digit_between_text + " and not include" + \
" more than one consecutive alpha character (i.e. matching `[A-Za-z]`)." + \
" Generally, you should watch/blacklist the non-obfuscated version of the number."
if not pattern_matches_number_regex and not deobfuscated_matches_number_regex:
digit_count = len(regex.findall(r'\d', pattern))
digit_count_text = ""
if not phone_numbers.is_digit_count_in_number_regex_range(digit_count):
digit_count_text = " The supplied pattern contains" + \
" {} digits, which doesn't meet the requirements.".format(digit_count)
raise CmdExceptionLongReply("That pattern can't be detected by the number detections. " +
number_regex_requires + digit_count_text)
normalized_format_escaped = str(normalized).replace('{', '{{').replace('}', '}}')
if normalized & GlobalVars.blacklisted_numbers_normalized:
raise CmdExceptionLongReply(get_normalized_on_list('black', extra=''))
if normalized & GlobalVars.watched_numbers_normalized:
# The following differentiates between watching and blacklisting, due to
# automatic movement of entries from the watchlist to the blacklist. It's
# assumed any conflict with something being blacklisted which is an exact
# pattern match for an existing entry on the watchlist will be resolved by the
# automatic removal of the pattern from the watchlist when moved to the
# blacklist. If it isn't resolved, CI testing will fail.
if is_watchlist:
raise CmdExceptionLongReply(get_normalized_on_list('watch', extra=''))
elif pattern not in GlobalVars.watched_numbers_full:
extra_blacklisting_non_exact_match = ' and the pattern you provided is not an exact match' + \
' to an existing entry on the number watchlist'
raise CmdExceptionLongReply(get_normalized_on_list('watch', extra=extra_blacklisting_non_exact_match))
force_is_north_american, force_no_north_american = \
phone_numbers.get_north_american_forced_or_no_from_pattern(pattern)
unused_maybe_north_american_norm = \
phone_numbers.get_maybe_north_american_not_in_normalized_but_in_all(processed, normalized)
north_american_alt = phone_numbers.get_north_american_alternate_normalized(normalized_deobfuscated, force=True)
maybe_north_american_norm = north_american_alt[2]
if deobfuscated_processed != processed:
other_issues.append("That pattern appears to be homoglyph obfuscated. It's better to" +
" use the non-obfuscated number. Perhaps try: " +
"`!!/{} {}`.".format(blacklist_command, deobfuscated_processed))
formatted_north_american = \
phone_numbers.get_north_american_with_separators_from_normalized(normalized_deobfuscated)
north_american_formatting = "use a format which starts with an optional `1` followed by" + \
" possible separator text and has the main" + \
" number in the format `{}`".format(formatted_north_american[-12:]) + \
" where `-` could be a single alpha character" + \
" or any `[\\W_]*+`. Alternately, you can add the comment `(?#IS NorAm)` to the" + \
" end of the pattern to force also using the alternate normalized form, or" + \
" `(?#NO NorAm)` if it's not a North American phone number and it's" + \
" incorrectly recognized as one." + \
" Perhaps try \n`!!/{} {}`.\n".format(blacklist_command, formatted_north_american)
if not force_no_north_american and unused_maybe_north_american_norm:
other_issues.append("That pattern may be a North American number. If it is, please " +
north_american_formatting)
unused_na_on_list = 'That pattern may be a North American number and the alternate normalized verison' + \
' is already on the {}list. This indicates a potential conflict. Ideally, there should' + \
' be one entry which is automatically used normalized both with and without a "1". The' + \
' version which is already in use is: `{}`, but it\'s not automatically recognized as' + \
' a North American number.'
if unused_maybe_north_american_norm in GlobalVars.blacklisted_numbers_normalized:
other_issues.append(unused_na_on_list.format("black", unused_maybe_north_american_norm))
if unused_maybe_north_american_norm in GlobalVars.watched_numbers_normalized:
other_issues.append(unused_na_on_list.format("watch", unused_maybe_north_american_norm))
if not phone_numbers.matches_number_regex_start(without_comments):
other_issues.append(exact_match_text + 'begin with a digit' +
' or up to two of `+`,`(`,`[`, or `{` immediately followed by a digit.')
if not phone_numbers.matches_number_regex_end(without_comments):
other_issues.append(exact_match_text + 'end with a digit.')
other_issues_text = ' '.join(other_issues)
if len(other_issues_text) > 350:
other_issues_text = '\n'.join(other_issues) + '\n'
other_issues_text = other_issues_text.replace('\n\n', '\n')
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
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:
raise CmdExceptionLongReply("That pattern looks like it's already caught by " +
format_blacklist_reasons(reasons) + other_issues_text + append_force_to_do)
if other_issues_text:
raise CmdExceptionLongReply(other_issues_text + 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,
before_pattern=text_before_pattern,
after_pattern=text_after_pattern
)
if not _status:
raise CmdException(result)
if code_permissions:
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", and_file=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
additional_state = (" However, the blacklists were not reloaded at this time. The most likely issue"
" is another change was made on SD's master branch on GitHub and everything"
" is waiting for CI to pass and MS to update the deploy branch.")
if GlobalVars.MSStatus.is_down():
additional_state += (" But, metasmoke is currently down, so that won't happen. Someone with write"
" permission to SD's GitHub reository will need to manually update the deploy"
" branch. Usually, this means you should ping an MS admin.")
else:
additional_state += (" That could take a few to several minutes. If SD doesn't automatically reload"
" the blacklists or automatically reboot after that time, then someone should"
" investigate why that hasn't happened.")
return result + additional_state
else:
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.replace("_", "-").split("-")
return do_blacklist(parts[1], msg, force='force' in alias_used)
# 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", and_file=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, aliases=["accept"])
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", and_file=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(str, privileged=True, whole_msg=True, give_name=True, aliases=["close", "reject-force", "close-force"])
def reject(msg, args, alias_used="reject"):
argsraw = args.split(' "', 1)
try:
pr_id = int(argsraw[0].split(' ')[0])
except ValueError:
reason = ''
pr_id = int(args.split(' ')[2])
try:
# Custom handle trailing quotation marks at the end of the custom reason, which could happen.
if argsraw[1][-1] == '"':
reason = argsraw[1][:-1]
else:
reason = argsraw[1]
except IndexError:
reason = ''
force = alias_used.split("-")[-1] == "force"
code_permissions = is_code_privileged(msg._client.host, msg.owner.id)
pr_object = GitHubManager.get_pull_request(pr_id)
pr_body = pr_object.json()['body']
pr_author_id = regex.search(r"(?<=\/users\/)\d+", pr_body).group(0)
self_reject = int(pr_author_id) == int(msg.owner.id)
if not code_permissions and not self_reject:
raise CmdException("You need blacklist manager privileges to reject pull requests "
"that aren't created by you.")
if len(reason) < 20 and not force:
raise CmdException("Please provide an adequate reason for rejection that is at least"
" 20 characters long. Use `-force` to ignore this requirement.")
rejected_image = "https://camo.githubusercontent.com/" \
"77d8d14b9016e415d36453f27ccbe06d47ef5ae2/68747470733a" \
"2f2f7261737465722e736869656c64732e696f2f62616467652f626c6" \
"1636b6c6973746572732d72656a65637465642d7265642e706e67"
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)
rejected_by_text = "[Rejected]({}) by [{}]({}) in {}.".format(message_url, msg.owner.name,
chat_user_profile_link, msg.room.name)
if self_reject:
rejected_by_text = "[Self-rejected]({}) by [{}]({}) in {}.".format(message_url, msg.owner.name,
chat_user_profile_link, msg.room.name)
reject_reason_text = " No rejection reason was provided.\n\n"
if reason:
reject_reason_text = " Reason: '{}'".format(reason)
reject_reason_image_text = "\n\n![Rejected with SmokeyReject]({})".format(rejected_image)
if self_reject:
reject_reason_image_text = ""
comment = rejected_by_text + reject_reason_text + reject_reason_image_text
try:
message = GitManager.reject_pull_request(pr_id, comment, self_reject)
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")
@command(str, str, str, give_name=True, arity=(0, 3), privileged=True, aliases=["stats", "scan-stat", "statistics",
"stats-force", "scan-stat-force",
"statistics-force", "stat-force"])
def stat(operation, from_stats=None, to_stats=None, alias_used="stats"):
""" Return post scan statistics. """
# As of Python 3.6+, dicts are iterated in insertion order.
report_order_with_defaults = {
'posts_scanned': 0,
'scan_time': 0,
'posts_per_second': 0,
'grace_period_edits': 0,
'unchanged_posts': 0,
'no_post_lock': 0,
'errors': 0,