forked from zippyy/zncbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot
executable file
·695 lines (601 loc) · 33 KB
/
bot
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
#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
# SuchZNC Bot
# Copyright (C) 2017 Nathaniel Olsen
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import atexit
import json
import logging
import random
import socket
import ssl
import sys
import time
import warnings
import os
import string
import re
from platform import python_version
from shutil import copyfile
from collections import defaultdict
warnings.simplefilter('default')
try:
configarg = sys.argv[1]
except:
print("Error: Please specify your configuration file in the system arguments.")
sys.exit("Example: ./bot config.json")
with open(configarg) as f:
config = json.load(f)
try:
with open("cache.json") as g:
cache = json.load(g)
except FileNotFoundError:
copyfile('examplejsons/cache.json.example', 'cache.json')
with open("cache.json") as g:
cache = json.load(g)
try:
with open("zncusersdb.json") as b:
zncusersdb = json.load(b)
except FileNotFoundError:
copyfile('examplejsons/zncusersdb.json.example', 'zncusersdb.json')
with open("zncusersdb.json") as b:
zncusersdb = json.load(b)
try:
with open("requestthrottle.json") as o:
requestthrottle = json.load(o)
except FileNotFoundError:
copyfile('examplejsons/requestthrottle.json.example', 'requestthrottle.json')
with open("requestthrottle.json") as o:
requestthrottle = json.load(o)
try:
with open("zncuserlist.json") as n:
zncuserlist = json.load(n)
except FileNotFoundError:
copyfile('examplejsons/zncuserlist.json.example', 'zncuserlist.json')
with open("zncuserlist.json") as n:
zncuserlist = json.load(n)
try:
with open("userlang.json") as p:
userlang = json.load(p)
except FileNotFoundError:
copyfile('examplejsons/userlang.json.example', 'userlang.json')
with open("userlang.json") as p:
userlang = json.load(p)
with open("i18n/{}.json".format(config['language'])) as h:
i18n = json.load(h)
logging_level = logging.DEBUG # Sets the logging level (valid options are DEBUG, INFO, WARNING, ERROR and CRITICAL)
logging.basicConfig(level=logging_level)
class TokenBucket(object):
"""An implementation of the token bucket algorithm.
>>> bucket = TokenBucket(80, 0.5)
>>> bucket.consume(1)
"""
def __init__(self, tokens, fill_rate):
"""tokens is the total tokens in the bucket. fill_rate is the
rate in tokens/second that the bucket will be refilled."""
self.capacity = float(tokens)
self._tokens = float(tokens)
self.fill_rate = float(fill_rate)
self.timestamp = time.time()
def consume(self, tokens):
"""Consume tokens from the bucket. Returns True if there were
sufficient tokens otherwise False."""
if tokens <= self.tokens:
self._tokens -= tokens
return True
return False
@property
def tokens(self):
now = time.time()
if self._tokens < self.capacity:
delta = self.fill_rate * (now - self.timestamp)
self._tokens = min(self.capacity, self._tokens + delta)
self.timestamp = now
return self._tokens
tokenbucket = TokenBucket(4, 0.5)
def irc_command(command, *args):
last_arg = args[-1]
other_args = args[:-1]
return "{} {} :{}\r\n".format(command, " ".join(other_args), last_arg)
def sendraw(msg):
while not tokenbucket.consume(1):
time.sleep(0.1)
ircsock.sendall(bytes(msg, "utf-8"))
def ping(arg):
sendraw(irc_command("PONG", arg))
def acs_normal(message):
return True
def wildcards_to_regex(s):
return re.sub(r'\\\*', '.*', re.sub(r'\\\?', '.', re.escape(s)))
def wildcard_match(pattern, s):
return bool(re.fullmatch(wildcards_to_regex(pattern), s))
def acs_admin(message):
return any(wildcard_match(admin, message['userhost']) for admin in config['admins'])
def cmd_restart(message, _):
sendmsg(message['replyto'], "Restarting...")
cache["channel"] = str(message['replyto'])
with open('cache.json', 'w') as g:
json.dump(cache, g, indent=2)
logging.info("{0} has issued a restart".format(message['nick']))
os.execl(sys.executable, sys.executable, * sys.argv)
def sendmsg(chan, msg):
global lastchan
lastchan = chan
logging.debug("sendmsg to {0} (' {1} ')".format(chan, msg))
sendraw(irc_command("PRIVMSG", chan, msg))
def cmd_timereset(message, znc_username):
znc_username_string = ''.join(znc_username)
try:
znc_username_real = zncusersdb["users"][znc_username_string.lower()]["real_username"]
if_user_match = znc_username_string.lower() == znc_username_real.lower()
znc_user_host = zncusersdb["users"][znc_username_string.lower()]["host_registered_as"]
if if_user_match:
requestthrottle[znc_user_host] = 0
sendmsg(message['replyto'], message['nick'] +": {0} {1} {2}".format(i18n['user'], str(znc_username_string), i18n['request_timer_reset']))
with open('requestthrottle.json', 'w') as o:
json.dump(requestthrottle, o, indent=2)
except KeyError:
try:
if requestthrottle[znc_username_string] > 0: # KeyError if host doesn't exist.
requestthrottle[znc_username_string] = 0
sendmsg(message['replyto'], message['nick'] +": {0} {1} {2}".format(i18n['host'], str(znc_username_string), i18n['request_timer_reset']))
with open('requestthrottle.json', 'w') as o:
json.dump(requestthrottle, o, indent=2)
except KeyError:
sendmsg(message['replyto'], message['nick'] +": {0} {1} {2}".format(i18n['error_user_or_host'], str(znc_username_string), i18n['404']))
def cmd_approve(message, znc_username):
znc_username_string = ''.join(znc_username)
try:
znc_username_real = zncusersdb["users"][znc_username_string.lower()]["real_username"]
if_user_match = znc_username_string.lower() == znc_username_real.lower()
user_state = zncusersdb["users"][znc_username_string.lower()]["state"]
if if_user_match and user_state == "Pending":
sendraw("ZNC *controlpanel set bindhost {0} {1}\n".format(str(znc_username_real), config['znchost']))
sendmsg(message['replyto'], message['nick'] +": {0} {1} {2}".format(i18n['user'], str(znc_username_string.lower()),i18n['user_been_approved']))
zncusersdb["users"][str(cmd_args[1]).lower()]["status_date"] = str(time.ctime(int(time.time())))
zncusersdb["users"][str(cmd_args[1]).lower()]["status_changed_by"] = str(message['nick'])
zncusersdb["users"][znc_username_string.lower()]["state"] = "Approved"
with open('zncusersdb.json', 'w') as f:
json.dump(zncusersdb, f, indent=2)
elif if_user_match and user_state == "Approved":
sendmsg(message['replyto'], message['nick'] +": {0} {1} {2}".format(i18n['error_user'], str(znc_username_string.lower()), i18n['already_approved']))
elif if_user_match and user_state == "Denied":
sendmsg(message['replyto'], message['nick'] +": {0} {1} {2}".format(i18n['error_user'], str(znc_username_string.lower()), i18n['already_approved']))
except KeyError:
sendmsg(message['replyto'], message['nick'] +": {0} {1} {2}".format(i18n['error_user'], str(znc_username_string.lower()), i18n['404']))
def cmd_adduser(message, znc_username):
znc_username_string = ''.join(znc_username)
try:
if znc_username_string.lower() in zncuserlist["main"]:
sendmsg(message['replyto'], message['nick'] +": {0} {1} {2}".format(i18n['error_user'], str(znc_username_string.lower()), i18n['already_added']))
else:
zncusersdb["users"][str(znc_username_string).lower()] = {}
zncusersdb["users"][str(znc_username_string).lower()]["state"] = "Approved"
zncusersdb["users"][str(znc_username_string).lower()]["real_username"] = str(znc_username_string)
zncusersdb["users"][str(znc_username_string).lower()]["nick_registered_as"] = "N/A"
zncusersdb["users"][str(znc_username_string).lower()]["userhost_registered_as"] = "N/A"
zncusersdb["users"][str(znc_username_string).lower()]["date_registered"] = "N/A"
zncusersdb["users"][str(znc_username_string).lower()]["isonline"] = "False"
zncusersdb["users"][str(cmd_args[1]).lower()]["status_date"] = "N/A"
zncusersdb["users"][str(cmd_args[1]).lower()]["status_changed_by"] = str(message['nick'])
zncusersdb["users"][znc_username_string.lower()]["state"] = "Approved"
zncusersdb["users"][str(cmd_args[1]).lower()]["onlinecount"] = 0
zncuserlist["main"].append(znc_username_string.lower())
sendmsg(message['replyto'], message['nick'] +": {0} {1} {2}".format(i18n['user'], str(znc_username_string.lower()), i18n['OK_manually_added']))
with open("zncuserlist.json", 'w') as n:
json.dump(zncuserlist, n, indent=2)
with open('zncusersdb.json', 'w') as f:
json.dump(zncusersdb, f, indent=2)
except KeyError:
zncusersdb["users"][str(znc_username_string).lower()] = {}
zncusersdb["users"][str(znc_username_string).lower()]["state"] = "Approved"
zncusersdb["users"][str(znc_username_string).lower()]["real_username"] = str(znc_username_string.lower())
zncusersdb["users"][str(znc_username_string).lower()]["nick_registered_as"] = "N/A"
zncusersdb["users"][str(znc_username_string).lower()]["userhost_registered_as"] = "N/A"
zncusersdb["users"][str(znc_username_string).lower()]["date_registered"] = "N/A"
zncusersdb["users"][str(znc_username_string).lower()]["isonline"] = "False"
zncusersdb["users"][str(cmd_args[1]).lower()]["status_date"] = "N/A"
zncusersdb["users"][str(cmd_args[1]).lower()]["status_changed_by"] = str(message['nick'])
zncusersdb["users"][str(cmd_args[1]).lower()]["onlinecount"] = 0
zncuserlist["main"].append(znc_username_string.lower())
sendmsg(message['replyto'], message['nick'] +": {0} {1} {2}".format(i18n['user'], str(znc_username_string.lower()), i18n['OK_manually_added']))
with open("zncuserlist.json", 'w') as n:
json.dump(zncuserlist , n, indent=2)
with open('zncusersdb.json', 'w') as f:
json.dump(zncusersdb, f, indent=2)
def cmd_deluser(message, znc_username):
znc_username_string = ''.join(znc_username)
try:
if znc_username_string.lower() in zncuserlist["main"]:
zncuserlist["main"].remove(znc_username_string.lower())
znc_username_real = zncusersdb["users"][znc_username_string.lower()]["real_username"]
sendraw("ZNC *controlpanel DelUser" + " " + str(znc_username_real) + "\n")
zncusersdb["users"][znc_username_string.lower()]["state"] = "Deleted"
sendmsg(message['replyto'], message['nick'] +": {0} {1} {2}".format(i18n['user'], str(znc_username_string.lower()), i18n['OK_deleted']))
with open("zncuserlist.json", 'w') as n:
json.dump(zncuserlist, n, indent=2)
with open('zncusersdb.json', 'w') as f:
json.dump(zncusersdb, f, indent=2)
else:
sendmsg(message['replyto'], message['nick'] +": {0} {1} {2}".format(i18n['error_user'], str(znc_username_string.lower()),i18n["either_deleted_or_404"]))
except KeyError:
sendmsg(message['replyto'], message['nick'] +": {0} {1} {2}".format(i18n['error_user'], str(znc_username_string.lower()), i18n["either_deleted_or_404"]))
def cmd_userinfo(message, znc_username):
znc_username_string = ''.join(znc_username)
sendmsg(message['replyto'], message['nick'] +": {0}".format(i18n['grab_info_send_pm']))
try:
#if zncusersdb["users"][str(cmd_args[1]).lower()]["isonline"]:
# isonline = True
#else:
# isonline = False
znc_username_real = zncusersdb["users"][znc_username_string.lower()]["real_username"]
if_user_pending = znc_username_string.lower() == znc_username_real.lower()
user_state = zncusersdb["users"][znc_username_string.lower()]["state"]
nick_registered_as = zncusersdb["users"][str(cmd_args[1]).lower()]["nick_registered_as"]
userhost_registered_as = zncusersdb["users"][str(cmd_args[1]).lower()]["userhost_registered_as"]
sendmsg(message['nick'], "*{0} {1}*".format(i18n['info_user'], znc_username_string))
if nick_registered_as == "N/A":
sendmsg(message['nick'], "Note: This user {0}".format(i18n['OK_manually_added']))
else:
sendmsg(message['nick'], "{0} {1}".format(i18n['account_status'], user_state))
sendmsg(message['nick'], "{0} {1}".format(i18n['nick_registered_as'], nick_registered_as))
sendmsg(message['nick'], "{0} {1}".format(i18n['userhost_registered_as'], userhost_registered_as))
sendmsg(message['nick'], "{0} {1}".format(i18n['real_ZNC_username'], znc_username_real))
if not nick_registered_as == "N/A":
sendmsg(message['nick'], "{0} {1}".format(i18n['date_requested'], zncusersdb["users"][str(cmd_args[1]).lower()]["date_registered"]))
#sendmsg(message['nick'], "{0} {1}".format(i18n['online'], isonline))
if user_state == "Approved" and nick_registered_as != "N/A":
sendmsg(message['nick'], "{0} {1}".format(i18n['approval_date'], zncusersdb["users"][str(cmd_args[1]).lower()]["status_date"]))
sendmsg(message['nick'], "{0} {1}".format(i18n['approved_by'], zncusersdb["users"][str(cmd_args[1]).lower()]["status_changed_by"]))
elif user_state == "Denied" and nick_registered_as != "N/A":
sendmsg(message['nick'], "{0} {1}".format(i18n['Date denied:'], zncusersdb["users"][str(cmd_args[1]).lower()]["status_date"]))
sendmsg(message['nick'], "{0} {1}".format(i18n['denied_by'], zncusersdb["users"][str(cmd_args[1]).lower()]["status_changed_by"]))
elif nick_registered_as == "N/A":
sendmsg(message['nick'], "{0} {1}".format(i18n['manually_added_by'], zncusersdb["users"][str(cmd_args[1]).lower()]["status_changed_by"]))
except KeyError:
try:
if znc_username_string.lower() in zncusers["main"]:
sendmsg(message['nick'], "*{0} {1}*".format(i18n['info_user'], znc_username_string))
except:
sendmsg(message['replyto'], message['nick'] +": {0} {1} {2}".format(i18n['error_user'], str(znc_username_string.lower()), i18n['404']))
def cmd_deny(message, znc_username):
znc_username_string = ''.join(znc_username)
try:
znc_username_real = zncusersdb["users"][znc_username_string.lower()]["real_username"]
if_user_match = znc_username_string.lower() == znc_username_real.lower()
user_state = zncusersdb["users"][znc_username_string.lower()]["state"]
if if_user_match and user_state == "Pending":
sendraw("ZNC *controlpanel DelUser" + " " + str(znc_username_real) + "\n")
sendmsg(message['replyto'], message['nick'] +": {0} {1} {2}".format(i18n['user'], str(znc_username_string.lower()), i18n['OK_denied']))
zncusersdb["users"][znc_username_string.lower()]["state"] = "Denied"
zncusersdb["users"][str(cmd_args[1]).lower()]["status_date"] = str(time.ctime(int(time.time())))
zncusersdb["users"][str(cmd_args[1]).lower()]["status_changed_by"] = str(message['nick'])
with open('zncusersdb.json', 'w') as f:
json.dump(zncusersdb, f, indent=2)
zncuserlist["main"].remove(znc_username_string.lower())
with open("zncuserlist.json", 'w') as n:
json.dump(zncuserlist, n, indent=2)
elif if_user_match and user_state == "Approved":
sendmsg(message['replyto'], message['nick'] +": {0} {1} {2}".format(i18n['error_user'], str(znc_username_string.lower()), i18n['already_approved']))
elif if_user_match and user_state == "Denied":
sendmsg(message['replyto'], message['nick'] +": {0} {1} {2}".format(i18n['error_user'], str(znc_username_string.lower()), i18n['already_denied']))
except KeyError:
sendmsg(message['replyto'], message['nick'] +": {0} {1} {2}".format(i18n['error_user'], str(znc_username_string.lower()), i18n['404']))
def zncrequest(message, cmd_args):
nick_formatted1 = re.sub(r'\x03\d{1,2}(?:,\d{1,2})?', '', str(cmd_args[0]))
nick_formatted2 = re.sub(r'\x02|\x03|\x16|\x1D|\x1F', '', nick_formatted1)
sendmsg(message['replyto'], message['nick'] +": {0}".format(i18n['create_account_send_details']))
length = 10
chars = string.ascii_letters + string.digits
random.seed = (os.urandom(2048))
key = ''.join(random.choice(chars) for i in range(length))
sendraw("ZNC *controlpanel CloneUser cloneuser {0}\n".format(nick_formatted2))
sendraw("ZNC *controlpanel set password {0} {1}\n".format(nick_formatted2, key))
sendraw("ZNC *controlpanel set nick {0} {1}\n".format(nick_formatted2, nick_formatted2))
sendraw("ZNC *controlpanel set altnick {0} {1}\n".format(nick_formatted2, nick_formatted2))
sendraw("ZNC *controlpanel set ident {0} {1}\n".format(nick_formatted2, nick_formatted2))
sendmsg(message['nick'], "{0}".format(i18n['account_created']))
sendmsg(message['nick'], "{0} {1}".format(i18n['username'], nick_formatted2))
sendmsg(message['nick'], "{0} {1}".format(i18n['password'], key))
sendmsg(message['nick'], "{0}".format(i18n['recommend_chg_pass_note']))
sendmsg(message['nick'], "{0} {1}".format(i18n['webpanel'], config['webpanel']))
if len(config['zncircport']) <= 0:
sendmsg(message['nick'], "IRC: {0}, port {1} for SSL, or {2} for standard.".format(config['zncircserver'], config['zncssl'], config['zncstandard']))
elif len(config['zncircportisssl']) > 0:
if config["zncircportisssl"] == "True":
sendmsg(message['nick'], "IRC: {0}, port {1} (SSL is supported)".format(config['zncircserver'], config['zncircport']))
elif config["zncircportisssl"] == "False":
sendmsg(message['nick'], "IRC: {0}, port {1} (SSL isn't supported)".format(config['zncircserver'], config['zncircport']))
if len(config['torhs']) >= 2:
sendmsg(message['nick'], "({0}, {1})".format(i18n['announce_hs'], config['torhs']))
if config['disableapproval'] == "False":
sendmsg(message['nick'], "{0}".format(i18n['note_account_require_approval']))
sendmsg(message['nick'], "{0}".format(i18n["note_account_require_approval2"]))
if len(config['linktotos']) > 1:
sendmsg(message['nick'], "{0} {1}".format(i18n['info_about_tos'], config['linktotos']))
zncusersdb["users"][nick_formatted2.lower()] = {}
if config['disableapproval'] == "True":
zncusersdb["users"][nick_formatted2.lower()]["state"] = "Approved"
sendraw("ZNC *controlpanel set bindhost {0} {1}\n".format(str(nick_formatted2), config['znchost']))
else:
zncusersdb["users"][nick_formatted2.lower()]["state"] = "Pending"
zncusersdb["users"][nick_formatted2.lower()]["real_username"] = str(nick_formatted2)
zncusersdb["users"][nick_formatted2.lower()]["nick_registered_as"] = str(message['nick'])
zncusersdb["users"][nick_formatted2.lower()]["userhost_registered_as"] = str(message['userhost'])
zncusersdb["users"][nick_formatted2.lower()]["host_registered_as"] = str(message['host'])
zncusersdb["users"][nick_formatted2.lower()]["date_registered"] = str(time.ctime(int(time.time())))
zncusersdb["users"][nick_formatted2.lower()]["onlinecount"] = 0
zncusersdb["users"][nick_formatted2.lower()]["isonline"] = False
with open('zncusersdb.json', 'w') as b:
json.dump(zncusersdb, b, indent=2)
requestthrottle[message['host']] = int(time.time())
with open('requestthrottle.json', 'w') as o:
json.dump(requestthrottle, o, indent=2)
cache['lastrequest'] = int(time.time())
with open('cache.json', 'w') as g:
json.dump(cache, g, indent=2)
zncuserlist["main"].append(nick_formatted2.lower())
with open("zncuserlist.json", 'w') as n:
json.dump(zncuserlist, n, indent=2)
def cmd_request(message, cmd_args):
cache['already_alerted_bug'] = False
with open('cache.json', 'w') as g:
json.dump(cache, g, indent=2)
try:
if time.time() < cache['lastrequest'] + 60:
sendmsg(message['replyto'], message['nick'] +": {0}".format(i18n['global_requestthrottle_error']))
cache['already_alerted_bug'] = True
with open('cache.json', 'w') as g:
json.dump(cache, g, indent=2)
except KeyError:
pass
if "#" not in message['replyto']:
sendmsg(message['nick'], "{0} {1} {2}".format(i18n['join_channel_error'], config['reqchan'], i18n['to_use_request_command']))
elif user_registered == '-':
sendmsg(message['replyto'], message['nick'] +": {0} !request".format(i18n['identify_services_error']))
elif len(cmd_args) <= 0:
sendmsg(message['replyto'], message['nick'] +": {0} \x1f{1}\x1f".format(i18n['request_syntax'], i18n['username_without_comma']))
elif message['userhost'] in requestthrottle: # This 'elif' is for backwards compatibility with older databases.
if time.time() < requestthrottle[message['userhost']] + 86400:
sendmsg(message['replyto'], message['nick'] +": {0}".format(i18n['requestthrottle_error']))
else:
zncrequest(message, cmd_args)
elif message['host'] in requestthrottle:
if time.time() < requestthrottle[message['host']] + 86400 and not cache['already_alerted_bug']:
sendmsg(message['replyto'], message['nick'] +": {0}".format(i18n['requestthrottle_error']))
elif time.time() > requestthrottle[message['host']] + 86400 and not cache['already_alerted_bug']:
zncrequest(message, cmd_args)
elif cmd_args[0].lower() in zncuserlist['main']:
sendmsg(message['replyto'], message['nick'] +": Error: The username {0} is already taken!".format(cmd_args[0]))
#elif cmd_args[0].lower() in zncusersdb['users']:
#if zncusersdb["users"][str(cmd_args[0]).lower()]["state"] == "Pending" or zncusersdb["users"][str(cmd_args[0]).lower()]["state"] == "Approved":
#sendmsg(message['replyto'], message['nick'] +": Error: The username {0} is already taken!".format(cmd_args[0]))
#else:
#zncrequest(message, cmd_args)
elif " " in cmd_args[0] or "/" in cmd_args[0] or "[" in cmd_args[0] or "]" in cmd_args[0] or "|" in cmd_args[0]:
sendmsg(message['replyto'], message['nick'] +": Error: Please enter a more valid username.")
else:
zncrequest(message, cmd_args)
def parse_ircmsg(rawmsg):
tmp = rawmsg.split(' :', 1)
message = tmp[0].split(' ')
if len(tmp) > 1:
message.append(tmp[1])
nick = None
user = None
host = None
userhost = None
prefix = None
if message[0][0] == ':':
prefix = message.pop(0)
tmp = prefix.split('!', 1)
if len(tmp) > 1:
nick = tmp[0][1:]
userhost = tmp[1]
tmp = tmp[1].split('@', 1)
user = tmp[0]
if len(tmp) > 1:
host = tmp[1]
parsed = dict(nick=nick, user=user, host=host, userhost=userhost, prefix=prefix,
command=message[0], args=message[1:])
# convenience for PRIVMSGs
parsed['replyto'] = parsed['args'][0]
if len(parsed['replyto']) < 2:
pass
else:
if parsed['replyto'][0] != '#':
parsed['replyto'] = parsed['nick']
return parsed
if "+" in config['port']:
converted_port = config['port'].replace('+','')
ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ircsock.connect((config['server'], int(converted_port)))
ircsock = ssl.wrap_socket(ircsock)
else:
ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ircsock.connect((config['server'], int(config['port'])))
atexit.register(ircsock.close)
sendraw(irc_command("USER", config['zncuser'], config['zncuser'], config['zncuser'], 'SuchZNC registeration & utility bot'))
sendraw(irc_command("NICK", config['zncuser']))
sendraw(irc_command("PASS", "{0}/{1}:{2}\n".format(config['zncuser'], config['network'], config['zncpass'])))
lines = []
while True:
ircmsg = ''
if len(lines) <= 1:
rawmsg = ''
if len(lines) == 1:
rawmsg = lines.pop()
rawmsg += ircsock.recv(2048).decode("utf-8", "replace")
lines += rawmsg.split('\r\n')
if len(lines) > 1:
ircmsg = lines.pop(0)
else:
continue
if logging_level == logging.DEBUG:
logging.debug("RECV: " + ircmsg)
else:
pass
message = parse_ircmsg(ircmsg)
if message['command'] == 'PING':
ping(' '.join(message['args']))
#elif message['command'] == '437' or message['command'] == '433':
# logging.error("botnick {0} is unavailable.".format(config['botnick']))
# sys.exit("")
elif message['command'] == '376':
if config['use_identify-msg'] == "True":
sendraw("znc *send_raw server znc {0} cap req identify-msg\n".format(config['network']))
elif message['command'] == "JOIN":
if len(cache['channel']) >= 1:
sendraw("PRIVMSG {0} :Restart completed!\n".format(cache['channel']))
cache['channel'] = ""
with open('cache.json', 'w') as g:
json.dump(cache, g, indent=2)
elif message['command'] == 'ERROR':
sys.exit(0)
elif message['args'][-1] == '\x01VERSION\x01':
sendraw("NOTICE {0} :\x01VERSION SuchZNC ZNC Utility-ish IRC bot, running on Python {1}\x01\r\n".format(message['nick'], python_version()))
elif message['args'][-1] == '\x01TIME\x01':
sendraw("NOTICE {0} :\x01TIME {1}\x01\r\n".format(message['nick'], time.strftime("%c, %Z")))
elif message['command'] == 'NOTICE':
notice_args = message['args'][-1].split(' ')
if len(notice_args) == 0:
continue
#if '***' == notice_args[0]:
#if message['nick'] == '*status':
#if notice_args[2] == "attached":
#zncusersdb["users"][str(notice_args[1]).lower()]["isonline"] = "True"
#zncusersdb["users"][str(notice_args[1]).lower()]["lastlogin"] = str(time.ctime(int(time.time())))
#with open('zncusersdb.json', 'w') as b:
#json.dump(zncusersdb, b, indent=2)
#try:
#zncusersdb["users"][str(notice_args[1]).lower()]["onlinecount"] = zncusersdb["users"][str(notice_args[1]).lower()]["onlinecount"] + 1
#except KeyError:
#zncusersdb["users"][str(notice_args[1]).lower()]["onlinecount"] = 1
#with open('zncusersdb.json', 'w') as b:
#json.dump(zncusersdb, b, indent=2)
#if zncusersdb["users"][str(notice_args[1]).lower()]["onlinecount"] >= 1:
#zncusersdb["users"][str(notice_args[1]).lower()]["isonline"] = "True"
#with open('zncusersdb.json', 'w') as b:
#json.dump(zncusersdb, b, indent=2)
#elif notice_args[2] == "detached":
# try:
# zncusersdb["users"][str(notice_args[1]).lower()]["onlinecount"] = zncusersdb["users"][str(notice_args[1]).lower()]["onlinecount"] - 1
# except KeyError:
# zncusersdb["users"][str(notice_args[1]).lower()]["onlinecount"] = 0
# with open('zncusersdb.json', 'w') as b:
# json.dump(zncusersdb, b, indent=2)
# if zncusersdb["users"][str(notice_args[1]).lower()]["onlinecount"] == 0:
# zncusersdb["users"][str(notice_args[1]).lower()]["isonline"] = "False"
# if zncusersdb["users"][str(notice_args[1]).lower()]["onlinecount"] <= -1:
# zncusersdb["users"][str(notice_args[1]).lower()]["onlinecount"] = 0
# with open('zncusersdb.json', 'w') as b:
# json.dump(zncusersdb, b, indent=2)
elif message['command'] == 'PRIVMSG':
command = None
access = acs_normal
cmd_args = message['args'][-1].split(' ')
if len(cmd_args) == 0:
continue
wanted_char = "!"
if config['use_identify-msg'] == "True":
user_registered = cmd_args[0][0]
try:
used_char = cmd_args[0][1]
except IndexError:
pass
command_word = cmd_args[0].lower()[2:]
else:
user_registered = "null"
used_char = cmd_args[0][0:len(wanted_char)]
command_word = cmd_args[0].lower()[len(wanted_char):]
if used_char != wanted_char:
continue
if command_word == 'ping':
sendmsg(message['replyto'], "{0}: PONG".format(message['nick']))
if command_word == 'request':
with open(os.path.join('i18n', f"{userlang.get(message['userhost'], config['language'])}.json")) as fd:
i18n = json.load(fd)
if any(wildcard_match(admin, message['host']) for admin in config['znchostmasks']):
sendmsg(message['replyto'], message['nick'] +": Error: You already have a ZNC account!")
else:
access = acs_normal
command = cmd_request
if command_word == 'approve':
access = acs_admin
with open(os.path.join('i18n', f"{userlang.get(message['userhost'], config['language'])}.json")) as fd:
i18n = json.load(fd)
if len(cmd_args) < 2:
sendmsg(message['replyto'], message['nick'] +": Syntax: !approve \x1fusername\x1f")
else:
znc_username = cmd_args[1]
command = cmd_approve
if command_word == 'deny':
access = acs_admin
with open(os.path.join('i18n', f"{userlang.get(message['userhost'], config['language'])}.json")) as fd:
i18n = json.load(fd)
if len(cmd_args) < 2:
sendmsg(message['replyto'], message['nick'] +": Syntax: !deny \x1fusername\x1f")
else:
znc_username = cmd_args[1]
command = cmd_deny
if command_word == 'adduser':
access = acs_admin
with open(os.path.join('i18n', f"{userlang.get(message['userhost'], config['language'])}.json")) as fd:
i18n = json.load(fd)
if len(cmd_args) < 2:
sendmsg(message['replyto'], message['nick'] +": Syntax: !adduser \x1fusername\x1f")
else:
znc_username = cmd_args[1]
command = cmd_adduser
if command_word == 'deluser':
access = acs_admin
with open(os.path.join('i18n', f"{userlang.get(message['userhost'], config['language'])}.json")) as fd:
i18n = json.load(fd)
if len(cmd_args) < 2:
sendmsg(message['replyto'], message['nick'] +": Syntax: !deluser \x1fusername\x1f")
else:
znc_username = cmd_args[1]
command = cmd_deluser
if command_word == 'userinfo':
access = acs_admin
with open(os.path.join('i18n', f"{userlang.get(message['userhost'], config['language'])}.json")) as fd:
i18n = json.load(fd)
if len(cmd_args) < 2:
sendmsg(message['replyto'], message['nick'] +": Syntax: !userinfo \x1fusername\x1f")
else:
znc_username = cmd_args[1]
command = cmd_userinfo
if command_word == 'restart':
access = acs_admin
command = cmd_restart
if command_word == 'timereset':
access = acs_admin
if len(cmd_args) < 2:
sendmsg(message['replyto'], message['nick'] +": Syntax: !timereset \x1fZNC username or host\x1f")
else:
znc_username = cmd_args[1]
command = cmd_timereset
if command_word == 'userlang':
if len(cmd_args) < 2:
sendmsg(message['replyto'], message['nick'] +": Syntax: !userlang \x1flanguage\x1f")
else:
userlang[message['userhost']] = str(cmd_args[1])
with open('userlang.json', 'w') as p:
json.dump(userlang, p, indent=2)
if not command is None:
if access(message):
try:
command(message, cmd_args[1], args)
except:
command(message, cmd_args[1:])
else:
sendmsg(message['replyto'], message['nick'] +": Permission Denied")