-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathafkbot.py
More file actions
executable file
·1525 lines (1423 loc) · 64.4 KB
/
Copy pathafkbot.py
File metadata and controls
executable file
·1525 lines (1423 loc) · 64.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# Copyright (c) 2013-2024 Chuck-R <github@chuck.cloud>
#
# Copyright (c) 2013-2024, Chuck-R <github@chuck.cloud>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of AFKBot nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AFKBOT'S CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
# Contains code from mumblebee
# Copyright (c) 2013, Toshiaki Hatano <haeena@haeena.net>
#
# Contains code from the eve-bot
# Copyright (c) 2009, Philip Cass <frymaster@127001.org>
# Copyright (c) 2009, Alan Ainsworth <fruitbat@127001.org>
#
# Contains code from the Mumble Project:
# Copyright (C) 2005-2009, Thorvald Natvig <thorvald@natvig.com>
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# - Neither the name of localhost, 127001.org, eve-bot nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import datetime
import importlib.util
import optparse
import os
import platform
import random
import select
import signal
import socket
import stat
import struct
import sys
import tempfile
import _thread
import threading
import time
import yaml
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
# The next 2 imports may not succeed
warning = ""
try:
import ssl
except Exception:
print("ERROR: This python program requires the python ssl module "
"(available in python 2.6+; standalone version may be found at"
"http://pypi.python.org/pypi/ssl/)\n")
print(warning)
sys.exit(1)
if importlib.util.find_spec('google') is None \
or importlib.util.find_spec("google.protobuf") is None:
print("ERROR: Google protobuf library not found. This can be installed "
"via 'pip install protobuf'")
sys.exit(1)
try:
import Mumble_pb2
except Exception:
print("Error: Module Mumble_pb2 not found\nIf the file 'Mumble_pb2.py' "
"does not exist, then you must compile it with "
"'protoc --python_out=. Mumble.proto' from the script directory.")
sys.exit(1)
afkbot_version = "0.8.3"
headerFormat = ">HI"
eavesdropper = None
controlBreak = False
logTimeFormat = "%a, %d %b %Y %H:%M:%S +0000"
messageIDByMessageType = {
Mumble_pb2.Version: 0,
Mumble_pb2.UDPTunnel: 1,
Mumble_pb2.Authenticate: 2,
Mumble_pb2.Ping: 3,
Mumble_pb2.Reject: 4,
Mumble_pb2.ServerSync: 5,
Mumble_pb2.ChannelRemove: 6,
Mumble_pb2.ChannelState: 7,
Mumble_pb2.UserRemove: 8,
Mumble_pb2.UserState: 9,
Mumble_pb2.BanList: 10,
Mumble_pb2.TextMessage: 11,
Mumble_pb2.PermissionDenied: 12,
Mumble_pb2.ACL: 13,
Mumble_pb2.QueryUsers: 14,
Mumble_pb2.CryptSetup: 15,
Mumble_pb2.ContextActionModify: 16,
Mumble_pb2.ContextAction: 17,
Mumble_pb2.UserList: 18,
Mumble_pb2.VoiceTarget: 19,
Mumble_pb2.PermissionQuery: 20,
Mumble_pb2.CodecVersion: 21,
Mumble_pb2.UserStats: 22,
Mumble_pb2.RequestBlob: 23,
Mumble_pb2.ServerConfig: 24,
Mumble_pb2.SuggestConfig: 25,
Mumble_pb2.PluginDataTransmission: 26
}
messageTypeNameById = {
0: "Version",
1: "UDPTunnel",
2: "Authenticate",
3: "Ping",
4: "Reject",
5: "ServerSync",
6: "ChannelRemove",
7: "ChannelState",
8: "UserRemove",
9: "UserState",
10: "BanList",
11: "TextMessage",
12: "PermissionDenied",
13: "ACL",
14: "QueryUsers",
15: "CryptSetup",
16: "ContextActionModify",
17: "ContextAction",
18: "UserList",
19: "VoiceTarget",
20: "PermissionQuery",
21: "CodecVersion",
22: "UserStats",
23: "RequestBlob",
24: "ServerConfig",
25: "SuggestConfig",
26: "PluginDataTransmission"
}
# Inversion of above
messageTypeByID = {}
for i in messageIDByMessageType.keys():
messageTypeByID[messageIDByMessageType[i]] = i
threadNumber = 0
def discontinue_processing(signl, frme):
global eavesdropper
print(f"{time.strftime(logTimeFormat)}: Received shutdown notice.")
if signl == signal.SIGUSR1:
pb_message = Mumble_pb2.TextMessage()
pb_message.actor = eavesdropper.session
for channel_id in eavesdropper.channelList:
pb_message.channel_id.append(channel_id)
pb_message.message = "Server rebooting!"
pb_message_id = messageIDByMessageType[type(pb_message)]
pb_message_string = pb_message.SerializeToString()
tosend = eavesdropper.packageMessage(pb_message_id, pb_message_string)
eavesdropper.sendTotally(tosend)
if eavesdropper:
eavesdropper.wrapUpThread()
else:
sys.exit(0)
global controlBreak
controlBreak = True
def GenerateCertificate(filename):
print(f"Generating Certificate at {filename}...", end="")
private_key = rsa.generate_private_key(public_exponent=65537,
key_size=2048)
public_key = private_key.public_key()
# No need to create p12 file, PEM is sufficient for ssl
subject = issuer = x509.Name([
x509.NameAttribute(x509.NameOID.COMMON_NAME, "AFKBot")
])
now = datetime.datetime.now()
cert = x509.CertificateBuilder().subject_name(subject)\
.issuer_name(issuer)\
.public_key(public_key)\
.serial_number(x509.random_serial_number())\
.not_valid_before(now)\
.not_valid_after(now+datetime.timedelta(weeks=52*20))\
.sign(private_key, hashes.SHA256())
pem = cert.public_bytes(serialization.Encoding.PEM)
key_contents = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
key_contents += pem
# Certificate for AFKBot
with open(filename, "wb") as file:
try:
file.write(key_contents)
except Exception:
raise ValueError("Could not write PEM certificate file")
os.chmod(filename, stat.S_IREAD | stat.S_IWRITE)
print("Done!")
# Dictionary copy, but don't override any values already set
def CopyConfig(src, dest):
for key in src:
if type(src[key]) is dict:
if key not in dest:
dest[key] = {}
CopyConfig(src[key], dest[key])
if key not in dest:
dest[key] = src[key]
class Logger(object):
def __init__(self, filename=None, copyfrom=None, config=None):
self.originalStdout = sys.stdout
self.terminal = sys.stdout
self.config = config
self.lastPrintWasVerbose = False
if filename is None:
self.internal_log = True
self.log_buffer = ""
self.log = None
else:
self.internal_log = False
try:
self.log = open(filename, "a")
except OSError as e:
self.terminal.write("WARN: Could not open log file "
f"'{filename}': {e}\n")
self.log = None
if copyfrom is not None:
try:
if self.log is not None:
self.log.write(copyfrom.log_buffer)
except Exception as e:
self.terminal.write("ERROR: Could not write to log file: "
f"{e}\n")
self.originalStdout = copyfrom.originalStdout
def write(self, message):
if message == os.linesep and self.lastPrintWasVerbose:
self.lastPrintWasVerbose = False
return
if message.startswith("VERBOSE: "):
# print() makes a separate call to write() for the line separator,
# apparently. So, even if the verbose message is filtered out, a
# blank line is still output via print(). So, we have to track if
# we are currently printing a verbose log line. If so, we have to
# filter out the newline. This means that for each verbose log
# message, we also have to append a new line to the string. I'm
# positive there is a bettery way to do this, but it works.
self.lastPrintWasVerbose = True
if self.config is None:
return
if self.config is not None \
and self.config["AFKBot"]["Verbose"] is False:
return
else:
message = message[len("VERBOSE: "):] + os.linesep
if message.startswith("ERROR: "):
self.terminal.write(f"\x1B[91m{message}\x1B[0m")
elif message.startswith("WARN"):
self.terminal.write(f"\x1B[93m{message}\x1B[0m")
else:
self.terminal.write(message)
if self.internal_log:
self.log_buffer += message
else:
if self.log is not None:
try:
self.log.write(message)
except Exception as e:
self.terminal.write("ERROR: Could not write to log file: "
f"{e}\n")
def flush(self):
self.terminal.flush()
if self.log is not None:
self.log.flush()
class timedWatcher(threading.Thread):
def __init__(self, socketLock, socket):
global threadNumber
threading.Thread.__init__(self)
self.pingTotal = 1
self.isRunning = True
self.socketLock = socketLock
self.socket = socket
i = threadNumber
threadNumber += 1
self.threadName = "Thread " + str(i)
def stopRunning(self):
self.isRunning = False
def run(self):
self.nextPing = time.time()-1
while self.isRunning:
t = time.time()
if t > self.nextPing:
pb_message = Mumble_pb2.Ping()
pb_message.timestamp = (self.pingTotal*5000000)
pb_message.good = 0
pb_message.late = 0
pb_message.lost = 0
pb_message.resync = 0
pb_message.udp_packets = 0
pb_message.tcp_packets = self.pingTotal
pb_message.udp_ping_avg = 0
pb_message.udp_ping_var = 0.0
pb_message.tcp_ping_avg = 50
pb_message.tcp_ping_var = 50
self.pingTotal += 1
packet = struct.pack(headerFormat, 3, pb_message.ByteSize()) \
+ pb_message.SerializeToString()
self.socketLock.acquire()
while len(packet) > 0:
try:
sent = self.socket.send(packet)
except Exception:
sent = 0
packet = packet[sent:]
self.socketLock.release()
self.nextPing = t+10
# sleeptime=self.nextPing-t
# if sleeptime > 0:
time.sleep(1)
print(f"{time.strftime(logTimeFormat)}: timed thread going away")
class mumbleConnection(threading.Thread):
def __init__(self, config, delay=None, limit=None):
global threadNumber
i = threadNumber
threadNumber += 1
self.threadName = "Thread " + str(i)
threading.Thread.__init__(self)
tcpSock = socket.socket(type=socket.SOCK_STREAM)
self.socketLock = _thread.allocate_lock()
self.socket = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
self.socket.load_default_certs(purpose=ssl.Purpose.SERVER_AUTH)
# load_cert_chain *has* to be a PEM file
self.socket.load_cert_chain(certfile=config["AFKBot"]["Certificate"])
if config["Server"]["AcceptSelfSignedCertificate"] is True:
# Retrieve server cert to add to CA's
server_cert = tempfile.NamedTemporaryFile(delete=False,
delete_on_close=False)
try:
server_cert.write(
ssl.get_server_certificate(
(config["Server"]["Host"]["Address"],
config["Server"]["Host"]["Port"]),
ssl.PROTOCOL_TLS_CLIENT
).encode()
)
server_cert.close()
self.socket.load_verify_locations(cafile=server_cert.name)
os.unlink(server_cert.name)
except Exception as e:
print(f"[self.threadName]: {time.strftime(logTimeFormat)} "
"Error writing SSL certificate to temporary file. "
"Will not be able to accept self-signed certifiate.")
print(f"[self.threadName]: {time.strftime(logTimeFormat)} {e}")
self.socket.check_hostname = False
self.socket = self.socket.wrap_socket(
tcpSock, server_hostname=config["Server"]["Host"]["Address"])
self.socket.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
self.host = (config["Server"]["Host"]["Address"],
config["Server"]["Host"]["Port"])
self.nickname = config["AFKBot"]["Nickname"]
self.inChannel = False
self.session = None
self.channelId = None
self.userList = {}
self.userListByName = {}
self.channelList = {}
self.channelListByName = {}
self.readyToClose = False
self.timedWatcher = None
self.serverSync = False
# TODO: Implement delay and rate limit
# self.delay=delay
# self.limit=limit
self.password = None
self.verbose = config["AFKBot"]["Verbose"]
#######################################
# AFKBot-specific config
#######################################
self.idleLimit = config["AFKBot"]["IdleTimeout"]
exception = ValueError("config['AFKBot']['IdleTimeout'] or command "
"line argument --idle-time is invalid. Valid "
"values are a number, a string convertible to "
"a number, or an string convertible to a "
"number suffixed with 's' for seconds.\n\n"
"Examples: 30, \"30\", or \"30s\"")
if type(self.idleLimit) is str:
if len(self.idleLimit) >= 2:
if self.idleLimit[-1:] == "s":
self.idleLimit = self.idleLimit[:-1]
try:
self.idleLimit = int(self.idleLimit)
except Exception:
raise exception
else:
self.idleLimit = int(self.idleLimit) * 60
else:
try:
self.idleLimit = int(self.idleLimit) * 60
except Exception:
raise exception
else:
try:
self.idleLimit = int(self.idleLimit) * 60
except Exception:
raise exception
self.channel = config["AFKBot"]["Channel"] # AFK channel to listen in
self.accessTokens = []
if "AccessTokens" in config["Server"]:
for item in config["Server"]["AccessTokens"]:
self.accessTokens.append(item)
if "Password" in config["Server"]:
self.password = config["Server"]["Password"]
def decodePDSInt(self, m, si=0):
v = m[si]
if ((v & 0x80) == 0x00):
return ((v & 0x7F), 1)
elif ((v & 0xC0) == 0x80):
return ((v & 0x4F) << 8 | m[si+1], 2)
elif ((v & 0xF0) == 0xF0):
if ((v & 0xFC) == 0xF0):
return (m[si+1] << 24 | m[si+2] << 16
| m[si+3] << 8 | m[si+4], 5)
elif ((v & 0xFC) == 0xF4):
return (m[si+1] << 56 | m[si+2] << 48
| m[si+3] << 40 | m[si+4] << 32
| m[si+5] << 24 | m[si+6] << 16
| m[si+7] << 8 | m[si+8], 9)
elif ((v & 0xFC) == 0xF8):
result, length = self.decodePDSInt(m, si+1)
return (-result, length+1)
elif ((v & 0xFC) == 0xFC):
return (-(v & 0x03), 1)
else:
print(f"[{self.threadName}] {time.strftime(logTimeFormat)}: "
"Help help, out of cheese :(")
sys.exit(1)
elif ((v & 0xF0) == 0xE0):
return ((v & 0x0F) << 24 | m[si+1] << 16
| m[si+2] << 8 | m[si+3], 4)
elif ((v & 0xE0) == 0xC0):
return ((v & 0x1F) << 16 | m[si+1] << 8 | m[si+2], 3)
else:
print(f"[{self.threadName}] {time.strftime(logTimeFormat)}: "
"out of cheese?")
sys.exit(1)
def packageMessage(self, message_type, message):
length = len(message)
return struct.pack(headerFormat, message_type, length)+message
def sendTotally(self, message):
self.socketLock.acquire()
while len(message) > 0:
sent = self.socket.send(message)
if sent < 0:
print(f"[{self.threadName}] {time.strftime(logTimeFormat)}: "
"Server socket error while trying to write, immediate "
"abort")
self.socketLock.release()
return False
message = message[sent:]
self.socketLock.release()
return True
def readTotally(self, size):
message = bytes()
while len(message) < size:
received = self.socket.recv(size-len(message))
message += received
if len(received) == 0:
print(f"[{self.threadName}] {time.strftime(logTimeFormat)}: "
"Server socket died while trying to read, immediate "
"abort")
return None
return message
def parseMessage(self, message_type, message):
message_class = messageTypeByID[message_type]
temp_message = message_class()
temp_message.ParseFromString(message)
return temp_message
def joinChannel(self):
if self.channelId is None:
print(f"Could not find channel {self.channel}")
return
if not self.inChannel:
pb_message = Mumble_pb2.UserState()
pb_message.channel_id = self.channelId
pb_message_id = messageIDByMessageType[type(pb_message)]
pb_message_string = pb_message.SerializeToString()
pb_message = self.packageMessage(pb_message_id, pb_message_string)
if not self.sendTotally(pb_message):
self.wrapUpThread()
return
else:
print("VERBOSE: joinChannel(): Already in a channel!")
def wrapUpThread(self):
# called after thread is confirmed to be needing to die because of
# kick / socket close
self.readyToClose = True
def readPacket(self):
# pdb.set_trace()
meta = self.readTotally(6)
if not meta:
self.wrapUpThread()
return
message_type, length = struct.unpack(headerFormat, meta)
stringMessage = self.readTotally(length)
if not stringMessage:
# An empty payload isn't necessarily a panic condition. I've
# seen packets such as CryptSetup with no payload
return
# Type 1 = UDP Tunnel, voice data or UDP ping
if message_type == 1:
# I'm not sure why the third byte is session ID, but it is.
session, sessLen = self.decodePDSInt(stringMessage, 2)
if session in self.userList and self.userList[session]["channel"] \
== self.channelListByName[self.channel]:
if "idleinfo" in self.userList[session] \
and "oldchannel" in self.userList[session]["idleinfo"]:
pb_message = Mumble_pb2.UserState()
pb_message.session = session
pb_message.actor = self.session
pb_message.channel_id = \
self.userList[session]["idleinfo"]["oldchannel"]
pb_message_id = messageIDByMessageType[type(pb_message)]
pb_message_string = pb_message.SerializeToString()
pb_message = self.packageMessage(pb_message_id,
pb_message_string)
if not self.sendTotally(pb_message):
self.wrapUpThread()
oldchan = self.userList[session]["idleinfo"]["oldchannel"]
print(f"VERBOSE: Moving {self.userList[session]['name']} "
"back to "
f"{self.channelList[oldchan]}")
# Type 5 = ServerSync
if message_type == 5 and not self.inChannel:
message = self.parseMessage(message_type, stringMessage)
self.serverSync = True
self.session = message.session
# Send channel join message
self.joinChannel()
# Query collected user stats
for item in self.userListByName:
pb_message = Mumble_pb2.UserStats()
pb_message.session = self.session
pb_message_id = messageIDByMessageType[type(pb_message)]
pb_message_string = pb_message.SerializeToString()
pb_message = self.packageMessage(pb_message_id,
pb_message_string)
if not self.sendTotally(pb_message):
self.wrapUpThread()
# Type 6 = ChannelRemove
if message_type == 6:
message = self.parseMessage(message_type, stringMessage)
channelid = message.channel_id
for item in self.channelListByName:
if self.channelListByName[item] == message.channel_id:
del self.channelListByName[item]
del self.channeList[message.channel_id]
break
for item in self.userList:
if "idleinfo" in self.userList[item] \
and "oldchannel" in self.userList[item]["idleinfo"]:
if self.userList[item]["idleinfo"]["oldchannel"] \
== channelid:
self.userList[item]["idleinfo"]["oldchannel"] = 0
# Type 7 = ChannelState
if message_type == 7:
message = self.parseMessage(message_type, stringMessage)
if message.channel_id not in self.channelList \
or self.channelList[message.channel_id] != message.name:
if not len(message.name):
return
self.channelList[message.channel_id] = message.name
self.channelListByName[message.name] = message.channel_id
if not self.inChannel and self.channelId is None:
if message.name == self.channel:
self.channelId = message.channel_id
if self.serverSync is True:
self.joinChannel()
# Type 8 = UserRemove (kick/leave)
if message_type == 8:
message = self.parseMessage(message_type, stringMessage)
if self.session is not None:
if message.session == self.session:
print(f"[{self.threadName}] {time.strftime(logTimeFormat)}"
": ********** KICKED **********")
self.wrapUpThread()
return
session = message.session
if session in self.userList:
del self.userListByName[self.userList[session]["name"]]
del self.userList[session]
# Type 9 = UserState
if message_type == 9:
message = self.parseMessage(message_type, stringMessage)
session = message.session
record = None
name = None
channel = None
channel_name = None
actor = None
if "session" in self.userList:
record = self.userList[session]
else:
record = {}
if "name" in message:
record["name"] = message.name
name = message.name
if "user_id" in message:
record["user_id"] = message.user_id
if "channel_id" in message:
record["channel"] = message.channel_id
channel = message.channel_id
if "actor" in message:
actor = message.actor
if channel is None and session in self.userList \
and "channel" in self.userList[session]:
channel = self.userList[session]["channel"]
# If channel is still None, Root is assumed. When the server first
# sends UserState messages, if the user is in the root channel when
# the bot enters the root channel initially, the server will not
# include the channel_id field for some reason.
if channel is None:
channel = 0
if not self.session and name == self.nickname:
print(f"VERBOSE: Bot session: {session}")
self.session = session
# Got a message back stating that we moved ourselves, we are
# now in the channel
if not self.inChannel and channel in self.channelList \
and actor == self.session and session == self.session:
print("VERBOSE: Moved ourselves to "
f"'{self.channelList[channel]}'")
self.inChannel = True
# Keep any data in userList that wasn't from this packet
if session in self.userList:
for item in self.userList[session]:
record[item] = self.userList[session][item]
if "channel" in self.userList[session] \
and self.userList[session]["channel"] in self.channelList:
channel_name = \
self.channelList[self.userList[session]["channel"]]
# No info on user, send a UserStats to fill in idle info
else:
# Only if ServerSync message received
if self.serverSync:
pb_message = Mumble_pb2.UserStats()
pb_message.session = session
pb_message_id = messageIDByMessageType[type(pb_message)]
pb_message_string = pb_message.SerializeToString()
pb_message = self.packageMessage(pb_message_id,
pb_message_string)
if not self.sendTotally(pb_message):
self.wrapUpThread()
self.userList[session] = record
if name:
self.userListByName[name] = session
# Set idle information on actor
if actor and actor != self.session:
if actor in self.userList:
record = self.userList[actor]
# If AFK channel is known
if self.channel in self.channelListByName:
# User is not in AFK channel
if channel != self.channelId:
if "idleinfo" not in record:
record["idleinfo"] = {}
record["idleinfo"]["checkon"] = time.time()+self.idleLimit
record["idleinfo"]["oldchannel"] = channel
record["idleinfo"]["moving"] = False
# User is in AFK channel
else:
if "idleinfo" in record:
record["idleinfo"]["checkon"] = -1
else:
record["idleinfo"] = {"checkon": -1, "oldchannel": 0}
if actor and actor == self.session and \
session != self.session and \
record["idleinfo"]["moving"] is True:
record["idleinfo"]["moving"] = False
else:
print("VERBOSE: No channel info yet for AFK channel")
# Update idleinfo for user sending message
update_user = session
to_update = self.userList[session]
if actor and actor != self.session:
update_user = actor
to_update = self.userList[actor]
temp_idleinfo = record["idleinfo"]
for item in to_update:
record[item] = to_update[item]
record["idleinfo"] = temp_idleinfo
self.userList[update_user] = record
if channel_name:
if self.inChannel and channel_name == "Private Chats":
pb_message = Mumble_pb2.TextMessage()
pb_message.actor = self.session
pb_message.session.append(message.session)
pb_message.message = \
("This is the Private Chats channel. To create a "
"sub-channel, right click Private Chats and select "
"'Add'. Name your channel and check the 'Temporary' "
"checkbox.")
pb_message_id = messageIDByMessageType[type(pb_message)]
pb_message_string = pb_message.SerializeToString()
pb_message = self.packageMessage(pb_message_id,
pb_message_string)
if not self.sendTotally(pb_message):
self.wrapUpThread()
if self.inChannel and channel_name in \
("Castle Wars", "Zamorak", "Saradomin"):
# Package a message to the user
pb_message = Mumble_pb2.TextMessage()
pb_message.actor = self.session
pb_message.session.append(message.session)
pb_message.message = (
"Welcome to the Castle Wars channels! In this channel "
"setup, you can set up a hotkey for Shout with a "
"target of the parent channel to send messages to "
"the opposing team.")
pb_message_id = messageIDByMessageType[type(pb_message)]
pb_message_string = pb_message.SerializeToString()
pb_message = self.packageMessage(pb_message_id,
pb_message_string)
if not self.sendTotally(pb_message):
self.wrapUpThread()
return
# Type 11 = TextMessage
if message_type == 11:
message = self.parseMessage(message_type, stringMessage)
if message.actor != self.session:
if message.message.lower().startswith("/roll"):
pb_message = Mumble_pb2.TextMessage()
pb_message.actor = self.session
pb_message.channel_id.append(self.channelId)
pb_message.channel_id.append(
self.userList[message.actor]["channel"])
pb_message.message = self.userList[message.actor]["name"] \
+ " rolled " + str(random.randint(0, 100))
pb_message.session.append(message.actor)
pb_message_id = messageIDByMessageType[type(pb_message)]
pb_message_string = pb_message.SerializeToString()
pb_message = self.packageMessage(pb_message_id,
pb_message_string)
if not self.sendTotally(pb_message):
self.wrapUpThread()
return
if message.message.lower().startswith("/afkme"):
pb_message = Mumble_pb2.UserState()
pb_message.session = message.actor
pb_message.actor = self.session
pb_message.channel_id = \
self.channelListByName[self.channel]
pb_message_id = messageIDByMessageType[type(pb_message)]
pb_message_string = pb_message.SerializeToString()
pb_message = self.packageMessage(pb_message_id,
pb_message_string)
if not self.sendTotally(pb_message):
self.wrapUpThread()
self.userList[message.actor]["idleinfo"]["checkon"] = -1
return
if message.message.lower().startswith("/afk"):
args = message.message.split(" ", 1)
if len(args) == 1:
return
pb_message = Mumble_pb2.UserState()
for key in self.userListByName:
if key.lower() == args[1].lower():
pb_message.session = self.userListByName[key]
if pb_message.session == 0:
pb_message = Mumble_pb2.TextMessage()
pb_message.actor = self.session
pb_message.session.append(message.actor)
pb_message.message = "No such user to AFK"
pb_message_id = \
messageIDByMessageType[type(pb_message)]
pb_message_string = pb_message.SerializeToString()
pb_message = self.packageMessage(pb_message_id,
pb_message_string)
if not self.sendTotally(pb_message):
self.wrapUpThread()
return
self.userList[pb_message.session]["idleinfo"]["checkon"] \
= -1
pb_message.actor = self.session
pb_message.channel_id = \
self.channelListByName[self.channel]
pb_message_id = messageIDByMessageType(type(pb_message))
pb_message_string = pb_message.SerializeToString()
pb_message = self.packageMessage(pb_message_id,
pb_message_string)
if not self.sendTotally(pb_message):
self.wrapUpThread()
return
if message.message.lower().startswith("/unafk"):
args = message.message.split(" ", 1)
if len(args) == 1:
return
pb_message = Mumble_pb2.UserState()
for key in self.userListByName:
if key.lower() == args[1].lower():
sess = self.userListByName[key]
pb_message.session = sess
pb_message.channel_id = \
self.userList[sess]["idleinfo"]["oldchannel"]
if pb_message.session == 0:
pb_message = Mumble_pb2.TextMessage()
pb_message.actor = self.session
pb_message.session.append(message.actor)
pb_message.message = "No such user to UnAFK"
pb_message_id = \
messageIDByMessageType[type(pb_message)]
pb_message_string = pb_message.SerializeToString()
pb_message = self.packageMessage(pb_message_id,
pb_message_string)
if not self.sendTotally(pb_message):
self.wrapUpThread()
return
self.userList[pb_message.session]["idleinfo"]["checkon"] \
= -1
pb_message.actor = self.session
pb_message_id = messageIDByMessageType[type(pb_message)]
pb_message_string = pb_message.SerializeToString()
pb_message = self.packageMessage(pb_message_id,
pb_message_string)
if not self.sendTotally(pb_message):
self.wrapUpThread()
if message.message.lower().startswith("/set"):
split = message.message.split()
if split[1].lower() == "afktime":
# Check permissions
pass
if split[1].lower() == "afkchannel":
# Check permissions
pass
# Type 12 = PermissionDenied
if message_type == 12:
print(f"[{self.threadName}] {time.strftime(logTimeFormat)}: "
"Permission Denied.")
return
# Type 22 = UserStats
if message_type == 22:
message = self.parseMessage(message_type, stringMessage)
# Don't act on ourselves
if message.session == self.session:
return
# Timer already expired
if message.idlesecs >= self.idleLimit and self.inChannel:
print("VERBOSE: Sending UserState() to move user "
f"{self.userList[message.session]['name']}")
# Move user to AFK channel
pb_message = Mumble_pb2.UserState()
pb_message.session = message.session
pb_message.actor = self.session
pb_message.channel_id = \
self.channelListByName[self.channel]
pb_message_id = messageIDByMessageType[type(pb_message)]
pb_message_string = pb_message.SerializeToString()
pb_message = self.packageMessage(pb_message_id,
pb_message_string)
if not self.sendTotally(pb_message):
self.wrapUpThread()
self.userList[message.session]["idleinfo"]["checkon"] = -1
else:
print("VERBOSE: Setting new timeout on user "
f"{self.userList[message.session]['name']}")
self.userList[message.session]["idleinfo"]["checkon"] = \
time.time()+(self.idleLimit-message.idlesecs)
return
def run(self):
try:
self.socket.connect(self.host)
except Exception as inst:
print(inst)
print(f"[{self.threadName}] {time.strftime(logTimeFormat)}: "
"Couldn't connect to server")
global controlBreak
controlBreak = True
return
self.socket.setblocking(False)
print(f"[{self.threadName}] {time.strftime(logTimeFormat)}: "
"Connected to server")
pb_message = Mumble_pb2.Version()
pb_message.release = pb_message.os_version = f"AFKBot {afkbot_version}"
version = {
"major": 1,
"minor": 5,
"build": 634
}
pb_message.version_v1 = (version["major"] << 16) +\
(version["minor"] << 8) +\
(version["build"] if version["build"] <= 255 else 255)
pb_message.version_v2 = (version["major"] << 48) +\
(version["minor"] << 32) +\
(version["build"] << 16)
pb_message.os = platform.system()
pb_message_id = messageIDByMessageType[type(pb_message)]
pb_message_string = pb_message.SerializeToString()
pb_message = self.packageMessage(pb_message_id, pb_message_string)
if not self.sendTotally(pb_message):
print("ERROR: Could not send Version packet")
return
pb_message = Mumble_pb2.Authenticate()
pb_message.username = self.nickname
if len(self.accessTokens):
for token in self.accessTokens:
pb_message.tokens.append(token)
if self.password is not None:
pb_message.password = self.password
# celt_version = pb_message.celt_versions.append(-2147483637)
pb_message_id = messageIDByMessageType[type(pb_message)]