-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
3635 lines (3140 loc) · 141 KB
/
bot.py
File metadata and controls
3635 lines (3140 loc) · 141 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 python3
import json
import base64
import argparse
import atexit
import getpass
import hashlib
import hmac
import math
import os
import queue
import random
import re
import socket
import ssl
import subprocess
import sys
import signal
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from collections import deque
from dataclasses import dataclass
from html import unescape
from html.parser import HTMLParser
from pathlib import Path
from typing import Iterable
from urllib.error import HTTPError, URLError
from urllib.parse import quote, quote_plus, urlparse
from urllib.request import Request, urlopen
from plugin_system import MessageContext, PluginManager
try:
from version_info import version_line
except ModuleNotFoundError:
_REPOSITORY_URL = "https://github.com/WarPigs1602/ircbot-python"
def _detect_version_fallback() -> str:
repo_root = Path(__file__).resolve().parent
try:
branch = subprocess.check_output(
["git", "-C", str(repo_root), "rev-parse", "--abbrev-ref", "HEAD"],
text=True,
stderr=subprocess.DEVNULL,
).strip()
commit = subprocess.check_output(
["git", "-C", str(repo_root), "rev-parse", "--short", "HEAD"],
text=True,
stderr=subprocess.DEVNULL,
).strip()
except (OSError, subprocess.SubprocessError):
return "unbekannt"
if branch and commit:
return f"{branch}@{commit}"
if commit:
return commit
return "unbekannt"
def version_line() -> str:
return f"Python IRC Bot {_detect_version_fallback()} | GitHub: {_REPOSITORY_URL}"
try:
import pymysql
except ImportError:
pymysql = None
URL_PATTERN = re.compile(r'https?://[^\s<>"]+', re.IGNORECASE)
SPAM_WORDS = (
"casino",
"viagra",
"porn",
"xxx",
"sex",
"adult",
"pharmacy",
"loan",
"crypto",
"bitcoin",
"bet",
"bonus",
"click",
"free money",
"win money",
)
SPAM_HOSTS = (
"bit.ly",
"tinyurl.com",
"t.co",
"goo.gl",
"is.gd",
"cutt.ly",
"rebrand.ly",
)
DANGEROUS_CONTENT_TYPES = frozenset({
# Generic binaries
"application/octet-stream",
# Windows executables / installers
"application/x-msdownload",
"application/x-ms-dos-executable",
"application/vnd.microsoft.portable-executable",
"application/x-executable",
"application/x-msi",
"application/x-msdos-program",
# Scripts
"application/x-sh",
"application/x-csh",
"application/x-bash",
"application/x-perl",
"application/x-python-code",
"text/x-sh",
"text/x-bash",
"text/x-perl",
"text/x-python",
"text/x-ruby",
"application/x-ruby",
"application/x-bat",
"application/x-powershell",
"text/x-powershell",
# Archives / compressed
"application/zip",
"application/x-zip-compressed",
"application/x-rar-compressed",
"application/vnd.rar",
"application/x-7z-compressed",
"application/x-tar",
"application/x-gzip",
"application/x-bzip2",
"application/x-xz",
"application/zstd",
"application/x-lzma",
# JVM / mobile
"application/java-archive",
"application/x-java-archive",
"application/vnd.android.package-archive",
# macOS
"application/x-apple-diskimage",
"application/x-macos-pkg",
# Linux packages
"application/x-deb",
"application/x-rpm",
# Office macros / legacy formats
"application/vnd.ms-excel.sheet.macroEnabled.12",
"application/vnd.ms-word.document.macroEnabled.12",
"application/vnd.ms-powerpoint.presentation.macroEnabled.12",
"application/vnd.ms-office",
# Flash (legacy, still seen in the wild)
"application/x-shockwave-flash",
# HTA / CHM
"application/x-ms-application",
"application/x-ms-xbap",
"application/vnd.ms-htmlhelp",
})
DEFAULT_PREFIX_MODES = {
"q": "~",
"a": "&",
"o": "@",
"h": "%",
"v": "+",
}
ADMIN_SESSION_TTL_SECONDS = 1800
ROLE_FLAG_COLUMNS = {
"admin": "is_admin",
"raw": "can_raw",
}
INVALID_HOSTMASK_MESSAGE = "Ungültige Hostmask."
INVALID_CHANNEL_MESSAGE = "Ungültiger Channel."
ROLE_EXISTS_QUERY = "SELECT 1 FROM bot_admin_roles WHERE network = %s AND role_name = %s LIMIT 1"
RSS_ANNOUNCE_CHANNELS_TABLE_SQL = """
CREATE TABLE IF NOT EXISTS bot_rss_announce_channels (
network VARCHAR(255) NOT NULL,
channel VARCHAR(128) NOT NULL,
updated_at VARCHAR(32) NOT NULL,
PRIMARY KEY (network, channel),
KEY idx_bot_rss_announce_channels_lookup (network, updated_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
"""
CONFIG_FILE_NAME = "config.json"
CONFIG_MISSING_MESSAGE = "config.json fehlt / is missing. Kopiere config.example.json zu config.json und passe die Werte an."
SASL_RESULT_COMMANDS = frozenset({"900", "902", "903", "904", "905", "906", "907", "908"})
STARTUP_COMPLETE_COMMANDS = frozenset({"376", "422"})
CHANNEL_JOIN_FAILURE_COMMANDS = frozenset({"403", "405", "471", "473", "474", "475", "476", "477", "489"})
@dataclass
class BotConfig:
server: str
port: int
use_tls: bool
nick: str
username: str
realname: str
channels: list[str]
bind_ip: str = ""
password: str = ""
command_prefix: str = "!"
mysql_host: str = "127.0.0.1"
mysql_port: int = 3306
mysql_user: str = "root"
mysql_password: str = ""
mysql_database: str = "nullbot"
weather_default_location: str = ""
weather_appid: str = ""
youtube_api_key: str = ""
perform: list[str] | None = None
sasl_enabled: bool = False
sasl_username: str = ""
sasl_password: str = ""
sasl_authzid: str = ""
language: str = "de"
flood_protection_enabled: bool = True
flood_burst: int = 4
flood_window_seconds: float = 2.0
flood_min_interval_ms: int = 2000
nick_protection_enabled: bool = False
nick_protection_nick: str = ""
nick_reclaim_interval_seconds: int = 60
nickserv_password: str = ""
nickserv_identify_command: str = "PRIVMSG NickServ :IDENTIFY {password}"
oidentd_conf: str = ""
network_key: str = ""
reconnect_delay_seconds: int = 30
raw_chat_logging_enabled: bool = False
url_timeout_seconds: float = 3.0
url_sniff_max_bytes: int = 65536
url_max_content_length_bytes: int = 2097152
rss_feeds: dict[str, str] | None = None
rss_announce_channel: str = ""
enabled_plugins: list[str] | None = None
disabled_plugins: list[str] | None = None
mondgesicht_url_enabled: bool = False
mondgesicht_url: str = ""
@staticmethod
def _from_raw(raw: dict[str, object]) -> "BotConfig":
server = str(raw["server"])
port = int(raw.get("port", 6697))
nick = str(raw["nick"])
perform_raw = raw.get("perform", [])
if isinstance(perform_raw, str):
perform_list = [perform_raw]
elif isinstance(perform_raw, list):
perform_list = [str(item) for item in perform_raw]
else:
perform_list = []
language_raw = str(raw.get("language", "de")).strip().lower()
language = language_raw if language_raw in {"de", "en"} else "de"
def _parse_string_list(value: object) -> list[str]:
if isinstance(value, str):
return [value]
if isinstance(value, list):
return [str(item) for item in value]
return []
def _parse_string_dict(value: object) -> dict[str, str]:
if not isinstance(value, dict):
return {}
parsed: dict[str, str] = {}
for key, item in value.items():
normalized_key = str(key).strip()
normalized_value = str(item).strip()
if normalized_key and normalized_value:
parsed[normalized_key] = normalized_value
return parsed
configured_network_key = str(raw.get("network_key", "")).strip()
network_key = configured_network_key or f"{server}:{port}:{nick}".lower()
return BotConfig(
server=server,
port=port,
use_tls=bool(raw.get("use_tls", True)),
nick=nick,
bind_ip=str(raw.get("bind_ip", "")).strip(),
username=str(raw.get("username", nick)),
realname=str(raw.get("realname", "Python IRC Bot")),
channels=list(raw.get("channels", [])),
password=str(raw.get("password", "")),
command_prefix=str(raw.get("command_prefix", "!")),
mysql_host=str(raw.get("mysql_host", "127.0.0.1")),
mysql_port=int(raw.get("mysql_port", 3306)),
mysql_user=str(raw.get("mysql_user", "root")),
mysql_password=str(raw.get("mysql_password", "")),
mysql_database=str(raw.get("mysql_database", "nullbot")),
weather_default_location=str(raw.get("weather_default_location", "")),
weather_appid=str(raw.get("weather_appid", "")).strip(),
youtube_api_key=str(raw.get("youtube_api_key", "")),
perform=perform_list,
sasl_enabled=bool(raw.get("sasl_enabled", False)),
sasl_username=str(raw.get("sasl_username", "")),
sasl_password=str(raw.get("sasl_password", "")),
sasl_authzid=str(raw.get("sasl_authzid", "")),
language=language,
flood_protection_enabled=bool(raw.get("flood_protection_enabled", True)),
flood_burst=max(1, int(raw.get("flood_burst", 4))),
flood_window_seconds=max(0.1, float(raw.get("flood_window_seconds", 2.0))),
flood_min_interval_ms=max(0, int(raw.get("flood_min_interval_ms", 2000))),
nick_protection_enabled=bool(raw.get("nick_protection_enabled", False)),
nick_protection_nick=str(raw.get("nick_protection_nick", nick)).strip(),
nick_reclaim_interval_seconds=max(5, int(raw.get("nick_reclaim_interval_seconds", 60))),
nickserv_password=str(raw.get("nickserv_password", "")),
nickserv_identify_command=str(raw.get("nickserv_identify_command", "PRIVMSG NickServ :IDENTIFY {password}")),
oidentd_conf=str(raw.get("oidentd_conf", "")).strip(),
network_key=network_key,
reconnect_delay_seconds=max(1, int(raw.get("reconnect_delay_seconds", 30))),
raw_chat_logging_enabled=bool(raw.get("raw_chat_logging_enabled", False)),
url_timeout_seconds=max(0.5, float(raw.get("url_timeout_seconds", 3.0))),
url_sniff_max_bytes=max(1024, int(raw.get("url_sniff_max_bytes", 65536))),
url_max_content_length_bytes=max(65536, int(raw.get("url_max_content_length_bytes", 2097152))),
rss_feeds=_parse_string_dict(raw.get("rss_feeds", {})),
rss_announce_channel=str(raw.get("rss_announce_channel", "")).strip(),
enabled_plugins=_parse_string_list(raw.get("enabled_plugins", [])),
disabled_plugins=_parse_string_list(raw.get("disabled_plugins", [])),
mondgesicht_url_enabled=bool(raw.get("mondgesicht_url_enabled", False)),
mondgesicht_url=str(raw.get("mondgesicht_url", "")).strip(),
)
@staticmethod
def load_from_file(path: Path) -> list["BotConfig"]:
raw = json.loads(path.read_text(encoding="utf-8"))
networks_raw = raw.get("networks")
if not isinstance(networks_raw, list) or not networks_raw:
raise ValueError("config.json muss ein nicht-leeres 'networks' Array enthalten.")
base = {k: v for k, v in raw.items() if k != "networks"}
configs: list[BotConfig] = []
for index, network_raw in enumerate(networks_raw, start=1):
if not isinstance(network_raw, dict):
raise ValueError(f"networks[{index - 1}] muss ein Objekt sein.")
if not bool(network_raw.get("enabled", True)):
continue
merged = dict(base)
merged.update(network_raw)
try:
configs.append(BotConfig._from_raw(merged))
except KeyError as exc:
missing_key = exc.args[0]
raise ValueError(f"networks[{index - 1}] fehlt Pflichtfeld: {missing_key}") from exc
if not configs:
raise ValueError("Kein aktives Netzwerk in 'networks' gefunden (enabled=true).")
seen_keys: set[str] = set()
for config in configs:
if config.network_key in seen_keys:
raise ValueError(f"Doppelter network_key gefunden: {config.network_key}")
seen_keys.add(config.network_key)
return configs
def display_name(self) -> str:
return f"{self.server}:{self.port}"
class IRCBot:
def __init__(self, config: BotConfig) -> None:
self.config = config
self.sock: socket.socket | None = None
self.file = None
self.seen_sniffed_urls: set[str] = set()
self.channel_modes: dict[str, set[str]] = {}
self.user_modes: set[str] = set()
self.channel_members: dict[str, dict[str, str]] = {}
self._member_mode_retry_at: dict[tuple[str, str, str], float] = {}
self.db_initialized = False
self.cap_negotiation_active = False
self.sasl_payload_sent = False
self._flood_timestamps: deque[float] = deque()
self._last_chat_send_at: float = 0.0
self.pending_lag_checks: dict[str, tuple[int, str]] = {}
self.initial_nick = self.config.nick
self.current_nick = self.config.nick
self.preferred_nick = self.config.nick_protection_nick or self.config.nick
self.fallback_nick = (f"{self.initial_nick}_" if self.initial_nick else "_")[:15]
self.last_nick_reclaim_attempt_at: float = 0.0
self.nickserv_identify_sent = False
self.startup_actions_completed = False
self.public_trigger_activation_at: float = 0.0
self.server_prefix_modes: dict[str, str] = dict(DEFAULT_PREFIX_MODES)
self.userhost_in_names_enabled = False
self.active_capabilities: set[str] = set()
self._admin_sessions: dict[str, dict[str, object]] = {}
self._admin_bootstrap_warned = False
self._send_lock = threading.RLock()
self._who_queue: queue.Queue[str] = queue.Queue()
self._who_worker = threading.Thread(target=self._who_queue_worker, daemon=True, name="who-worker")
self._who_worker.start()
self._url_executor = ThreadPoolExecutor(max_workers=2, thread_name_prefix="urlsniff")
self._runtime_stop_event = threading.Event()
self._plugin_tick_thread: threading.Thread | None = None
self._url_service = None
self.spam_words = SPAM_WORDS
self.spam_hosts = SPAM_HOSTS
self.dangerous_content_types = DANGEROUS_CONTENT_TYPES
self.plugin_manager = PluginManager(self, Path(__file__).resolve().parent / "plugins")
def _get_url_service(self):
if self._url_service is None:
from plugins.url_service import URLService
self._url_service = URLService()
return self._url_service
def tr(self, key: str, **kwargs) -> str:
language = self.config.language if self.config.language in {"de", "en"} else "de"
core_messages = {
"de": {
"not_connected": "Nicht verbunden",
"sasl_failed": "SASL-Authentifizierung fehlgeschlagen.",
"nick_taken": "Nickname {old_nick} ist belegt, verwende {new_nick}",
"channel_not_joinable": "Channel nicht joinbar, entferne aus Liste: {channel}",
"db_setup_skip": "Hinweis: Konnte MySQL-Server nicht erreichen, DB-Setup wird übersprungen.",
"db_create_failed": "Hinweis: DB-Erstellung fehlgeschlagen: {error}",
"db_connect_failed": "Hinweis: Konnte keine Verbindung zur Bot-Datenbank herstellen.",
"db_table_setup_failed": "Hinweis: Tabellen-Setup fehlgeschlagen: {error}",
"admin_bootstrap_missing": "Kein Admin für Netzwerk {network} konfiguriert. Starte den Bot einmal im Vordergrund und lege einen Admin an.",
"admin_bootstrap_prompt": "Erststart für {network}: initialen Admin anlegen.",
"admin_bootstrap_created": "Initialer Admin {mask} wurde für Netzwerk {network} angelegt.",
"admin_bootstrap_skipped": "Admin-Bootstrap übersprungen. Ohne Admin sind keine Verwaltungsbefehle verfügbar.",
"weather_appid_missing": "Weather-App-ID fehlt. Bitte weather_appid in der Konfiguration setzen.",
"config_missing": "config.json fehlt. Kopiere config.example.json zu config.json und passe die Werte an.",
"connecting": "Verbinde zu {server}:{port} (TLS={tls}) ...",
"connection_closed": "Verbindung beendet.",
"network_error": "Netzwerkfehler: {error}",
"shutting_down": "Beende Bot.",
"reconnect_in": "Reconnect in {seconds} Sekunden ...",
},
"en": {
"not_connected": "Not connected",
"sasl_failed": "SASL authentication failed.",
"nick_taken": "Nickname {old_nick} is taken, using {new_nick}",
"channel_not_joinable": "Channel not joinable, removing from list: {channel}",
"db_setup_skip": "Notice: Could not reach MySQL server, skipping DB setup.",
"db_create_failed": "Notice: DB creation failed: {error}",
"db_connect_failed": "Notice: Could not connect to bot database.",
"db_table_setup_failed": "Notice: Table setup failed: {error}",
"admin_bootstrap_missing": "No admin is configured for network {network}. Start the bot once in the foreground and create an admin.",
"admin_bootstrap_prompt": "First run for {network}: create the initial admin.",
"admin_bootstrap_created": "Initial admin {mask} was created for network {network}.",
"admin_bootstrap_skipped": "Admin bootstrap skipped. No administrative commands will be available until an admin is created.",
"weather_appid_missing": "Weather app ID is missing. Please set weather_appid in the configuration.",
"config_missing": "config.json is missing. Copy config.example.json to config.json and adjust values.",
"connecting": "Connecting to {server}:{port} (TLS={tls}) ...",
"connection_closed": "Connection closed.",
"network_error": "Network error: {error}",
"shutting_down": "Stopping bot.",
"reconnect_in": "Reconnect in {seconds} seconds ...",
},
}
plugin_manager = getattr(self, "plugin_manager", None)
plugin_template = None if plugin_manager is None else plugin_manager.translation(key, language)
if plugin_template is None and language != "de" and plugin_manager is not None:
plugin_template = plugin_manager.translation(key, "de")
template = plugin_template
if template is None:
template = core_messages.get(language, core_messages["de"]).get(
key,
core_messages["de"].get(key, key),
)
return template.format(**kwargs)
def connect(self) -> None:
source_address = (self.config.bind_ip, 0) if self.config.bind_ip else None
base_sock = socket.create_connection((self.config.server, self.config.port), timeout=20, source_address=source_address)
base_sock.settimeout(None)
if self.config.use_tls:
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.check_hostname = True
ctx.verify_mode = ssl.CERT_REQUIRED
ctx.load_default_certs()
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
self.sock = ctx.wrap_socket(base_sock, server_hostname=self.config.server)
else:
self.sock = base_sock
self.file = self.sock.makefile("r", encoding="utf-8", errors="replace", newline="\r\n")
if self.should_use_sasl():
self.cap_negotiation_active = True
self.send_raw("CAP LS 302")
if self.config.password:
self.send_raw(f"PASS {self.config.password}")
self.send_raw(f"NICK {self.current_nick}")
self.send_raw(f"USER {self.config.username} 0 * :{self.config.realname}")
self.last_nick_reclaim_attempt_at = 0.0
self.nickserv_identify_sent = False
def close(self) -> None:
self._runtime_stop_event.set()
if self._plugin_tick_thread is not None and self._plugin_tick_thread.is_alive():
self._plugin_tick_thread.join(timeout=2)
self._plugin_tick_thread = None
if self._url_executor is not None:
self._url_executor.shutdown(wait=False, cancel_futures=True)
self._url_executor = None
try:
if self.file:
self.file.close()
finally:
self.file = None
try:
if self.sock:
self.sock.close()
finally:
self.sock = None
def start_plugin_tick_loop(self) -> None:
if self._plugin_tick_thread is not None and self._plugin_tick_thread.is_alive():
return
self._runtime_stop_event.clear()
self._plugin_tick_thread = threading.Thread(
target=self.run_plugin_tick_loop,
name=f"plugin-tick-{self.config.display_name()}",
daemon=True,
)
self._plugin_tick_thread.start()
def run_plugin_tick_loop(self) -> None:
while not self._runtime_stop_event.wait(5.0):
try:
self.plugin_manager.handle_tick()
except Exception as exc:
print(f"[{self.config.display_name()}] Plugin-Tick-Fehler: {exc}")
def setup_oidentd_conf(self) -> None:
if not self.config.oidentd_conf:
return
try:
oidentd_path = Path(self.config.oidentd_conf).expanduser().resolve()
oidentd_path.parent.mkdir(parents=True, exist_ok=True)
content = f"""global {{
reply "{self.config.username}"
}}
"""
oidentd_path.write_text(content, encoding="utf-8")
print(f"oidentd.conf created: {oidentd_path}")
except Exception as exc:
print(f"Failed to create oidentd.conf: {exc}")
def send_raw(self, line: str) -> None:
with self._send_lock:
if not self.sock:
raise RuntimeError(self.tr("not_connected"))
self.cache_own_user_mode_command(line)
payload = (line + "\r\n").encode("utf-8")
self.sock.sendall(payload)
print(f">>> {line}")
self.log_chat_raw_line(line)
@staticmethod
def sanitize_network_key_for_filename(network_key: str) -> str:
sanitized = re.sub(r'[^A-Za-z0-9._-]+', "_", network_key.strip())
return sanitized or "network"
def chat_log_path(self) -> Path:
filename = f"chat-{self.sanitize_network_key_for_filename(self.config.network_key)}.log"
return Path("log") / filename
def log_chat_raw_line(self, line: str) -> None:
if not self.config.raw_chat_logging_enabled:
return
try:
timestamp_ms = int(time.time() * 1000)
log_path = self.chat_log_path()
log_path.parent.mkdir(parents=True, exist_ok=True)
log_path.open("a", encoding="utf-8").write(f"{timestamp_ms} {line}\n")
except OSError:
pass
def send_privmsg(self, target: str, message: str) -> None:
with self._send_lock:
self.apply_flood_protection()
self.send_raw(f"PRIVMSG {target} :{message}")
def send_notice(self, target: str, message: str) -> None:
with self._send_lock:
self.apply_flood_protection()
self.send_raw(f"NOTICE {target} :{message}")
def send_action(self, target: str, message: str) -> None:
with self._send_lock:
self.apply_flood_protection()
self.send_raw(f"PRIVMSG {target} :\x01ACTION {message}\x01")
def schedule_url_sniff(self, message: str, channel: str, source_nick: str) -> None:
if not URL_PATTERN.search(message):
return
if self._url_executor is None:
return
self._url_executor.submit(self._safe_sniff_urls_in_message, message, channel, source_nick)
def _safe_sniff_urls_in_message(self, message: str, channel: str, source_nick: str) -> None:
try:
self.sniff_urls_in_message(message, channel, source_nick)
except Exception as exc:
print(f"URL sniff worker failed: {exc}")
def apply_flood_protection(self) -> None:
if not self.config.flood_protection_enabled:
return
if "B" in self.user_modes:
return
now = time.monotonic()
# Ensure a minimum delay between chat messages.
# This runs inside the shared send lock, so threaded senders are serialized too.
min_interval = self.config.flood_min_interval_ms / 1000.0
if min_interval > 0:
elapsed = now - self._last_chat_send_at
if elapsed < min_interval:
time.sleep(min_interval - elapsed)
now = time.monotonic()
# Enforce a burst/window rate limit.
window = self.config.flood_window_seconds
while self._flood_timestamps and (now - self._flood_timestamps[0]) > window:
self._flood_timestamps.popleft()
if len(self._flood_timestamps) >= self.config.flood_burst:
sleep_for = window - (now - self._flood_timestamps[0])
if sleep_for > 0:
time.sleep(sleep_for)
now = time.monotonic()
while self._flood_timestamps and (now - self._flood_timestamps[0]) > window:
self._flood_timestamps.popleft()
self._flood_timestamps.append(now)
self._last_chat_send_at = now
def join_channels(self, channels: Iterable[str]) -> None:
normalized = [ch.strip() for ch in channels if ch and ch.strip()]
if not normalized:
return
self.send_raw(f"JOIN {','.join(normalized)}")
def request_channel_modes(self, channel: str) -> None:
# Intentionally disabled: no explicit MODE/TOPIC polling on join/startup.
return
def request_user_modes(self) -> None:
if self.current_nick:
self.send_raw(f"MODE {self.current_nick}")
def request_channel_members(self, channel: str) -> None:
normalized_channel = channel.strip()
if normalized_channel:
self.channel_members[self.normalize_channel_name(normalized_channel)] = {}
self.send_raw(f"NAMES {normalized_channel}")
def _who_queue_worker(self) -> None:
while True:
channel = self._who_queue.get()
if channel is None:
break
try:
self.send_raw(f"WHO {channel}")
except Exception:
pass
time.sleep(2.0)
def request_channel_who(self, channel: str) -> None:
if self.userhost_in_names_enabled:
return
normalized_channel = channel.strip()
if normalized_channel:
self._who_queue.put(normalized_channel)
@staticmethod
def parse_prefix_token(value: str) -> dict[str, str] | None:
token = value[7:] if value.upper().startswith("PREFIX=") else value
if not token.startswith("(") or ")" not in token:
return None
modes_part, prefixes_part = token[1:].split(")", 1)
if not modes_part or not prefixes_part or len(modes_part) != len(prefixes_part):
return None
return dict(zip(modes_part, prefixes_part))
def handle_isupport_message(self, params: list[str]) -> None:
if len(params) < 2:
return
for token in params[1:]:
if token.startswith(":"):
break
parsed = self.parse_prefix_token(token)
if parsed is not None:
self.server_prefix_modes = parsed
break
@staticmethod
def split_hostmask(prefix: str) -> tuple[str, str, str]:
nick = prefix
ident = ""
host = ""
if "!" in prefix:
nick, remainder = prefix.split("!", 1)
if "@" in remainder:
ident, host = remainder.split("@", 1)
else:
ident = remainder
elif "@" in prefix:
ident, host = prefix.split("@", 1)
return nick, ident, host
@staticmethod
def normalize_user_mask(mask: str) -> str | None:
raw = mask.strip()
if raw.count("@") != 1:
return None
ident, host = raw.split("@", 1)
ident = ident.strip().lower()
host = host.strip().lower()
if not ident or not host:
return None
return f"{ident}@{host}"
@staticmethod
def normalize_role_name(role_name: str) -> str | None:
role = role_name.strip().lower()
if not role or not re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,31}", role):
return None
return role
@staticmethod
def normalize_channel_name(channel: str) -> str:
return channel.strip().lower()
def strip_channel_member_prefixes(self, nick: str) -> str:
cleaned = nick.strip()
prefixes = set(self.server_prefix_modes.values())
while cleaned and cleaned[0] in prefixes:
cleaned = cleaned[1:]
return cleaned
def normalize_channel_member_nick(self, nick: str) -> str:
cleaned = self.strip_channel_member_prefixes(nick)
member_nick, _, _ = self.split_hostmask(cleaned)
return member_nick.strip()
def parse_names_member_hostmask(self, value: str) -> tuple[str, str, str]:
cleaned = self.strip_channel_member_prefixes(value)
nick, ident, host = self.split_hostmask(cleaned)
return nick.strip(), ident.strip(), host.strip()
def add_channel_member(self, channel: str, nick: str) -> None:
normalized_channel = self.normalize_channel_name(channel)
cleaned_nick = self.normalize_channel_member_nick(nick)
if not normalized_channel or not cleaned_nick:
return
self.clear_member_mode_retry(normalized_channel, cleaned_nick)
members = self.channel_members.setdefault(normalized_channel, {})
members[cleaned_nick.lower()] = cleaned_nick
def add_channel_members(self, channel: str, nicks: Iterable[str]) -> None:
for nick in nicks:
self.add_channel_member(channel, nick)
def remove_channel_member(self, channel: str, nick: str) -> None:
normalized_channel = self.normalize_channel_name(channel)
cleaned_nick = self.normalize_channel_member_nick(nick)
if not normalized_channel or not cleaned_nick:
return
self.clear_member_mode_retry(normalized_channel, cleaned_nick)
members = self.channel_members.get(normalized_channel)
if members is not None:
members.pop(cleaned_nick.lower(), None)
def rename_channel_member(self, old_nick: str, new_nick: str) -> None:
cleaned_old_nick = self.normalize_channel_member_nick(old_nick)
cleaned_new_nick = self.normalize_channel_member_nick(new_nick)
if not cleaned_old_nick or not cleaned_new_nick:
return
for channel in tuple(self.channel_members):
self.clear_member_mode_retry(channel, cleaned_old_nick)
lowered_old_nick = cleaned_old_nick.lower()
lowered_new_nick = cleaned_new_nick.lower()
for members in self.channel_members.values():
if lowered_old_nick in members:
members.pop(lowered_old_nick, None)
members[lowered_new_nick] = cleaned_new_nick
def remove_channel_member_from_all(self, nick: str) -> None:
cleaned_nick = self.normalize_channel_member_nick(nick)
if not cleaned_nick:
return
for channel in tuple(self.channel_members):
self.clear_member_mode_retry(channel, cleaned_nick)
lowered_nick = cleaned_nick.lower()
for members in self.channel_members.values():
members.pop(lowered_nick, None)
def get_channel_member_nicks(self, channel: str) -> tuple[str, ...]:
normalized_channel = self.normalize_channel_name(channel)
members = self.channel_members.get(normalized_channel, {})
return tuple(members.values())
def is_nick_in_channel(self, channel: str, nick: str) -> bool:
normalized_channel = self.normalize_channel_name(channel)
cleaned_nick = self.normalize_channel_member_nick(nick)
if not normalized_channel or not cleaned_nick:
return False
members = self.channel_members.get(normalized_channel, {})
return cleaned_nick.lower() in members
def user_mask_from_parts(self, ident: str, host: str) -> str | None:
if not ident or not host:
return None
return self.normalize_user_mask(f"{ident}@{host}")
def normalize_member_mode(self, mode_or_prefix: str) -> str | None:
token = mode_or_prefix.strip()
if len(token) == 2 and token[0] in {"+", "-"}:
token = token[1:]
if len(token) != 1:
return None
if token in self.server_prefix_modes:
return token
for mode, prefix in self.server_prefix_modes.items():
if prefix == token:
return mode
return None
@staticmethod
def parse_mode_snapshot(modes: str) -> set[str]:
active: set[str] = set()
for char in modes:
if char in {"+", "-"}:
continue
active.add(char)
return active
def apply_mode_delta(self, channel: str, mode_changes: str) -> None:
active = set(self.channel_modes.get(channel, set()))
sign = "+"
for char in mode_changes:
if char in {"+", "-"}:
sign = char
continue
if sign == "+":
active.add(char)
else:
active.discard(char)
self.channel_modes[channel] = active
def apply_user_mode_delta(self, mode_changes: str) -> None:
active = set(self.user_modes)
sign = "+"
for char in mode_changes:
if char in {"+", "-"}:
sign = char
continue
if sign == "+":
active.add(char)
else:
active.discard(char)
self.user_modes = active
def cache_own_user_mode_command(self, line: str) -> None:
parts = line.split()
if len(parts) < 3 or parts[0].upper() != "MODE":
return
if parts[1].startswith("#") or parts[1].lower() != self.current_nick.lower():
return
self.apply_user_mode_delta(parts[2])
def apply_member_mode(self, channel: str, nick: str, mode: str) -> None:
if not channel or not nick or not mode:
return
self.send_raw(f"MODE {channel} +{mode} {nick}")
def remove_member_mode(self, channel: str, nick: str, mode: str) -> None:
if not channel or not nick or not mode:
return
self.clear_member_mode_retry(channel, nick, mode)
self.send_raw(f"MODE {channel} -{mode} {nick}")
def clear_member_mode_retry(self, channel: str, nick: str, mode: str = "") -> None:
normalized_channel = self.normalize_channel_name(channel)
cleaned_nick = self.normalize_channel_member_nick(nick).lower()
if not normalized_channel or not cleaned_nick:
return
for key in tuple(self._member_mode_retry_at):
cached_channel, cached_nick, cached_mode = key
if cached_channel != normalized_channel or cached_nick != cleaned_nick:
continue
if mode and cached_mode != mode:
continue
self._member_mode_retry_at.pop(key, None)
def should_retry_member_mode(self, channel: str, nick: str, mode: str, cooldown_seconds: float) -> bool:
normalized_channel = self.normalize_channel_name(channel)
cleaned_nick = self.normalize_channel_member_nick(nick).lower()
if not normalized_channel or not cleaned_nick or not mode:
return False
key = (normalized_channel, cleaned_nick, mode)
now = time.monotonic()
retry_at = self._member_mode_retry_at.get(key, 0.0)
if retry_at > now:
return False
self._member_mode_retry_at[key] = now + max(1.0, cooldown_seconds)
return True
def remember_channel(self, channel: str) -> None:
normalized_channel = channel.strip()
if normalized_channel and normalized_channel not in self.config.channels:
self.config.channels.append(normalized_channel)
if normalized_channel:
self.channel_members.setdefault(self.normalize_channel_name(normalized_channel), {})
self.store_channel_if_missing(normalized_channel)
def forget_channel(self, channel: str) -> None:
normalized_channel = channel.strip()
if not normalized_channel:
return
self.config.channels = [ch for ch in self.config.channels if ch.lower() != normalized_channel.lower()]
self.channel_modes.pop(normalized_channel, None)
self.channel_members.pop(self.normalize_channel_name(normalized_channel), None)
for key in tuple(self._member_mode_retry_at):
if key[0] == self.normalize_channel_name(normalized_channel):
self._member_mode_retry_at.pop(key, None)
self.delete_saved_channel(normalized_channel)
def merge_saved_channels(self) -> None:
for channel in self.load_saved_channels():
if channel and channel not in self.config.channels:
self.config.channels.append(channel)
def should_use_sasl(self) -> bool:
return bool(
self.config.sasl_enabled
and self.config.sasl_username.strip()
and self.config.sasl_password
)
def run_perform_commands(self) -> None:
commands = self.config.perform or []
for raw_command in commands:
command = str(raw_command).strip()
if not command:
continue
resolved = command.replace("{nick}", self.current_nick)
self.send_raw(resolved)
def should_use_nickserv_identify(self) -> bool:
return bool(self.config.nickserv_password and self.config.nickserv_identify_command.strip())
def send_nickserv_identify(self) -> None:
if self.nickserv_identify_sent or not self.should_use_nickserv_identify():
return
command = self.config.nickserv_identify_command.format(
password=self.config.nickserv_password,
nick=self.current_nick,
preferred_nick=self.preferred_nick,
).strip()
if not command:
return
self.send_raw(command)
self.nickserv_identify_sent = True
def complete_startup_actions(self) -> None:
if self.startup_actions_completed:
return
self.run_perform_commands()