-
Notifications
You must be signed in to change notification settings - Fork 15
/
telegramircd.py
executable file
·2306 lines (2013 loc) · 86.6 KB
/
telegramircd.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
#!/usr/bin/env python3
from configargparse import ArgParser, Namespace
#from ipdb import set_trace as bp
from collections import deque
from datetime import datetime, timezone
from itertools import chain
import subprocess
from telethon import TelegramClient
from telethon.errors import SessionPasswordNeededError
import telethon.tl as tl
#from telethon.tl.functions.contacts import GetContactsRequest
import telethon.tl.types as tg_types
import telethon.tl.functions.contacts
import telethon.tl.functions.messages
import aiohttp.web, asyncio, base64, inspect, json, logging.handlers, magic, os, pprint, random, re, \
shlex, signal, socket, ssl, string, sys, tempfile, time, traceback, uuid, weakref
logger = logging.getLogger('telegramircd')
im_name = 'Telegram'
capabilities = set(['away-notify', 'draft/message-tags', 'echo-message', 'multi-prefix', 'sasl', 'server-time']) # http://ircv3.net/irc/
options = None
server = None
web = None
def debug(msg, *args):
logger.debug(msg, *args)
def info(msg, *args):
logger.info(msg, *args)
def warning(msg, *args):
logger.warning(msg, *args)
def error(msg, *args):
logger.error(msg, *args)
class ExceptionHook(object):
instance = None
def __call__(self, *args, **kwargs):
if self.instance is None:
from IPython.core import ultratb
self.instance = ultratb.VerboseTB(call_pdb=True)
return self.instance(*args, **kwargs)
class TelegramCliFail(Exception):
def __init__(self, *msg):
super().__init__(*msg)
### HTTP server
class Web(object):
def __init__(self, tls):
global web
web = self
self.tls = tls
self.id2media = {}
self.id2message = {}
self.webpage_id2sender_to = {}
self.recent_messages = deque()
self.proc = None
self.authorized = False
self.two_step = False
async def handle_media(self, typ, request):
id = re.sub(r'\..*', '', request.match_info.get('id'))
if id not in self.id2media:
return aiohttp.web.Response(status=404, text='Not Found')
try:
media, filename = self.id2media[id]
if not filename:
try:
with tempfile.NamedTemporaryFile(dir=options.tg_media_dir, suffix='.blob') as temp:
filename = temp.name
self.proc.download_media(media, filename)
self.id2media[id] = (media, filename)
except asyncio.TimeoutError:
return aiohttp.web.Response(status=504, text='I used to live in 504A')
except TelegramCliFail as ex:
return aiohttp.web.Response(status=404, text=ex.args[0])
with open(filename, 'rb') as f:
mime = None
if sys.platform == 'linux':
try:
mime = subprocess.check_output(['xdg-mime', 'query', 'filetype', filename],
stdin=subprocess.DEVNULL).decode().strip()
except:
pass
if mime is None:
mime = magic.from_file(filename, mime=True)
return aiohttp.web.Response(body=f.read(), headers={'Content-Type': mime})
except Exception as ex:
return aiohttp.web.Response(status=500, text=str(ex))
async def handle_document(self, request):
return await self.handle_media('document', request)
def run_telethon(self):
if self.proc:
self.proc.disconnect()
self.proc = TelegramClient(options.tg_session, options.tg_api_id, options.tg_api_hash)
try:
self.proc.connect()
except:
error('Failed to connect to Telegram server')
sys.exit(2)
self.authorized = self.proc.is_user_authorized()
if not self.authorized and not options.tg_phone:
error('Not authorized. Please set --tg-phone')
sys.exit(2)
self.proc.add_event_handler(server.on_telegram_update)
async def restart_telegram_cli(self):
traceback.print_stack()
if self.proc:
try:
self.proc.disconnect()
time.sleep(1)
except:
pass
os.execl(sys.executable, sys.executable, *sys.argv)
def start(self, listens, port, loop):
self.loop = loop
self.app = aiohttp.web.Application()
self.app.router.add_route('GET', '/document/{id}', self.handle_document)
self.handler = self.app.make_handler()
self.srv = []
for i in listens:
self.srv.append(loop.run_until_complete(
loop.create_server(self.handler, i, port, ssl=self.tls)))
self.run_telethon()
if self.authorized:
self.init()
#async def poll():
# while 1:
# await asyncio.sleep(options.tg_poll_interval)
# for peer_id in options.tg_poll_channels:
# self.proc.stdin.write('history channel#{} {}\n'.format(peer_id, options.tg_poll_limit).encode())
#if options.telegram_cli_poll_channels:
# self.poll = loop.create_task(poll())
def stop(self):
self.proc.disconnect()
for i in self.srv:
i.close()
self.loop.run_until_complete(i.wait_closed())
self.loop.run_until_complete(self.app.shutdown())
self.loop.run_until_complete(self.handler.shutdown(3))
self.loop.run_until_complete(self.app.cleanup())
for _, filename in self.id2media.values():
if filename:
try:
os.unlink(filename)
except:
pass
def append_history(self, record):
if len(self.recent_messages) >= 10000:
msg = self.recent_messages.popleft()
del self.id2message[msg['id']]
self.recent_messages.append(record)
self.id2message[record['id']] = record
# TODO admin channel.update_admins(members)
def channel_get_participants(self, channel):
tg_users = []
offset = 0
while True:
participants = self.proc(tl.functions.channels.GetParticipantsRequest(
channel.tg_room,
tl.types.ChannelParticipantsSearch(''),
offset,
100,
0, # hash
))
if not participants.users: break
tg_users.extend(participants.users)
offset += len(participants.users)
channel.update_members(tg_users)
def channel_invite(self, client, channel, user):
try:
if channel.is_type(tl.types.PeerChannel):
self.proc(tl.functions.channels.InviteToChannelRequest(
channel.peer.channel_id,
[self.proc.get_input_entity(user.user_id)]
))
elif channel.is_type(tl.types.PeerChat):
self.proc(tl.functions.messages.AddChatUserRequest(
channel.peer.chat_id,
self.proc.get_input_entity(user.user_id),
0,
))
except telethon.errors.rpcerrorlist.UserAlreadyParticipantError:
client.err_useronchannel(user.nick, channel.name)
except telethon.errors.rpcbaseerrors.RPCError:
pass
async def channel_set_admin(self, client, channel, user, ty):
if channel.is_type(tl.types.PeerChannel):
try:
await self.send_command('channel_set_admin {} {} {}'.format(channel.peer, user.peer, ty))
except (asyncio.TimeoutError, TelegramCliFail):
client.err_chanoprivsneeded(channel.name)
else:
if ty == 0:
self.unset_cmode(user, 'h')
self.unset_cmode(user, 'o')
elif ty == 1:
self.set_cmode(user, 'h')
channel.halfop_event(user)
elif ty == 2:
self.set_cmode(user, 'o')
channel.op_event(user)
else:
client.err_chanoprivsneeded(channel.name)
def channel_kick(self, client, channel, user):
try:
if channel.is_type(tl.types.PeerChannel):
pass
elif channel.is_type(tl.types.PeerChat):
self.proc(tl.functions.messages.DeleteChatUserRequest(
channel.peer.chat_id,
self.proc.get_input_entity(user.user_id),
))
except telethon.errors.rpcerrorlist.UserNotParticipantError:
client.err_usernotinchannel(user.nick, channel.name)
except telethon.errors.rpcbaseerrors.RPCError:
pass
def chat_get_full(self, channel):
chatfull = self.proc(tl.functions.messages.GetFullChatRequest(
channel.tg_room.id
))
channel.update_members(chatfull.users)
def contact_list(self):
contacts = self.proc(tl.functions.contacts.GetContactsRequest(0))
for tg_user in contacts.users:
server.ensure_special_user(tg_user.id, tg_user)
def channel_list(self):
# https://github.com/LonamiWebs/Telethon/wiki/Retrieving-all-dialogs
last_date = None
chunk_size = 20
while True:
debug('channel_list %r', last_date)
r = self.proc(tl.functions.messages.GetDialogsRequest(
offset_date=last_date,
offset_id=0,
offset_peer=tl.types.InputPeerEmpty(),
limit=chunk_size,
hash=0
))
for tg_user in r.users:
server.ensure_special_user(tg_user.id, tg_user)
# Channel & Chat & ChatForbidden & ...
for tg_room in r.chats:
if isinstance(tg_room, (tl.types.Channel, tl.types.Chat)):
server.ensure_special_room(tg_room.id, tg_room)
if not r.messages: break
date = min(msg.date for msg in r.messages)
if date == last_date: break
last_date = date
time.sleep(0.7)
def channel_message_get(self, channel, id):
messages = self.proc(tl.functions.channels.GetMessagesRequest(
self.proc.get_input_entity(channel.peer), [id])).messages
return messages[0] if messages else None
def message_get(self, id):
messages = self.proc(tl.functions.messages.GetMessagesRequest([id])).messages
return messages[0] if messages else None
def get_self(self):
data = self.proc.get_me()
server.user_id = data.id
def init(self):
try:
web.get_self()
web.channel_list()
web.contact_list()
except Exception as ex:
traceback.print_exc()
def mark_read(self, peer, max_id):
self.proc.send_read_acknowledge(peer, max_id=max_id)
def channel_members(self, channel):
try:
if channel.is_type(tl.types.PeerChannel):
self.channel_get_participants(channel)
elif channel.is_type(tl.types.PeerChat):
self.chat_get_full(channel)
except Exception as ex:
error('channel_members %r', channel)
traceback.print_exc()
def send_file(self, client, peer, filename, body):
with tempfile.TemporaryDirectory() as directory:
filename = os.path.join(directory, filename)
try:
with open(filename, 'wb') as f:
f.write(body)
f.flush()
self.proc.send_file(peer, f.name)
except telethon.errors.rpcbaseerrors.RPCError:
client.err_cannotsendtochan(peer.nick, 'Cannot send the file')
os.unlink(filename)
def msg(self, client, to, text, reply_to=None):
try:
msg = self.proc.send_message(to.peer, text, reply_to=reply_to)
irc_log(to, to, msg.date, client, msg.message)
except telethon.errors.rpcbaseerrors.RPCError:
traceback.print_exc()
if isinstance(to.peer, SpecialChannel):
client.err_nosuchchannel(to.name)
elif isinstance(to.peer, SpecialUser):
client.err_nosuchnick(to.nick)
### IRC utilities
def irc_lower(s):
irc_trans = str.maketrans(string.ascii_uppercase + '[]\\^',
string.ascii_lowercase + '{}|~')
return s.translate(irc_trans)
# loose
def irc_escape(s):
s = re.sub(r',', '.', s) # `,` is used as seprator in IRC messages
s = re.sub(r'&?', '', s) # chatroom name may include `&`
s = re.sub(r'<[^>]*>', '', s) # remove emoji
return re.sub(r'[^-\w$%^*()=./]', '', s)
def irc_escape_nick(s):
return re.sub('^[&#!+:]*', '', irc_escape(s))
def process_text(to, text):
# !m
# @(\d\d)(\d\d)(\d\d)?
reply = None
multiline = False
while 1:
cont = False
in_channel = isinstance(to, SpecialChannel)
match = re.match(r'@(\d\d)(\d\d)(\d\d)? ', text)
if match:
cont = True
text = text[match.end():]
HH, MM, SS = int(match.group(1)), int(match.group(2)), match.group(3)
if SS is not None:
SS = int(SS)
for msg in reversed(web.recent_messages):
if (msg['to'] is to and msg['from'] is not server) if in_channel \
else (msg['from'] is to and msg['to'] is server):
# UTC -> local
dt = datetime.fromtimestamp(msg['date'].timestamp())
if dt.hour == HH and dt.minute == MM and (SS is None or dt.second == SS):
reply = msg['id']
break
match = re.match(r'@(\d{1,2}) ', text)
if match:
cont = True
text = text[match.end():]
which = int(match.group(1))
if which > 0:
for msg in reversed(web.recent_messages):
if not msg['inferred']:
if (msg['to'] is to and msg['from'] is not server) if in_channel \
else (msg['from'] is to and msg['to'] is server):
which -= 1 if 'media' in msg else len(msg['message'].splitlines())
if which <= 0:
reply = msg['id']
break
if text.startswith('!m '):
cont = True
text = text[3:]
multiline = True
if not cont: break
if multiline:
text = text.replace('\\n', '\n')
# nick: -> @username
at = ''
i = 0
while i < len(text) and text[i] != ' ':
j = text.find(': ', i)
if j == -1: break
nick = text[i:j]
if not server.has_special_user(nick): break
at += '@'+server.get_special_user(nick).preferred_nick()+' '
i = j+2
return reply, at + text[i:]
def irc_log(where, peer, local_time, sender, line):
if options.logger_mask is None:
return
for regex in options.logger_ignore or []:
if re.search(regex, peer.name):
return
filename = local_time.strftime(options.logger_mask.replace('$channel', peer.nick))
time_str = local_time.strftime(options.logger_time_format.replace('$channel', peer.nick))
if where.log_file is None or where.log_file.name != filename:
if where.log_file is not None:
where.log_file.close()
os.makedirs(os.path.dirname(filename), exist_ok=True)
where.log_file = open(filename, 'a')
where.log_file.write('{}\t{}\t{}\n'.format(
time_str, sender.nick,
re.sub(r'\x03\d+(,\d+)?|[\x02\x0f\x1d\x1f\x16]', '', line)))
where.log_file.flush()
def irc_privmsg(client, command, to, text):
if command == 'PRIVMSG' and client.ctcp(to.peer, text):
return
def send():
web.msg(client, to, to.privmsg_text, to.privmsg_reply)
to.last_text_by_client[client] = to.privmsg_text
to.privmsg_reply = None
to.privmsg_text = ''
async def wait(seq):
await asyncio.sleep(options.paste_wait)
if to.privmsg_seq == seq:
send()
reply, text = process_text(to, text)
if reply and len(to.privmsg_text):
send()
to.privmsg_reply = reply
to.privmsg_seq = to.privmsg_seq+1
if len(to.privmsg_text):
to.privmsg_text += '\n'
to.privmsg_text += text
server.loop.create_task(wait(to.privmsg_seq))
### Commands
cmd_use_case = {}
def registered(v):
def wrapped(fn):
cmd_use_case[fn.__name__] = v
return fn
return wrapped
class Command:
@staticmethod
@registered(7)
def authenticate(client, arg):
if arg.upper() == 'PLAIN':
client.write('AUTHENTICATE +')
return
if not (client.nick and client.user):
return
try:
if base64.b64decode(arg).split(b'\0')[2].decode() == options.sasl_password:
client.authenticated = True
client.reply('900 {} {} {} :You are now logged in as {}', client.nick, client.user, client.nick, client.nick)
client.reply('903 {} :SASL authentication successful', client.nick)
client.register()
else:
client.reply('904 {} :SASL authentication failed', client.nick)
except:
client.reply('904 {} :SASL authentication failed', client.nick)
@staticmethod
def away(client):
pass
@staticmethod
@registered(7)
def cap(client, *args):
if not args: return
comm = args[0].lower()
if comm == 'list':
client.reply('CAP * LIST :{}', ' '.join(client.capabilities))
elif comm == 'ls':
client.reply('CAP * LS :{}', ' '.join(capabilities))
elif comm == 'req':
enabled, disabled = set(), set()
for name in args[1].split():
if name.startswith('-'):
disabled.add(name[1:])
else:
enabled.add(name)
client.capabilities = (capabilities & enabled) - disabled
client.reply('CAP * ACK :{}', ' '.join(client.capabilities))
@staticmethod
def info(client):
client.rpl_info('{} users', len(server.nicks))
client.rpl_info('{} {} users', im_name, len(client.nick2special_user))
client.rpl_info('{} {} rooms', im_name, len(client.name2special_room))
@staticmethod
def invite(client, nick, channelname):
if client.is_in_channel(channelname):
server.get_channel(channelname).on_invite(client, nick)
else:
client.err_notonchannel(channelname)
@staticmethod
def ison(client, *nicks):
client.reply('303 {} :{}', client.nick,
' '.join(nick for nick in nicks
if server.has_nick(nick)))
@staticmethod
def join(client, *args):
if not args:
self.err_needmoreparams('JOIN')
else:
arg = args[0]
if arg == '0':
channels = list(client.channels.values())
for channel in channels:
channel.on_part(client, channel.name)
else:
JOINCHAT = 'https://t.me/joinchat/'
for channelname in arg.split(','):
# Join via joinchat link
if channelname.startswith(JOINCHAT):
web.proc(tl.functions.messages.ImportChatInviteRequest(channelname[len(JOINCHAT):]))
else:
if server.has_special_room(channelname):
server.get_special_room(channelname).on_join(client)
else:
try:
server.ensure_channel(channelname).on_join(client)
except ValueError:
client.err_nosuchchannel(channelname)
@staticmethod
def kick(client, channelname, nick, reason=None):
if client.is_in_channel(channelname):
server.get_channel(channelname).on_kick(client, nick, reason)
else:
client.err_notonchannel(channelname)
@staticmethod
def kill(client, nick, reason=None):
if not server.has_nick(nick):
client.err_nosuchnick(nick)
return
user = server.get_nick(nick)
if not isinstance(user, Client) or user == client:
client.err_nosuchnick(nick)
return
user.disconnect(reason)
@staticmethod
def list(client, arg=None):
if arg:
channels = []
for channelname in arg.split(','):
if server.has_channel(channelname):
channels.append(server.get_channel(channelname))
else:
web.init()
channels = set(server.channels.values())
channels.update(server.name2special_room.values())
channels = list(channels)
channels.sort(key=lambda ch: ch.name)
for channel in channels:
n = channel.n_members(client)
if n == 0 and channel.is_type(tl.types.PeerChat):
n = channel.tg_room.participants_count
client.reply('322 {} {} {} :{}', client.nick, channel.name, n, channel.topic)
client.reply('323 {} :End of LIST', client.nick)
@staticmethod
def lusers(client):
client.reply('251 :There are {} users and {} {} users on 1 server',
len(server.nicks),
len(server.nick2special_user),
im_name
)
@staticmethod
def mode(client, target, *args):
if server.has_nick(target):
if args:
client.err_umodeunknownflag()
else:
client.rpl_umodeis(server.get_nick(target).mode)
elif server.has_channel(target):
server.get_channel(target).on_mode(client, *args)
else:
client.err_nosuchchannel(target)
@staticmethod
def motd(client):
async def do():
try:
async with aiohttp.ClientSession() as session:
async with session.get('https://api.github.com/repos/MaskRay/telegramircd/commits') as resp:
client.reply('375 {} :- {} Message of the Day -', client.nick, server.name)
data = await resp.json()
for x in data[:5]:
client.reply('372 {} :- {} {} {}'.format(client.nick, x['sha'][:7], x['commit']['committer']['date'][:10], x['commit']['message'].replace('\n', '\\n')))
client.reply('376 {} :End of /MOTD command.', client.nick)
except:
pass
server.loop.create_task(do())
@staticmethod
def names(client, target):
if not client.is_in_channel(target):
client.err_notonchannel(target)
return
channel = server.get_channel(target)
web.channel_members(channel)
channel.on_names(client)
@staticmethod
@registered(7)
def nick(client, *args):
if len(options.irc_password) and not client.authenticated:
client.err_passwdmismatch('NICK')
return
if not args:
client.err_nonicknamegiven()
return
server.change_nick(client, args[0])
@staticmethod
@registered(7)
def oper(client, _, password):
ok = False
StatusChannel.instance.respond(client, 'Signing in...')
if web.two_step:
web.two_step = False
ok = web.proc.sign_in(password=password)
if not ok:
StatusChannel.instance.respond(client, 'Wrong password. Please type /oper a $login_code; /oper a $password')
else:
try:
ok = web.proc.sign_in(options.tg_phone, password)
if not ok:
StatusChannel.instance.respond(client, 'Wrong login code. Please type /oper a $login_code')
except SessionPasswordNeededError:
web.two_step = True
StatusChannel.instance.respond(client, 'Two step verification enabled. Please type /oper a $password')
if ok:
StatusChannel.instance.respond(client, 'Authorized. Initializing...')
web.init()
@staticmethod
def notice(client, *args):
Command.notice_or_privmsg(client, 'NOTICE', *args)
@staticmethod
def part(client, arg, *args):
partmsg = args[0] if args else None
for channelname in arg.split(','):
if client.is_in_channel(channelname):
server.get_channel(channelname).on_part(client, partmsg)
else:
client.err_notonchannel(channelname)
@staticmethod
@registered(6)
def pass_(client, password):
if len(options.irc_password) and password == options.irc_password:
client.authenticated = True
client.register()
@staticmethod
@registered(7)
def ping(client, *args):
if not args:
client.err_noorigin()
return
client.reply('PONG {} :{}', server.name, args[0])
@staticmethod
@registered(7)
def pong(client, *args):
pass
@staticmethod
def privmsg(client, *args):
Command.notice_or_privmsg(client, 'PRIVMSG', *args)
@staticmethod
@registered(7)
def quit(client, *args):
client.disconnect(args[0] if args else client.prefix)
@staticmethod
def squit(client, *args):
client.err_unknowncommand('SQUIT')
@staticmethod
def stats(client, query):
if len(query) == 1:
if query == 'u':
td = datetime.now() - server._boot
client.reply('242 {} :Server Up {} days {}:{:02}:{:02}',
client.nick, td.days, td.seconds // 3600,
td.seconds // 60 % 60, td.seconds % 60)
client.reply('219 {} {} :End of STATS report', client.nick, query)
@staticmethod
def summon(client, nick, msg):
client.err_nologin(nick)
@staticmethod
def time(client):
client.reply('391 {} {} :{}Z', client.nick, server.name,
datetime.utcnow().isoformat())
@staticmethod
def topic(client, channelname, new=None):
if not client.is_in_channel(channelname):
client.err_notonchannel(channelname)
return
server.get_channel(channelname).on_topic(client, new)
@staticmethod
def who(client, target):
if server.has_channel(target):
server.get_channel(target).on_who(client)
elif server.has_nick(target):
server.get_nick(target).on_who_member(client, server)
client.reply('315 {} {} :End of WHO list', client.nick, target)
@staticmethod
def whois(client, *args):
if not args:
client.err_nonicknamegiven()
return
elif len(args) == 1:
target = args[0]
else:
target = args[1]
if server.has_nick(target):
server.get_nick(target).on_whois(client)
else:
client.err_nosuchnick(target)
return
client.reply('318 {} {} :End of WHOIS list', client.nick, target)
@classmethod
def notice_or_privmsg(cls, client, command, *args):
if not args:
client.err_norecipient(command)
return
if len(args) == 1:
client.err_notexttosend()
return
target = args[0]
msg = args[1]
# on name conflict, prefer to resolve user first
if server.has_nick(target):
user = server.get_nick(target)
if isinstance(user, Client):
user.write(':{} PRIVMSG {} :{}'.format(client.prefix, user.nick, msg))
else:
user.on_notice_or_privmsg(client, command, msg)
# IRC channel or special chatroom
elif client.is_in_channel(target):
server.get_channel(target).on_notice_or_privmsg(
client, command, msg)
elif command == 'PRIVMSG':
client.err_nosuchnick(target)
@staticmethod
@registered(6)
def user(client, user, mode, _, realname):
if len(options.irc_password) and not client.authenticated:
client.err_passwdmismatch('USER')
return
client.user = user
client.realname = realname
client.register()
### Channels: StandardChannel, StatusChannel, SpecialChannel
class Channel:
def __init__(self, name):
self.name = name
self.peer_type = ''
self.topic = ''
self.mode = 'n'
self.members = {}
def __repr__(self):
return repr({k: v for k, v in self.__dict__.items()
if k in ('name', 'topic')})
@property
def prefix(self):
return self.name
def log(self, source, fmt, *args):
info('%s %s '+fmt, self.name, source.nick, *args)
def multicast_group(self, source):
return self.members.keys()
def n_members(self, client):
return len(self.members)
def event(self, source, command, fmt, *args, include_source=True):
line = fmt.format(*args) if args else fmt
for client in self.multicast_group(source):
if client != source or include_source:
client.write(':{} {} {}'.format(source.prefix, command, line))
def dehalfop_event(self, user):
self.event(self, 'MODE', '{} -h {}', self.name, user.nick)
def deop_event(self, user):
self.event(self, 'MODE', '{} -o {}', self.name, user.nick)
def devoice_event(self, user):
self.event(self, 'MODE', '{} -v {}', self.name, user.nick)
def halfop_event(self, user):
self.event(self, 'MODE', '{} +h {}', self.name, user.nick)
def nick_event(self, user, new):
self.event(user, 'NICK', new)
def join_event(self, user):
self.event(user, 'JOIN', self.name)
def kick_event(self, kicker, channel, kicked, reason=None):
if reason:
self.event(kicker, 'KICK', '{} {}: {}', channel.name, kicked.nick, reason)
else:
self.event(kicker, 'KICK', '{} {}', channel.name, kicked.nick)
self.log(kicker, 'kicked %s', kicked.prefix)
def op_event(self, user):
self.event(self, 'MODE', '{} +o {}', self.name, user.nick)
def part_event(self, user, partmsg):
if partmsg:
self.event(user, 'PART', '{} :{}', self.name, partmsg)
else:
self.event(user, 'PART', self.name)
def voice_event(self, user):
self.event(user, 'MODE', '{} +v {}', self.name, user.nick)
def on_invite(self, client, nick):
# TODO
client.err_chanoprivsneeded(self.name)
# subclasses should return True if succeeded to join
def on_join(self, client):
client.enter(self)
self.join_event(client)
self.on_topic(client)
self.on_names(client)
def on_kick(self, client, nick, reason):
client.err_chanoprivsneeded(self.name)
def on_mode(self, client):
client.rpl_channelmodeis(self.name, self.mode)
def on_names(self, client):
self.on_names_impl(client, self.members.items())
def on_names_impl(self, client, items):
names = []
for u, mode in items:
nick = u.nick
prefix = ''
while 1:
if 'o' in mode:
prefix += '@'
if 'multi-prefix' not in client.capabilities:
break
if 'h' in mode:
prefix += '%'
if 'multi-prefix' not in client.capabilities:
break
if 'v' in mode:
prefix += '+'
if 'multi-prefix' not in client.capabilities:
break
break
names.append(prefix+nick)
buf = ''
bytelen = 0
maxlen = 510-1-len(server.name)-5-len(client.nick.encode())-3-len(self.name.encode())-2
for name in names:
if bytelen+1+len(name.encode()) > maxlen:
client.reply('353 {} = {} :{}', client.nick, self.name, buf)
buf = ''
bytelen = 0
if buf:
buf += ' '
bytelen += 1
buf += name
bytelen += len(name.encode())
if buf:
client.reply('353 {} = {} :{}', client.nick, self.name, buf)
client.reply('366 {} {} :End of NAMES list', client.nick, self.name)
def on_topic(self, client, new=None):
if new:
client.err_nochanmodes(self.name)
else:
if self.topic:
client.reply('332 {} {} :{}', client.nick, self.name, self.topic)
else:
client.reply('331 {} {} :No topic is set', client.nick, self.name)
class StandardChannel(Channel):
def __init__(self, name):
super().__init__(name)
def on_notice_or_privmsg(self, client, command, msg):
self.event(client, command, '{} :{}', self.name, msg, include_source=False)
def on_join(self, client):
if client in self.members:
return False
# first user becomes op
self.members[client] = 'o' if not self.members else ''
super().on_join(client)
return True
def on_kick(self, client, nick, reason):
if 'o' not in self.members[client]:
client.err_chanoprivsneeded(self.name)
elif not server.has_nick(nick):
client.err_usernotinchannel(nick, self.name)
else:
user = server.get_nick(nick)
if user not in self.members:
client.err_usernotinchannel(nick, self.name)
elif client != user:
self.kick_event(client, self, user, reason)
self.on_part(user, None)
def on_part(self, client, msg=None):
if client not in self.members:
client.err_notonchannel(self.name)
return False
if msg: # explicit PART, not disconnection
self.part_event(client, msg)
if len(self.members) == 1:
server.remove_channel(self.name)
elif 'o' in self.members.pop(client):
user = next(iter(self.members))
self.members[user] += 'o'
self.op_event(user)
client.leave(self)
return True
def on_topic(self, client, new=None):
if new:
self.log(client, 'set topic %r', new)
self.topic = new
self.event(client, 'TOPIC', '{} :{}', self.name, new)
else:
super().on_topic(client, new)
def on_who(self, client):
for member in self.members:
member.on_who_member(client, self)
# A special channel where each client can only see himself
class StatusChannel(Channel):
instance = None
def __init__(self):
super().__init__('+telegram')