forked from Charcoal-SE/SmokeDetector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatcommands.py
1647 lines (1350 loc) · 59.2 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
# noinspection PyUnresolvedReferences
from globalvars import GlobalVars
from findspam import FindSpam
# noinspection PyUnresolvedReferences
from datetime import datetime
from utcdate import UtcDate
from apigetpost import api_get_post, PostData
import datahandling
from datahandling import *
from blacklists import load_blacklists
from parsing import *
from spamhandling import check_if_spam, handle_spam
from gitmanager import GitManager
import threading
import random
import requests
import os
import time
from html import unescape
from ast import literal_eval
# noinspection PyCompatibility
import regex
from helpers import only_blacklists_changed, log, expand_shorthand_link, to_metasmoke_link
from classes import Post
from classes.feedback import *
# 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 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.test_post(question)
answer_reasons, _ = FindSpam.test_post(answer)
# Filter out duplicates
reasons = list(set(question_reasons) | set(answer_reasons))
# Filter out watchlist results
filter_out = ["potentially bad ns"]
if not is_watchlist:
filter_out.append("potentially bad keyword")
# Ignore "Mostly non-latin body/answer" for phone number watches
elif is_phone:
filter_out.append("mostly non-latin")
if filter_out:
reasons = list(filter(
lambda reason: all([x not in reason.lower() for x in filter_out]), reasons))
return reasons
def format_blacklist_reasons(reasons):
# Capitalize
reasons = list(map(lambda reason: reason.capitalize(), 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 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
"""
chat_user_profile_link = "https://chat.{host}/users/{id}".format(host=msg._client.host,
id=msg.owner.id)
# noinspection PyProtectedMember
pattern = rebuild_str(msg.content_source.split(" ", 1)[1])
try:
regex.compile(pattern, city=FindSpam.city_list)
except regex._regex_core.error:
raise CmdException("An invalid pattern was provided, not blacklisting.")
if not force:
if regex.match(r'(?:\[a-z_]\*)?(?:\(\?:)?\d+(?:[][\\W_*()?:]+\d+)+(?:\[a-z_]\*)?$', pattern):
is_phone = True
else:
is_phone = False
is_watchlist = bool(blacklist_type == 'watch_keyword')
concretized_pattern = pattern.replace("\\W", " ").replace("\\.", ".").replace("\\d", "8")
for username in False, True:
reasons = check_blacklist(
concretized_pattern, is_username=username, is_watchlist=is_watchlist, is_phone=is_phone)
if reasons:
raise CmdException(
"That pattern looks like it's already caught by " +
format_blacklist_reasons(reasons) +
"; append `-force` if you really want to do that.")
metasmoke_down = False
try:
code_permissions = is_code_privileged(msg._client.host, msg.owner.id)
except (requests.exceptions.ConnectionError, json.decoder.JSONDecodeError):
code_permissions = False # Because we need the system to assume that we don't have code privs.
metasmoke_down = True
_, 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
)
return result
# noinspection PyIncorrectDocstring
@command(str, whole_msg=True, privileged=True, give_name=True, aliases=["blacklist-keyword",
"blacklist-website",
"blacklist-username",
"blacklist-keyword-force",
"blacklist-website-force",
"blacklist-username-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"])
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_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.")
metasmoke_down = False
try:
code_privs = is_code_privileged(msg._client.host, msg.owner.id)
except (requests.exceptions.ConnectionError, json.decoder.JSONDecodeError):
code_privs = False
metasmoke_down = True
pattern = msg.content_source.split(" ", 1)[1]
_status, message = GitManager.remove_from_blacklist(
rebuild_str(pattern), msg.owner.name, blacklist_type,
code_privileged=code_privs, metasmoke_down=metasmoke_down)
return message
# noinspection PyIncorrectDocstring
@command(privileged=True)
def gitstatus():
return GitManager.current_git_status()
@command(privileged=True, aliases=["remote-diff", "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}
user = sum([(len(base)**i) * base[char] for i, char in enumerate(reversed(x))])
try:
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 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(2017, 12, 13, 0, 0, 0)
wb_end = datetime(2018, 1, 3, 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 --- #
# noinspection PyIncorrectDocstring
@command(aliases=["live"])
def alive():
"""
Returns a string indicating the process is still active
:return: A string
"""
return random.choice(['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'])
# 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 50)
# 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
"""
os._exit(8)
# noinspection PyIncorrectDocstring,PyProtectedMember
@command(privileged=True)
def pull():
"""
Pull an update from GitHub
:return: String on failure, None on success
"""
if only_blacklists_changed(GitManager.get_remote_diff()):
GitManager.pull_remote()
load_blacklists()
return "No code modified, only blacklists reloaded."
else:
request = requests.get('https://api.github.com/repos/Charcoal-SE/SmokeDetector/git/refs/heads/deploy')
latest_sha = request.json()["object"]["sha"]
request = requests.get(
'https://api.github.com/repos/Charcoal-SE/SmokeDetector/commits/{commit_code}/statuses'.format(
commit_code=latest_sha))
states = []
for ci_status in request.json():
state = ci_status["state"]
states.append(state)
if "success" in states:
os._exit(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.")
# noinspection PyIncorrectDocstring,PyProtectedMember
@command(whole_msg=True, privileged=True, aliases=["restart"])
def reboot(msg):
"""
Forces a system exit with exit code = 5
:param msg:
:return: None
"""
tell_rooms("Goodbye, cruel world", ("debug", (msg._client.host, msg.room.id)), ())
time.sleep(3)
os._exit(5)
# 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)
def amicodeprivileged(msg):
"""
Tells user whether or not they have code privileges
:param msg:
:return: A string
"""
if is_code_privileged(msg._client.host, msg.owner.id):
return "\u2713 You are a code-privileged user."
return "\u2573 No, you are not a code-privileged user."
# noinspection PyIncorrectDocstring
@command()
def apiquota():
"""
Report how many API hits remain for the day
:return: A string
"""
return "The current API quota remaining is {}.".format(GlobalVars.apiquota)
# noinspection PyIncorrectDocstring
@command()
def queuestatus():
"""
Report current API queue
:return: A string
"""
return GlobalVars.bodyfetcher.print_queue()
@command(str)
def inqueue(url):
post_id, site, post_type = fetch_post_id_and_site_from_url(url)
if post_type != "question":
raise CmdException("Can't check for answers.")
if site in GlobalVars.bodyfetcher.queue:
for i, id in enumerate(GlobalVars.bodyfetcher.queue[site].keys()):
if id == post_id:
return "#" + str(i + 1) + " in queue."
return "Not in queue."
@command()
def listening():
# return "{} post(s) currently monitored for deletion.".format(len(GlobalVars.deletion_watcher.posts))
return "Currently listening to:\n" + repr(GlobalVars.deletion_watcher.posts)
@command()
def last_feedbacked():
return datahandling.last_feedbacked
# noinspection PyIncorrectDocstring,PyProtectedMember
@command(str, whole_msg=True, privileged=True, arity=(0, 1))
def stappit(msg, location_search):
"""
Forces a system exit with exit code = 6
:param msg:
:param location_search:
:return: None
"""
if location_search is None or location_search.lower() in GlobalVars.location.lower():
tell_rooms("Goodbye, cruel world", ((msg._client.host, msg.room.id)), ())
time.sleep(3)
os._exit(6)
def td_format(td_object):
# source: http://stackoverflow.com/a/13756038/5244995
seconds = int(td_object.total_seconds())
periods = [
('year', 60 * 60 * 24 * 365),
('month', 60 * 60 * 24 * 30),
('day', 60 * 60 * 24),
('hour', 60 * 60),
('minute', 60),
('second', 1)
]
strings = []
for period_name, period_seconds in periods:
if seconds > period_seconds:
period_value, seconds = divmod(seconds, period_seconds)
if period_value == 1:
strings.append("%s %s" % (period_value, period_name))
else:
strings.append("%s %ss" % (period_value, period_name))
return ", ".join(strings)
# noinspection PyIncorrectDocstring
@command()
def status():
"""
Returns the amount of time the application has been running
:return: A string
"""
now = datetime.utcnow()
diff = now - UtcDate.startup_utc_date
return 'Running since {time} UTC ({relative})'.format(time=GlobalVars.startup_utc, relative=td_format(diff))
# noinspection PyIncorrectDocstring
@command(privileged=True, whole_msg=True)
def stopflagging(msg):
Tasks.do(Metasmoke.stop_autoflagging)
log('warning', 'Disabling autoflagging ({} ran !!/stopflagging, message {})'.format(msg.owner.name, msg.id))
return 'Stopping'
# noinspection PyIncorrectDocstring,PyProtectedMember
@command(str, whole_msg=True, privileged=True, aliases=["standby-except"], give_name=True)
def standby(msg, location_search, alias_used="standby"):
"""
Forces a system exit with exit code = 7
:param msg:
:param location_search:
:return: None
"""
match = location_search.lower() in GlobalVars.location.lower()
reverse_search = "except" in alias_used
# Use `!=` as Logical XOR
if match != reverse_search:
tell_rooms("{location} is switching to standby".format(location=GlobalVars.location),
("debug", (msg._client.host, msg.room.id)), (), notify_site="/standby")
time.sleep(3)
os._exit(7)
# noinspection PyIncorrectDocstring
@command(str, aliases=["test-q", "test-a", "test-u", "test-t"], give_name=True)
def test(content, alias_used="test"):
"""
Test an answer to determine if it'd be automatically reported
:param content:
:return: A string
"""
result = "> "
site = ""
option_count = 0
for segment in content.split():
if segment.startswith("site="):
site = expand_shorthand_link(segment[5:])
else:
# Stop parsing options at first non-option
break
option_count += 1
content = content.split(' ', option_count)[-1] # Strip parsed options
if alias_used == "test-q":
kind = "a question"
fakepost = Post(api_response={'title': 'Valid title', 'body': content,
'owner': {'display_name': "Valid username", 'reputation': 1, 'link': ''},
'site': site, 'IsAnswer': False, 'score': 0})
elif alias_used == "test-a":
kind = "an answer"
fakepost = Post(api_response={'title': 'Valid title', 'body': content,
'owner': {'display_name': "Valid username", 'reputation': 1, 'link': ''},
'site': site, 'IsAnswer': True, 'score': 0})
elif alias_used == "test-u":
kind = "a username"
fakepost = Post(api_response={'title': 'Valid title', 'body': "Valid question body",
'owner': {'display_name': content, 'reputation': 1, 'link': ''},
'site': site, 'IsAnswer': False, 'score': 0})
elif alias_used == "test-t":
kind = "a title"
fakepost = Post(api_response={'title': content, 'body': "Valid question body",
'owner': {'display_name': "Valid username", 'reputation': 1, 'link': ''},
'site': site, 'IsAnswer': False, 'score': 0})
else:
kind = "a post, title or username"
fakepost = Post(api_response={'title': content, 'body': content,
'owner': {'display_name': content, 'reputation': 1, 'link': ''},
'site': site, 'IsAnswer': False, 'score': 0})
reasons, why_response = FindSpam.test_post(fakepost)
if len(reasons) == 0:
result += "Would not be caught as {}".format(kind)
if site == "chat.stackexchange.com":
result += " on this magic userspace"
elif len(site) > 0:
result += " on site `{}`".format(site)
result += "."
else:
result += ", ".join(reasons).capitalize()
if why_response is not None and len(why_response) > 0:
result += "\n----------\n"
result += why_response
return result
# noinspection PyIncorrectDocstring
@command()
def threads():
"""
Returns a description of current threads, for debugging
:return: A string
"""
threads_list = ["{ident}: {name}".format(ident=t.ident, name=t.name) for t in threading.enumerate()]
return "\n".join(threads_list)
# noinspection PyIncorrectDocstring
@command(aliases=["rev", "ver"])
def version():
"""
Returns the current version of the application
:return: A string
"""
return '{id} [{commit_name}]({repository}/commit/{commit_code})'.format(id=GlobalVars.location,
commit_name=GlobalVars.commit_with_author,
commit_code=GlobalVars.commit['id'],
repository=GlobalVars.bot_repository)
# noinspection PyIncorrectDocstring
@command(whole_msg=True)
def whoami(msg):
"""
Returns user id of smoke detector
:param msg:
:return:
"""
return "My id for this room is {}, and it's not apnorton's fault.".format(msg._client._br.user_id)
# --- Notification functions --- #
# noinspection PyIncorrectDocstring
@command(int, whole_msg=True, aliases=["allnotifications", "allnoti"])
def allnotificationsites(msg, room_id):
"""
Returns a string stating what sites a user will be notified about
:param msg:
:param room_id:
:return: A string
"""
sites = get_all_notification_sites(msg.owner.id, msg._client.host, room_id)
if len(sites) == 0:
return "You won't get notified for any sites in that room."
return "You will get notified for these sites:\r\n" + ", ".join(sites)
# noinspection PyIncorrectDocstring,PyMissingTypeHints
@command(int, str, literal_eval, whole_msg=True, arity=(2, 3))
def notify(msg, room_id, se_site, always_ping):
"""
Subscribe a user to events on a site in a single room
:param msg:
:param room_id:
:param se_site:
:return: A string
"""
# TODO: Add check whether smokey reports in that room
response, full_site = add_to_notification_list(msg.owner.id, msg._client.host, room_id, se_site,
always_ping=(always_ping if always_ping is not None else True))
if response == 0:
return "You'll now get pings from me if I report a post on `{site}`, in room "\
"`{room}` on `chat.{domain}`".format(site=se_site, room=room_id, domain=msg._client.host)
elif response == -1:
raise CmdException("That notification configuration is already registered.")
elif response == -2:
raise CmdException("The given SE site does not exist.")
else:
raise CmdException("Unrecognized code returned when adding notification.")
# temp command
@command(privileged=True)
def migrate_notifications():
for i, notification in enumerate(GlobalVars.notifications):
if len(notification) == 4:
GlobalVars.notifications[i] = notification + (True,)
with open("notifications.p", "wb") as f:
pickle.dump(GlobalVars.notifications, f, protocol=pickle.HIGHEST_PROTOCOL)
return "shoutouts to simpleflips"
# noinspection PyIncorrectDocstring,PyMissingTypeHints
@command(whole_msg=True, aliases=["unnotify-all"])
def unnotify_all(msg):
"""
Unsubscribes a user to all events
:param msg:
:return: A string
"""
remove_all_from_notification_list(msg.owner.id)
return "I will no longer ping you if I report a post anywhere."
# noinspection PyIncorrectDocstring,PyMissingTypeHints
@command(int, str, whole_msg=True)
def unnotify(msg, room_id, se_site):
"""
Unsubscribes a user to specific events
:param msg:
:param room_id:
:param se_site:
:return: A string
"""
response = remove_from_notification_list(msg.owner.id, msg._client.host, room_id, se_site)
if response:
return "I will no longer ping you if I report a post on `{site}`, in room `{room}` "\
"on `chat.{domain}`".format(site=se_site, room=room_id, domain=msg._client.host)
raise CmdException("That configuration doesn't exist.")