forked from Charcoal-SE/SmokeDetector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatcommands.py
1850 lines (1632 loc) · 72.6 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 globalvars import GlobalVars
from findspam import FindSpam
# noinspection PyUnresolvedReferences
from datetime import datetime
from utcdate import UtcDate
from apigetpost import api_get_post
from datahandling import *
from blacklists import load_blacklists
from metasmoke import Metasmoke
from parsing import *
from spamhandling import handle_spam
from spamhandling import handle_user_with_all_spam
from gitmanager import GitManager
import threading
from threading import Thread
import random
import requests
import os
import time
# noinspection PyCompatibility
import regex
from helpers import Response, only_blacklists_changed
from classes import Post
# TODO: pull out code block to get user_id, chat_site, room_id into function
# TODO: Return result for all functions should be similar (tuple/named tuple?)
# TODO: Do we need uid == -2 check? Turn into "is_user_valid" check
# TODO: Consistant return structure
# if return...else return vs if return...return
# noinspection PyMissingTypeHints
def check_permissions(function_):
# noinspection PyMissingTypeHints
def run_command(ev_room, ev_user_id, wrap2, *args, **kwargs):
if is_privileged(ev_room, ev_user_id, wrap2):
kwargs['ev_room'] = ev_room
kwargs['ev_user_id'] = ev_user_id
kwargs['wrap2'] = wrap2
return function_(*args, **kwargs)
else:
return Response(command_status=False,
message=GlobalVars.not_privileged_warning)
return run_command
# Functions go before the final dictionaries of command to function mappings
def post_message_in_room(room_id_str, msg, length_check=True):
if room_id_str == GlobalVars.charcoal_room_id:
GlobalVars.charcoal_hq.send_message(msg, length_check)
elif room_id_str == GlobalVars.meta_tavern_room_id:
GlobalVars.tavern_on_the_meta.send_message(msg, length_check)
elif room_id_str == GlobalVars.socvr_room_id:
GlobalVars.socvr.send_message(msg, length_check)
# noinspection PyMissingTypeHints
def is_report(post_site_id):
"""
Checks if a post is a report
:param post_site_id: Report to check
:return: Boolean stating if it is a report
"""
if post_site_id is None:
return False
return True
# noinspection PyIncorrectDocstring,PyUnusedLocal,PyMissingTypeHints
def send_metasmoke_feedback(post_url, second_part_lower, ev_user_name, ev_user_id, ev_chat_host):
"""
Sends feedback to metasmoke
:param ev_user_name:
:param post_url: The post url we are sending
:param second_part_lower: Feedback
:param ev_user_name: User name supplying the feedback
:param ev_user_id: User ID supplying the feedback
:return: None
"""
t_metasmoke = Thread(name="metasmoke feedback send on #{url}".format(url=post_url),
target=Metasmoke.send_feedback_for_post,
args=(post_url, second_part_lower, ev_user_name, ev_user_id, ev_chat_host,))
t_metasmoke.start()
# noinspection PyMissingTypeHints
def single_random_user(ev_room):
"""
Returns a single user name from users in a room
:param ev_room: Room to select users from
:return: A single user tuple
"""
return random.choice(GlobalVars.users_chatting[ev_room])
#
#
# System command functions below here
# Each of these should take the *args and **kwargs parameters. This allows us to create functions that
# don't accept any parameters but still use the `command_dict` mappings
@check_permissions
def command_approve(message_parts, content_lower, ev_room, ev_user_id, wrap2, *args, **kwargs):
if is_code_privileged(ev_room, ev_user_id, wrap2):
if len(message_parts) >= 2:
pr_num = message_parts[1]
resp = requests.post('{}/github/pr_approve/{}'.format(GlobalVars.metasmoke_host, pr_num))
if resp.status_code == 200:
return Response(command_status=True, message='Posted approval comment. PR will be merged automatically '
'if it\'s a blacklist PR.')
else:
return Response(command_status=False, message='Forwarding request to metasmoke returned HTTP {}. '
'Check status manually.'.format(resp.status_code))
else:
return Response(command_status=False, message='Missing PR ID. Usage: !!/approve <id>')
else:
return Response(command_status=False, message='You don\'t have permission to do that.')
# --- Blacklist Functions --- #
# noinspection PyIncorrectDocstring,PyUnusedLocal
@check_permissions
def command_add_blacklist_user(message_parts, content_lower, message_url, ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Adds a user to the site blacklist
:param wrap2:
:param ev_user_id:
:param ev_room:
:param message_url:
:param content_lower:
:param message_parts:
:param kwargs: No additional arguments expected
:return: A string
"""
quiet_action = any([part.endswith('-') for part in message_parts])
uid, val = get_user_from_list_command(content_lower)
if int(uid) > -1 and val != "":
add_blacklisted_user((uid, val), message_url, "")
return Response(command_status=True, message=None) if quiet_action \
else Response(command_status=True, message="User blacklisted (`{}` on `{}`).".format(uid, val))
elif int(uid) == -2:
return Response(command_status=True, message="Error: {}".format(val))
else:
return Response(command_status=False,
message="Invalid format. Valid format: `!!/addblu profileurl` "
"*or* `!!/addblu userid sitename`.")
# noinspection PyIncorrectDocstring,PyUnusedLocal,PyMissingTypeHints
def command_check_blacklist(content_lower, *args, **kwargs):
"""
Checks if a user is blacklisted
:param content_lower:
:param kwargs: No additional arguments expected
:return: A string
"""
uid, val = get_user_from_list_command(content_lower)
if int(uid) > -1 and val != "":
if is_blacklisted_user((uid, val)):
return Response(command_status=True, message="User is blacklisted (`{}` on `{}`).".format(uid, val))
else:
return Response(command_status=True, message="User is not blacklisted (`{}` on `{}`).".format(uid, val))
elif int(uid) == -2:
return Response(command_status=True, message="Error: {}".format(val))
else:
return Response(command_status=False,
message="Invalid format. Valid format: `!!/isblu profileurl` *or* `!!/isblu userid sitename`.")
# noinspection PyIncorrectDocstring,PyUnusedLocal
@check_permissions
def command_remove_blacklist_user(message_parts, content_lower, ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Removes user from site blacklist
:param wrap2:
:param ev_user_id:
:param ev_room:
:param content_lower:
:param message_parts:
:param kwargs: No additional arguments expected
:return: A string
"""
quiet_action = any([part.endswith('-') for part in message_parts])
uid, val = get_user_from_list_command(content_lower)
if int(uid) > -1 and val != "":
if remove_blacklisted_user((uid, val)):
return Response(command_status=True, message=None) if quiet_action \
else Response(command_status=True,
message="User removed from blacklist (`{}` on `{}`).".format(uid, val))
else:
return Response(command_status=True, message="User is not blacklisted.")
elif int(uid) == -2:
return Response(command_status=True, message="Error: {}".format(val))
else:
return Response(command_status=False,
message="Invalid format. Valid format: `!!/rmblu profileurl` *or* `!!/rmblu userid sitename`.")
# --- Whitelist functions --- #
# noinspection PyIncorrectDocstring,PyUnusedLocal,PyMissingTypeHints
@check_permissions
def command_add_whitelist_user(message_parts, content_lower, ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Adds a user to site whitelist
:param wrap2:
:param ev_user_id:
:param ev_room:
:param content_lower:
:param message_parts:
:param kwargs: No additional arguments expected
:return: A string
"""
quiet_action = any([part.endswith('-') for part in message_parts])
uid, val = get_user_from_list_command(content_lower)
if int(uid) > -1 and val != "":
add_whitelisted_user((uid, val))
return Response(command_status=True, message=None) if quiet_action \
else Response(command_status=True, message="User whitelisted (`{}` on `{}`).".format(uid, val))
elif int(uid) == -2:
return Response(command_status=True, message="Error: {}".format(val))
else:
return Response(command_status=False,
message="Invalid format. Valid format: `!!/addwlu profileurl` *or* "
"`!!/addwlu userid sitename`.")
# noinspection PyIncorrectDocstring,PyUnusedLocal,PyMissingTypeHints
def command_check_whitelist(content_lower, *args, **kwargs):
"""
Checks if a user is whitelisted
:param content_lower:
:param kwargs: No additional arguments expected
:return: A string
"""
uid, val = get_user_from_list_command(content_lower)
if int(uid) > -1 and val != "":
if is_whitelisted_user((uid, val)):
return Response(command_status=True, message="User is whitelisted (`{}` on `{}`).".format(uid, val))
else:
return Response(command_status=True, message="User is not whitelisted (`{}` on `{}`).".format(uid, val))
elif int(uid) == -2:
return Response(command_status=True, message="Error: {}".format(val))
else:
return Response(command_status=False,
message="Invalid format. Valid format: `!!/iswlu profileurl` *or* `!!/iswlu userid sitename`.")
# noinspection PyIncorrectDocstring,PyUnusedLocal,PyMissingTypeHints
@check_permissions
def command_remove_whitelist_user(message_parts, content_lower, ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Removes a user from site whitelist
:param wrap2:
:param ev_user_id:
:param ev_room:
:param content_lower:
:param message_parts:
:param kwargs: No additional arguments expected
:return: A string
"""
quiet_action = any([part.endswith('-') for part in message_parts])
uid, val = get_user_from_list_command(content_lower)
if int(uid) != -1 and val != "":
if remove_whitelisted_user((uid, val)):
return Response(command_status=True, message=None) if quiet_action \
else Response(command_status=True,
message="User removed from whitelist (`{}` on `{}`).".format(uid, val))
else:
return Response(command_status=True, message="User is not whitelisted.")
elif int(uid) == -2:
return Response(command_status=True, message="Error: {}".format(val))
else:
return Response(command_status=False,
message="Invalid format. Valid format: `!!/rmwlu profileurl` *or* `!!/rmwlu userid sitename`.")
# noinspection PyIncorrectDocstring,PyUnusedLocal
@check_permissions
def command_blacklist_help(*args, **kwargs):
"""
Returns a string which explains the usage of the new blacklist commands.
:return: A string
"""
return Response(command_status=True,
message="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):
# 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
if not is_watchlist:
reasons = list(filter(lambda reason: "potentially bad keyword" not in reason, 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(**kwargs):
"""
Adds a string to the website blacklist and commits/pushes to GitHub
:param message_parts:
:param ev_user_name:
:param ev_room:
:param :ev_user_id:
:return: A Response
"""
chat_user_profile_link = "http://chat.{host}/users/{id}".format(host=kwargs['wrap2'].host,
id=str(kwargs['ev_user_id']))
pattern = " ".join(kwargs['message_parts'][1:])
# noinspection PyProtectedMember
try:
regex.compile(pattern)
except regex._regex_core.error:
return Response(command_status=False, message="An invalid pattern was provided, not blacklisting.")
if not kwargs['force']:
reasons = check_blacklist(pattern.replace("\\W", " ").replace("\\.", "."),
kwargs['blacklist'] == "username",
kwargs['blacklist'] == "watch_keyword")
if reasons:
return Response(command_status=False,
message="That pattern looks like it's already caught by " +
format_blacklist_reasons(reasons) + "; use `" +
kwargs['message_parts'][0] + "-force` if you really want to do that.")
result = GitManager.add_to_blacklist(
blacklist=kwargs['blacklist'],
item_to_blacklist=pattern,
username=kwargs['ev_user_name'],
chat_profile_link=chat_user_profile_link,
code_permissions=is_code_privileged(kwargs['ev_room'], kwargs['ev_user_id'], kwargs['wrap2'])
)
return Response(command_status=result[0], message=result[1])
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_blacklist_website(message_parts, ev_user_name, ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Adds a string to the website blacklist and commits/pushes to GitHub
:param message_parts:
:param ev_user_name:
:param ev_room:
:param :ev_user_id:
:return: A Response
"""
return do_blacklist(blacklist="website", force=False, message_parts=message_parts,
ev_user_name=ev_user_name, ev_room=ev_room, ev_user_id=ev_user_id, wrap2=wrap2)
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_blacklist_keyword(message_parts, ev_user_name, ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Adds a string to the keyword blacklist and commits/pushes to GitHub
:param message_parts:
:param ev_user_name:
:param ev_room:
:param :ev_user_id:
:return: A Response
"""
return do_blacklist(blacklist="keyword", force=False, message_parts=message_parts,
ev_user_name=ev_user_name, ev_room=ev_room, ev_user_id=ev_user_id, wrap2=wrap2)
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_watch_keyword(message_parts, ev_user_name, ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Adds a string to the watched keywords list and commits/pushes to GitHub
:param message_parts:
:param ev_user_name:
:param ev_room:
:param :ev_user_id:
:return: A Response
"""
return do_blacklist(blacklist="watch_keyword", force=False, message_parts=message_parts,
ev_user_name=ev_user_name, ev_room=ev_room, ev_user_id=ev_user_id, wrap2=wrap2)
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_blacklist_username(message_parts, ev_user_name, ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Adds a string to the username blacklist and commits/pushes to GitHub
:param message_parts:
:param ev_user_name:
:param ev_room:
:param :ev_user_id:
:return: A Response
"""
return do_blacklist(blacklist="username", force=False, message_parts=message_parts,
ev_user_name=ev_user_name, ev_room=ev_room, ev_user_id=ev_user_id, wrap2=wrap2)
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_force_blacklist_website(message_parts, ev_user_name, ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Adds a string to the website blacklist and commits/pushes to GitHub
:param message_parts:
:param ev_user_name:
:param ev_room:
:param :ev_user_id:
:return: A Response
"""
return do_blacklist(blacklist="website", force=True, message_parts=message_parts,
ev_user_name=ev_user_name, ev_room=ev_room, ev_user_id=ev_user_id, wrap2=wrap2)
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_force_blacklist_keyword(message_parts, ev_user_name, ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Adds a string to the keyword blacklist and commits/pushes to GitHub
:param message_parts:
:param ev_user_name:
:param ev_room:
:param :ev_user_id:
:return: A Response
"""
return do_blacklist(blacklist="keyword", force=True, message_parts=message_parts,
ev_user_name=ev_user_name, ev_room=ev_room, ev_user_id=ev_user_id, wrap2=wrap2)
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_force_watch_keyword(message_parts, ev_user_name, ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Adds a string to the watched keywords list and commits/pushes to GitHub
:param message_parts:
:param ev_user_name:
:param ev_room:
:param :ev_user_id:
:return: A Response
"""
return do_blacklist(blacklist="watch_keyword", force=True, message_parts=message_parts,
ev_user_name=ev_user_name, ev_room=ev_room, ev_user_id=ev_user_id, wrap2=wrap2)
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_force_blacklist_username(message_parts, ev_user_name, ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Adds a string to the username blacklist and commits/pushes to GitHub
:param message_parts:
:param ev_user_name:
:param ev_room:
:param :ev_user_id:
:return: A Response
"""
return do_blacklist(blacklist="username", force=True, message_parts=message_parts,
ev_user_name=ev_user_name, ev_room=ev_room, ev_user_id=ev_user_id, wrap2=wrap2)
# noinspection PyIncorrectDocstring,PyUnusedLocal
@check_permissions
def command_gitstatus(wrap2, *args, **kwargs):
return Response(command_status=True, message=GitManager.current_git_status())
@check_permissions
def command_remotediff(*args, **kwargs):
will_require_full_restart = "SmokeDetector will require a full restart to pull changes: " \
"{}".format(str(not only_blacklists_changed(GitManager.get_remote_diff())))
return Response(command_status=True, message="{}\n\n{}".format(GitManager.get_remote_diff(),
will_require_full_restart))
# --- Joke Commands --- #
# noinspection PyIncorrectDocstring,PyUnusedLocal,PyMissingTypeHints
def command_blame(ev_room, *args, **kwargs):
"""
Returns a string with a user to blame (This is a joke command)
:param ev_room:
:param kwargs: No additional arguments expected
:return: A string
"""
GlobalVars.users_chatting[ev_room] = list(set(GlobalVars.users_chatting[ev_room]))
user_to_blame = single_random_user(ev_room)
return Response(command_status=True, message=u"It's [{}]({})'s fault.".format(user_to_blame[0], user_to_blame[1]))
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_brownie(*args, **kwargs):
"""
Returns a string equal to "Brown!" (This is a joke command)
:return: A string
"""
return Response(command_status=True, message="Brown!")
# noinspection PyIncorrectDocstring,PyUnusedLocal,PyMissingTypeHints
def command_coffee(ev_user_name, *args, **kwargs):
"""
Returns a string stating who the coffee is for (This is a joke command)
:param ev_user_name:
:param kwargs: No additional arguments expected
:return: A string
"""
return Response(command_status=True, message=u"*brews coffee for @" + ev_user_name.replace(" ", "") + "*")
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_lick(*args, **kwargs):
"""
Returns a string when a user says 'lick' (This is a joke command)
:return: A string
"""
return Response(command_status=True, message="*licks ice cream cone*")
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_tea(ev_user_name, *args, **kwargs):
"""
Returns a string stating who the tea is for (This is a joke command)
:param ev_user_name:
:param kwargs: No additional arguments expected
:return: A string
"""
return Response(command_status=True,
message=u"*brews a cup of {choice} tea for @{user}*".format(
choice=random.choice(['earl grey', 'green', 'chamomile',
'lemon', 'darjeeling', 'mint', 'jasmine']),
user=ev_user_name.replace(" ", "")))
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_wut(*args, **kwargs):
"""
Returns a string when a user asks 'wut' (This is a joke command)
:return: A string
"""
return Response(command_status=True, message="Whaddya mean, 'wut'? Humans...")
""" Uncomment when Winterbash comes back
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_hats(*args, **kwargs):
wb_start = datetime(2016, 12, 19, 0, 0, 0)
wb_end = datetime(2017, 1, 9, 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 "diff_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 Response(command_status=True, message=return_string)
"""
# --- Block application from posting functions --- #
# noinspection PyIncorrectDocstring,PyUnusedLocal
@check_permissions
def command_block(message_parts, ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Blocks posts from application for a period of time
:param ev_room:
:param wrap2:
:param ev_user_id:
:param message_parts:
:param kwargs: No additional arguments expected
:return: A string
"""
room_id = message_parts[2] if len(message_parts) > 2 else "all"
time_to_block = message_parts[1] if len(message_parts) > 1 else "0"
if not time_to_block.isdigit():
return Response(command_status=False, message="Invalid duration.")
time_to_block = int(time_to_block)
time_to_block = time_to_block if 0 < time_to_block < 14400 else 900
GlobalVars.blockedTime[room_id] = time.time() + time_to_block
which_room = "globally" if room_id == "all" else "in room " + room_id
report = "Reports blocked for {} seconds {}.".format(time_to_block, which_room)
if room_id != GlobalVars.charcoal_room_id:
GlobalVars.charcoal_hq.send_message(report)
return Response(command_status=True, message=report)
# noinspection PyIncorrectDocstring,PyUnusedLocal
@check_permissions
def command_unblock(message_parts, ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Unblocks posting to a room
:param ev_room:
:param wrap2:
:param ev_user_id:
:param message_parts:
:param kwargs: No additional arguments expected
:return: A string
"""
room_id = message_parts[2] if len(message_parts) > 2 else "all"
GlobalVars.blockedTime[room_id] = time.time()
which_room = "globally" if room_id == "all" else "in room " + room_id
report = "Reports unblocked {}.".format(GlobalVars.blockedTime - time.time(), which_room)
if room_id != GlobalVars.charcoal_room_id:
GlobalVars.charcoal_hq.send_message(report)
return Response(command_status=True, message=report)
# --- Administration Commands --- #
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_alive(ev_room, *args, **kwargs):
"""
Returns a string indicating the process is still active
:param ev_room:
:param kwargs: No additional arguments expected
:return: A string
"""
return Response(command_status=True,
message=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,PyUnusedLocal
@check_permissions
def command_allspam(message_parts, ev_room, ev_user_id, wrap2, ev_user_name, ev_room_name, *args, **kwargs):
"""
Reports all of a user's posts as spam
:param ev_room_name:
:param ev_user_name:
:param wrap2:
:param ev_user_id:
:param ev_room:
:param message_parts:
:param kwargs: No additional arguments expected
:return:
"""
if len(message_parts) != 2:
return Response(command_status=False, message="1 argument expected")
url = message_parts[1]
user = get_user_from_url(url)
if user is None:
return Response(command_status=True, message="That doesn't look like a valid user URL.")
why = u"User manually reported by *{}* in room *{}*.\n".format(ev_user_name, ev_room_name.decode('utf-8'))
handle_user_with_all_spam(user, why)
return Response(command_status=True, message=None)
# noinspection PyIncorrectDocstring,PyUnusedLocal
@check_permissions
def command_errorlogs(ev_room, ev_user_id, wrap2, message_parts, *args, **kwargs):
"""
Shows the most recent lines in the error logs
:param message_parts:
:param wrap2:
:param ev_user_id:
:param ev_room:
:param kwargs: No additional arguments expected
:return:
"""
count = -1
if len(message_parts) > 2:
return Response(command_status=False, message="The !!/errorlogs command requires either 0 or 1 arguments.")
try:
count = int(message_parts[1])
except (ValueError, IndexError):
count = 50
logs_part = fetch_lines_from_error_log(count)
post_message_in_room(room_id_str=ev_room, msg=logs_part, length_check=False)
return Response(command_status=True, message=None)
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_help(*args, **kwargs):
"""
Returns the help text
:param kwargs: No additional arguments expected
:return: A string
"""
return Response(command_status=True, message="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,PyUnusedLocal
def command_location(*args, **kwargs):
"""
Returns the current location the application is running from
:return: A string with current location
"""
return Response(command_status=True, message=GlobalVars.location)
# noinspection PyIncorrectDocstring,PyUnusedLocal,PyProtectedMember
@check_permissions
def command_master(ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Forces a system exit with exit code = 8
:param wrap2:
:param ev_user_id:
:param ev_room:
:param kwargs: No additional arguments expected
:return: None
"""
os._exit(8)
# noinspection PyIncorrectDocstring,PyUnusedLocal,PyProtectedMember
@check_permissions
def command_pull(ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Pull an update from GitHub
:param wrap2:
:param ev_user_id:
:param ev_room:
:param kwargs: No additional arguments expected
:return: String on failure, None on success
"""
if only_blacklists_changed(GitManager.get_remote_diff()):
GitManager.pull_remote()
load_blacklists()
return Response(command_status=True, message="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 status in request.json():
state = status["state"]
states.append(state)
if "success" in states:
os._exit(3)
elif "error" in states or "failure" in states:
return Response(command_status=True, message="CI build failed! :( Please check your commit.")
elif "pending" in states or not states:
return Response(command_status=True,
message="CI build is still pending, wait until the build has finished and then pull again.")
# noinspection PyIncorrectDocstring,PyUnusedLocal,PyProtectedMember
@check_permissions
def command_reboot(ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Forces a system exit with exit code = 5
:param wrap2:
:param ev_user_id:
:param ev_room:
:param kwargs: No additional arguments expected
:return: None
"""
post_message_in_room(room_id_str=ev_room, msg="Goodbye, cruel world")
os._exit(5)
# noinspection PyIncorrectDocstring,PyUnusedLocal,PyMissingTypeHints
def command_privileged(ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Tells user whether or not they have privileges
:param wrap2:
:param ev_user_id:
:param ev_room:
:param kwargs: No additional arguments expected
:return: A string
"""
if is_privileged(ev_room, ev_user_id, wrap2):
return Response(command_status=True, message=u"\u2713 You are a privileged user.")
return Response(command_status=True,
message=u"\u2573 " + GlobalVars.not_privileged_warning)
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_code_privileged(ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Tells user whether or not they have code privileges
:param wrap2:
:param ev_user_id:
:param ev_room:
:param kwargs: No additional arguments expected
:return: A string
"""
if is_code_privileged(ev_room, ev_user_id, wrap2):
return Response(command_status=True, message="Yes, you have code privileges.")
return Response(command_status=True,
message="No, you are not a code-privileged user.")
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_quota(*args, **kwargs):
"""
Report how many API hits remain for the day
:return: A string
"""
return Response(command_status=True, message="The current API quota remaining is {}.".format(GlobalVars.apiquota))
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_queuestatus(*args, **kwargs):
"""
Report current API queue
:return: A string
"""
return Response(command_status=True, message=GlobalVars.bodyfetcher.print_queue())
# noinspection PyIncorrectDocstring,PyUnusedLocal,PyProtectedMember
@check_permissions
def command_stappit(message_parts, ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Forces a system exit with exit code = 6
:param message_parts:
:param wrap2:
:param ev_user_id:
:param ev_room:
:param kwargs: No additional arguments expected
:return: None
"""
if len(message_parts) == 1 or " ".join(message_parts[1:]).lower() in GlobalVars.location.lower():
post_message_in_room(room_id_str=ev_room, msg="Goodbye, cruel world")
os._exit(6)
return Response(command_status=True, message=None)
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,PyUnusedLocal
def command_status(*args, **kwargs):
"""
Returns the amount of time the application has been running
:return: A string
"""
now = datetime.utcnow()
diff = now - UtcDate.startup_utc_date
return Response(command_status=True,
message='Running since {time} UTC ({relative})'.format(
time=GlobalVars.startup_utc,
relative=td_format(diff)))
# noinspection PyIncorrectDocstring,PyUnusedLocal
@check_permissions
def command_stop_flagging(*args, **kwargs):
t_metasmoke = Thread(name="stop_autoflagging", target=Metasmoke.stop_autoflagging,
args=())
t_metasmoke.start()
return Response(command_status=True, message="Request sent...")
# noinspection PyIncorrectDocstring,PyUnusedLocal,PyProtectedMember
@check_permissions
def command_standby(message_parts, ev_room, ev_user_id, wrap2, *args, **kwargs):
"""
Forces a system exit with exit code = 7
:param message_parts:
:param wrap2:
:param ev_user_id:
:param ev_room:
:param kwargs: No additional arguments expected
:return: None
"""
if " ".join(message_parts[1:]).lower() in GlobalVars.location.lower():
m = "{location} is switching to standby".format(location=GlobalVars.location)
post_message_in_room(room_id_str=ev_room, msg=m)
os._exit(7)
return Response(command_status=True, message=None)
# noinspection PyIncorrectDocstring,PyUnusedLocal,PyMissingTypeHints
def command_test(content, content_lower, *args, **kwargs):
"""
Test a post to determine if it'd be automatically reported
:param content_lower:
:param content:
:param kwargs: No additional arguments expected
:return: A string
"""
string_to_test = content[8:]
test_as_answer = False
if len(string_to_test) == 0:
return Response(command_status=True, message="Nothing to test")
result = "> "
fakepost = Post(api_response={'title': string_to_test, 'body': string_to_test,
'owner': {'display_name': string_to_test, 'reputation': 1, 'link': ''},
'site': "", 'IsAnswer': test_as_answer, 'score': 0})
reasons, why = FindSpam.test_post(fakepost)
if len(reasons) == 0:
result += "Would not be caught for title, body, and username."
return Response(command_status=True, message=result)
result += ", ".join(reasons).capitalize()
if why is not None and len(why) > 0:
result += "\n----------\n"
result += why
return Response(command_status=True, message=result)
# noinspection PyIncorrectDocstring,PyUnusedLocal
def command_test_answer(content, content_lower, *args, **kwargs):
"""
Test an answer to determine if it'd be automatically reported
:param content_lower:
:param content:
:param kwargs: No additional arguments expected
:return: A string
"""
string_to_test = content[10:]
test_as_answer = True
if len(string_to_test) == 0:
return Response(command_status=True, message="Nothing to test")
result = "> "
fakepost = Post(api_response={'title': 'Valid title', 'body': string_to_test,
'owner': {'display_name': "Valid username", 'reputation': 1, 'link': ''},
'site': "", 'IsAnswer': test_as_answer, 'score': 0})
reasons, why = FindSpam.test_post(fakepost)
if len(reasons) == 0:
result += "Would not be caught as an answer."
return Response(command_status=True, message=result)
result += ", ".join(reasons).capitalize()
if why is not None and len(why) > 0:
result += "\n----------\n"
result += why
return Response(command_status=True, message=result)