Repository navigation
Expand file tree
/
Copy pathbot.py
More file actions
executable file
·1889 lines (1635 loc) · 76 KB
/
Copy pathbot.py
File metadata and controls
executable file
·1889 lines (1635 loc) · 76 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
"""Discord bot for server management and automation with reminder functionality."""
# pylint: disable=line-too-long,trailing-whitespace,cyclic-import
import os
import re
import sys
import asyncio
import hashlib
import logging
from collections import deque
from datetime import datetime, timedelta, timezone
from apscheduler.triggers.interval import IntervalTrigger
from apscheduler.triggers.cron import CronTrigger
import aiohttp
import discord
from discord.ext import commands
import json
import config
from config import (
TOKEN,
PROTECTED_CHANNELS,
MODERATORS_CHANNEL_NAME,
ADULT_ROLE_NAMES,
CHILD_ROLE_NAMES,
UPDATE_CHECK_REPO_URL,
BOT_TIMEZONE,
logger
)
_last_notified_commit = None
def _parse_repo_from_url(url):
"""Extract 'owner/repo' from a GitHub URL."""
url = url.rstrip('/')
parts = url.split('github.com/')
if len(parts) == 2:
return parts[1].removesuffix('.git')
return None
def _get_moderators_channel():
"""Find the moderators channel across all guilds, or None."""
return next(
(ch for g in bot.guilds for ch in g.text_channels
if ch.name == MODERATORS_CHANNEL_NAME), None)
async def _run_cmd(*args):
"""Run a command in the bot directory without blocking the event loop.
Returns (returncode, stdout, stderr) as decoded strings.
"""
proc = await asyncio.create_subprocess_exec(
*args,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=os.path.dirname(os.path.abspath(__file__))
)
stdout, stderr = await proc.communicate()
return proc.returncode, stdout.decode().strip(), stderr.decode().strip()
async def _ci_passed(session, repo_path, sha):
"""Return True if all completed check runs for `sha` succeeded.
Requires at least one check run so an untested commit is never
auto-deployed.
"""
url = f"https://api.github.com/repos/{repo_path}/commits/{sha}/check-runs"
try:
async with session.get(url) as response:
if response.status != 200:
logger.warning("Failed to fetch check runs: HTTP %s", response.status)
return False
runs = (await response.json()).get('check_runs', [])
except (aiohttp.ClientError, KeyError, ValueError) as e:
logger.error("Error fetching check runs: %s", e)
return False
if not runs:
logger.info("No check runs found for %s; skipping auto-update", sha[:8])
return False
return all(
run['status'] == 'completed'
and run['conclusion'] in ('success', 'neutral', 'skipped')
for run in runs
)
def _short_sha(sha):
return sha[:8] if sha else '?'
async def _local_tag_for_commit(sha):
"""Return a git tag pointing at `sha` in the local checkout, or None.
Update detection stays commit-SHA-based (see check_for_updates) —
this only resolves a friendlier label to display, so a missing or
unparsable tag never blocks an update, it just falls back to the
short SHA.
"""
try:
rc, out, _ = await _run_cmd('git', 'tag', '--points-at', sha)
except OSError:
return None
if rc == 0 and out:
return out.splitlines()[0]
return None
async def _remote_tag_for_commit(session, repo_path, sha):
"""Return a git tag pointing at `sha` on the remote, or None."""
url = f"https://api.github.com/repos/{repo_path}/tags"
try:
async with session.get(url) as response:
if response.status != 200:
return None
tags = await response.json()
except (aiohttp.ClientError, KeyError, ValueError, TypeError):
return None
for t in tags:
if t.get('commit', {}).get('sha') == sha:
return t.get('name')
return None
async def _version_label(session, repo_path, sha, *, local):
"""A tag name if `sha` is tagged, else its short SHA."""
tag = (await _local_tag_for_commit(sha) if local
else await _remote_tag_for_commit(session, repo_path, sha))
return tag or _short_sha(sha)
async def _auto_update_and_restart(local_commit, remote_commit, deps_changed,
local_version=None, remote_version=None):
"""Pull the latest code, reinstall deps if needed, and re-exec the bot.
On success this never returns (the process is replaced). Returns an
error string on failure so the caller can notify moderators.
"""
local_version = local_version or _short_sha(local_commit)
remote_version = remote_version or _short_sha(remote_commit)
rc, _, err = await _run_cmd('git', 'pull', '--ff-only')
if rc != 0:
return f"`git pull --ff-only` failed: {err or 'unknown error'}"
if deps_changed:
rc, _, err = await _run_cmd(
sys.executable, '-m', 'pip', 'install', '-r', 'requirements.txt')
if rc != 0:
# Code is already pulled; restarting with missing deps could
# crash-loop, so bail out and ask for a manual fix
return f"`pip install -r requirements.txt` failed: {err or 'unknown error'}"
channel = _get_moderators_channel()
if channel:
try:
await channel.send(
"🤖 **Auto-updating JohnnyBot**\n\n"
f"`{local_version}` → `{remote_version}` — "
"restarting now. Back in a moment!"
)
except (discord.HTTPException, discord.Forbidden) as e:
logger.error("Error sending auto-update notice: %s", e)
logger.info("Auto-update complete (%s -> %s); restarting",
local_version, remote_version)
logging.shutdown()
bot_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'bot.py')
os.execv(sys.executable, [sys.executable, bot_path])
return None # unreachable; satisfies linters
async def check_for_updates():
"""Check for updates from the GitHub repository by comparing commit hashes.
With AUTO_UPDATE_ENABLED, updates whose CI passed and which don't
touch config_example.py are pulled and the bot restarts itself;
everything else falls back to a moderator notification.
"""
global _last_notified_commit
if not config.UPDATE_CHECKING_ENABLED:
return
# Get the current local commit hash (async to avoid blocking event loop)
try:
rc, local_commit, err = await _run_cmd('git', 'rev-parse', 'HEAD')
if rc != 0:
logger.error("Failed to get local git commit hash: %s", err)
return
except OSError as e:
logger.error("Error getting local git commit: %s", e)
return
# Build API URL from repo URL
repo_path = _parse_repo_from_url(UPDATE_CHECK_REPO_URL)
if not repo_path:
logger.error("Could not parse repo from URL: %s", UPDATE_CHECK_REPO_URL)
return
auto_update = bool(getattr(config, 'AUTO_UPDATE_ENABLED', False))
# Get the latest commit hash and check what changed
try:
timeout = aiohttp.ClientTimeout(total=30)
async with aiohttp.ClientSession(timeout=timeout) as session:
# Fetch latest commit
api_url = f"https://api.github.com/repos/{repo_path}/commits/main"
async with session.get(api_url) as response:
if response.status != 200:
logger.error("Failed to fetch remote commit info: HTTP %s", response.status)
return
data = await response.json()
remote_commit = data['sha']
# Skip if up to date or already notified for this commit
if local_commit == remote_commit:
logger.info("Bot is up to date: %s", local_commit[:8])
return
if remote_commit == _last_notified_commit:
logger.info("Already notified for commit %s, skipping", remote_commit[:8])
return
# Check what changed between local and remote
compare_url = f"https://api.github.com/repos/{repo_path}/compare/{local_commit}...{remote_commit}"
changed_files = []
async with session.get(compare_url) as response:
if response.status == 200:
compare_data = await response.json()
changed_files = [f['filename'] for f in compare_data.get('files', [])]
else:
logger.warning("Failed to fetch commit comparison: HTTP %s", response.status)
config_changed = 'config_example.py' in changed_files
# Auto-update only commits that passed CI and don't
# require config changes
ci_ok = False
if auto_update and not config_changed:
ci_ok = await _ci_passed(session, repo_path, remote_commit)
# Tag names are cosmetic only — detection above stays
# commit-SHA-based regardless of whether either side is
# tagged, so an untagged commit (or a fork with no tags at
# all) still updates correctly, just displayed by short SHA.
local_version = await _version_label(session, repo_path, local_commit, local=True)
remote_version = await _version_label(session, repo_path, remote_commit, local=False)
except (aiohttp.ClientError, KeyError, ValueError) as e:
logger.error("Error fetching remote git info: %s", e)
return
logger.info("Update available: local=%s, remote=%s", local_version, remote_version)
if auto_update and not config_changed and ci_ok:
error = await _auto_update_and_restart(
local_commit, remote_commit, 'requirements.txt' in changed_files,
local_version, remote_version)
# Only reached on failure — os.execv never returns
logger.error("Auto-update failed: %s", error)
_last_notified_commit = remote_commit
channel = _get_moderators_channel()
if channel:
try:
await channel.send(
"❌ **Auto-update failed**\n\n"
f"{error}\n\n"
"**Please update manually** from the bot directory "
"on the server.\n\n"
f"Repository: {UPDATE_CHECK_REPO_URL}"
)
except (discord.HTTPException, discord.Forbidden) as e:
logger.error("Error sending auto-update failure notice: %s", e)
return
if auto_update and not config_changed and not ci_ok:
logger.info("Auto-update skipped: CI not green for %s", remote_version)
_last_notified_commit = remote_commit
await send_update_notification(local_version, remote_version, config_changed)
async def send_update_notification(local_version, remote_version, config_changed=False):
"""Send update notification to the moderators channel."""
try:
moderators_channel = _get_moderators_channel()
if not moderators_channel:
logger.error("Moderators channel '%s' not found", MODERATORS_CHANNEL_NAME)
return
if config_changed:
message = (
"⚠️ **Breaking Changes in New Version**\n\n"
f"`config_example.py` has been modified in the latest update.\n"
f"Current version: `{local_version}`\n"
f"Latest version: `{remote_version}`\n\n"
f"**Please update manually** — review the config changes and "
f"update your local `config.py` before pulling.\n\n"
f"Repository: {UPDATE_CHECK_REPO_URL}"
)
else:
message = (
"🤖 **Bot Update Available!**\n\n"
f"A new version of JohnnyBot is available on GitHub.\n"
f"Current version: `{local_version}`\n"
f"Latest version: `{remote_version}`\n\n"
f"**To update:**\n"
f"1. Run `git pull` from the bot directory on the server\n"
f"2. Restart the bot service\n\n"
f"Repository: {UPDATE_CHECK_REPO_URL}"
)
await moderators_channel.send(message)
logger.info("Update notification sent to %s", moderators_channel.name)
except (discord.HTTPException, discord.Forbidden) as e:
logger.error("Error sending update notification: %s", e)
# Version-change announcements
# ---------------------------------------------------------------------------
# Both existing notices fire *before* anything changes — "Update
# Available", and "restarting now" sent immediately before os.execv. So
# nothing ever confirms an update actually landed: if the new version
# fails to boot, the last thing moderators saw was "Back in a moment!",
# and silence looks identical to success. A manual `git pull` + restart
# announces nothing at all. This is the missing half, posted on the first
# start after the running commit changes.
# Kept out of config.py for the same reason as CHAPERONE_MUTES_FILE:
# deployed configs are not tracked by git and would not have the constant
# after a pull.
VERSION_STATE_FILE = getattr(
config, 'VERSION_STATE_FILE',
os.path.join(os.path.dirname(os.path.abspath(__file__)),
'version_state.json'))
# Well under Discord's 2000-character cap, leaving room for the header.
_RELEASE_NOTES_BUDGET = 1500
def _load_version_state():
"""The commit/label recorded on the last start, or None."""
if not os.path.exists(VERSION_STATE_FILE):
return None
try:
with open(VERSION_STATE_FILE, 'r', encoding='utf-8') as f:
state = json.load(f)
return state if isinstance(state, dict) else None
except (OSError, IOError, ValueError, TypeError) as e:
logger.error('Failed to read version state: %s', e)
return None
def _save_version_state(sha, label):
"""Record the running version. Never let this abort startup."""
try:
_atomic_json_write(VERSION_STATE_FILE, {
'commit': sha,
'label': label,
'recorded_at': datetime.now(timezone.utc).isoformat(),
})
except (OSError, IOError, TypeError, ValueError) as e:
logger.error('Failed to save version state: %s', e)
async def _current_version():
"""(sha, label) for the running checkout, or None if git is absent.
Update checking already assumes a git checkout, so a tarball or
container install without one simply opts out rather than erroring.
"""
try:
rc, sha, err = await _run_cmd('git', 'rev-parse', 'HEAD')
except OSError as e:
logger.info('Version announce: git unavailable (%s)', e)
return None
if rc != 0 or not sha:
logger.info('Version announce: could not resolve HEAD (%s)', err)
return None
label = await _local_tag_for_commit(sha) or _short_sha(sha)
return sha, label
async def _is_ancestor(old_sha, new_sha):
"""True if old_sha is an ancestor of new_sha — i.e. a forward move.
Distinguishes an upgrade from a rollback or a diverged checkout, so a
surprise `git checkout` of an older tag reads as what it is instead
of being announced as an update.
"""
try:
rc, _, _ = await _run_cmd(
'git', 'merge-base', '--is-ancestor', old_sha, new_sha)
except OSError:
return True
return rc == 0
# Signed tags carry the signature inside the annotation, so `%(contents)`
# returns it too. This repo signs with SSH, others use PGP/GPG — match
# any of them rather than one, or a wall of base64 gets posted to the
# moderators channel.
_SIGNATURE_RE = re.compile(r'^-----BEGIN [A-Z0-9 ]*SIGNATURE-----',
re.MULTILINE)
def _strip_signature(notes):
"""Drop a trailing signature block from a tag annotation."""
match = _SIGNATURE_RE.search(notes)
return notes[:match.start()].strip() if match else notes
async def _tag_release_notes(label):
"""The annotated tag's message for `label`, or ''.
Deliberately the tag annotation rather than `git log old..new`: a
commit log is noise in a moderators channel — every chore, CI tweak
and doc fix — while the annotation is written by whoever cut the
release and therefore contains the highlights by construction.
Returns '' for a lightweight tag (no message), an untagged commit, or
any git failure. A missing body must never suppress the announcement.
"""
if not label or not label.startswith('v'):
return ''
try:
rc, out, _ = await _run_cmd(
'git', 'for-each-ref', '--format=%(contents)',
f'refs/tags/{label}')
except OSError:
return ''
if rc != 0 or not out.strip():
return ''
notes = _strip_signature(out.strip())
if len(notes) > _RELEASE_NOTES_BUDGET:
notes = notes[:_RELEASE_NOTES_BUDGET].rstrip() + '\n…'
return notes
async def announce_version_change():
"""Post to every guild's moderators channel when the running version
differs from the one recorded on the last start.
Posts to each guild rather than via _get_moderators_channel(), which
returns the first match across all guilds — in a multi-guild
deployment only one server would ever learn the bot changed. The
existing update notices still use that single-channel lookup; that
inconsistency is known and left alone here.
"""
if not getattr(config, 'VERSION_ANNOUNCE_ENABLED', True):
return
current = await _current_version()
if current is None:
return
sha, label = current
previous = _load_version_state()
if previous is None:
# First start after this feature ships, or a fresh install.
# Recording silently avoids a bogus "updated" notice on every
# existing deployment the first time it runs.
await asyncio.to_thread(_save_version_state, sha, label)
logger.info('Version announce: recorded baseline %s', label)
return
if previous.get('commit') == sha:
return # ordinary restart, reconnect, or crash-loop
old_label = previous.get('label') or _short_sha(previous.get('commit'))
forward = await _is_ancestor(previous.get('commit', ''), sha)
header = (f"🤖 **JohnnyBot updated** — `{old_label}` → `{label}`"
if forward else
f"🔄 **JohnnyBot version changed** — `{old_label}` → "
f"`{label}` (rollback or diverged checkout)")
notes = await _tag_release_notes(label)
message = f"{header}\n\n{notes}" if notes else header
sent = 0
for guild in bot.guilds:
channel = discord.utils.get(
guild.text_channels, name=MODERATORS_CHANNEL_NAME)
if channel is None:
# Matches the "not found" logging every other alert path in
# this file does (raid/anti-nuke/spam) — a silent `continue`
# here left this exact bug invisible: the info line below
# fired unconditionally, so a channel-name mismatch looked
# identical to a successful send in the log.
logger.error('Moderators channel "%s" not found in %s',
MODERATORS_CHANNEL_NAME, guild.name)
continue
try:
await channel.send(message)
sent += 1
except (discord.HTTPException, discord.Forbidden) as e:
logger.error('Failed to announce version change in %s: %s',
guild.name, e)
logger.info('Version announce: %s -> %s (delivered to %d guild(s))',
old_label, label, sent)
await asyncio.to_thread(_save_version_state, sha, label)
intents = discord.Intents.default()
intents.message_content = True
intents.guilds = True
intents.members = True
intents.voice_states = True
# Non-privileged; enables on_audit_log_entry_create for anti-nuke
# protection. Already on via Intents.default(), set explicitly for
# clarity alongside the other intents here.
intents.moderation = True
bot = commands.Bot(command_prefix='!', intents=intents)
async def _sync_commands():
"""Synchronize application commands with Discord, with retries."""
max_retries = 3
retry_delay = 5
for attempt in range(max_retries):
try:
pre_sync_commands = bot.tree.get_commands()
if not pre_sync_commands:
logger.error("No commands found in command tree before sync")
raise RuntimeError("No commands found in command tree")
synced = await bot.tree.sync()
logger.info('Synced %d global commands', len(synced))
registered = await bot.tree.fetch_commands()
if not registered:
raise RuntimeError("No commands registered after sync")
logger.info('Successfully registered commands: %s',
[cmd.name for cmd in registered])
return
except Exception as e: # pylint: disable=broad-exception-caught
logger.error('Command sync attempt %d failed: %s',
attempt + 1, e)
if attempt < max_retries - 1:
await asyncio.sleep(retry_delay * (attempt + 1))
continue
raise
@bot.event
async def setup_hook():
"""One-time async startup, run before the gateway connects.
Command sync belongs here rather than in on_ready: on_ready fires
again on every reconnect, which is what the old _ready_ran flag and
the leading asyncio.sleep(5) were working around.
Only the sync moves. Anything needing bot.guilds — the chaperone
sweep — or anything whose jobs call bot.get_channel — the scheduler
registrations — must stay in on_ready, because guild state is not
populated yet at this point.
"""
logger.info('Pre-sync commands: %s',
[cmd.name for cmd in bot.tree.get_commands()])
try:
await _sync_commands()
except (discord.HTTPException, discord.ClientException, RuntimeError,
asyncio.TimeoutError) as e:
logger.error('Final command sync failure: %s', e)
_ready_ran = False
@bot.event
async def on_ready(): # pylint: disable=too-many-statements
"""Post-connect startup: chaperone sweep and scheduler registration.
Still guarded by _ready_ran because on_ready re-fires on reconnect
and these steps are not idempotent-by-accident. Command sync now
happens once in setup_hook().
"""
global _ready_ran
if _ready_ran:
return
_ready_ran = True
if bot.user:
logger.info('Logged in as %s (ID: %s)', bot.user, bot.user.id)
logger.info('Bot initialization complete')
# Lift any chaperone mutes left outstanding by the last shutdown
_load_chaperone_mutes()
try:
await sweep_chaperone_mutes()
except (discord.HTTPException, AttributeError) as e:
logger.error('Chaperone startup sweep failed: %s', e)
try:
from commands import event_feed, register_all_reminder_jobs, register_all_auto_backup_jobs # pylint: disable=import-outside-toplevel,line-too-long
if event_feed:
sched = getattr(event_feed, 'scheduler', None)
if sched and not sched.running:
# Route APScheduler logs to the bot log file so job errors
# are visible. Attach handlers only to the parent logger;
# child loggers propagate up, so attaching to both would
# emit each message twice.
_aplogger = logging.getLogger('apscheduler')
_aplogger.setLevel(logging.INFO)
for _h in logger.handlers:
if _h not in _aplogger.handlers:
_aplogger.addHandler(_h)
sched.start()
# Feed check: Monday 9am Central (pulls next 30 days,
# creates Discord Events) — runs one hour before the
# weekly announce so new events are visible when it fires
if hasattr(event_feed, 'check_feeds_job'):
sched.add_job(
event_feed.check_feeds_job,
trigger=CronTrigger(
day_of_week='mon', hour=9,
minute=0,
timezone=BOT_TIMEZONE),
id='weekly_feed_check',
replace_existing=True
)
logger.info(
'Feed check scheduled: Monday 9am CT')
# Weekly preview: Monday 10am Central
if hasattr(event_feed, 'announce_weekly_events'):
sched.add_job(
event_feed.announce_weekly_events,
trigger=CronTrigger(
day_of_week='mon', hour=10,
minute=0,
timezone=BOT_TIMEZONE),
id='weekly_announce',
replace_existing=True
)
logger.info(
'Weekly announce scheduled: Monday 10am CT')
# Day-of reminder: 10am Central, Tue-Sun. Mondays are
# skipped because the weekly preview fires at the same
# minute and already covers that day's events — running
# both posted every Monday event twice.
if hasattr(event_feed, 'announce_todays_events'):
sched.add_job(
event_feed.announce_todays_events,
trigger=CronTrigger(
day_of_week='tue-sun',
hour=10,
minute=0,
timezone=BOT_TIMEZONE),
id='daily_event_reminder',
replace_existing=True
)
logger.info(
'Day-of reminder scheduled: Tue-Sun 10am CT')
# Daily update checking; the job no-ops when
# UPDATE_CHECKING_ENABLED is off in config.py
sched.add_job(
check_for_updates,
trigger=IntervalTrigger(hours=24),
next_run_time=(
datetime.now() + timedelta(minutes=5))
)
logger.info(
'Update checking scheduled (enabled=%s)',
config.UPDATE_CHECKING_ENABLED)
# Register all persisted reminders as scheduler jobs
register_all_reminder_jobs()
# Register all persisted auto-backup jobs
register_all_auto_backup_jobs()
else:
logger.info('Event feed scheduler already running')
else:
logger.warning('Event feed not available')
except (AttributeError, ImportError, ValueError) as e:
logger.error('Failed to start event feed scheduler: %s', e)
# Last, so a git or network problem here can never delay the
# chaperone sweep or the scheduler above.
try:
await announce_version_change()
except Exception as e: # pylint: disable=broad-exception-caught
logger.error('Version announce failed: %s', e)
async def handle_unsolicited_dm(message):
"""Kick anyone who DMs the bot.
Exempt: moderators, and anyone the bot itself DMed recently — the
/message_dump archive and /log_tail output arrive by DM, so a reply
to one of those is solicited and must not be punished.
"""
author = message.author
if _was_recently_dmed(author.id):
logger.info(
'Ignoring DM from %s (replying to a DM we sent)', author)
return
# A user can share more than one guild with the bot; moderator
# status anywhere exempts them everywhere. Fall back to an API
# fetch when the member cache misses — kicking is irreversible for
# the member, so never decide it on a stale cache.
# Anyone on the internet can DM the bot, and this used to spend one
# fetch_member API call per guild on every such DM — an easy way for
# an outsider to burn the global rate limit.
#
# A cache miss is only trustworthy when the guild is chunked, i.e.
# its member cache is known complete. Before chunking finishes (cold
# start, or a large guild) a miss means nothing, and treating it as
# "not a member" would silently exempt a real member from a kick —
# so those guilds still get an API confirmation. Kicking is
# irreversible; it must never run off a cache that may be stale.
candidates = []
for guild in bot.guilds:
member = guild.get_member(author.id)
if member is not None:
candidates.append((guild, member))
elif not guild.chunked:
candidates.append((guild, None)) # must confirm via the API
if not candidates:
logger.info(
'DM from %s who is not a member of any chunked guild; '
'nothing to kick', author)
return
memberships = []
for guild, member in candidates:
if member is None:
try:
member = await guild.fetch_member(author.id)
except discord.NotFound:
continue
except discord.HTTPException as e:
logger.error(
'Could not fetch %s in %s, skipping kick there: %s',
author, guild.name, e)
continue
memberships.append(member)
# Matches the mod_only command gate (manage_messages permission)
# rather than a role literally named MODERATOR_ROLE_NAME, so DM
# exemption tracks the same authorization as command access.
if any(getattr(getattr(m, 'guild_permissions', None), 'manage_messages', False)
for m in memberships):
logger.info('Ignoring DM from moderator %s', author)
return
if not memberships:
logger.info(
'DM from %s who shares no guild with the bot; nothing to kick',
author)
return
logger.warning('Kicking %s for DMing the bot', author)
for member in memberships:
try:
await member.kick(reason='Sent an unsolicited DM to the bot')
logger.info('Kicked %s from %s for DMing the bot',
member, member.guild.name)
except discord.Forbidden:
logger.error(
'Missing permission to kick %s from %s',
member, member.guild.name)
except discord.HTTPException as e:
logger.error('Failed to kick %s from %s: %s',
member, member.guild.name, e)
continue
moderators_channel = discord.utils.get(
member.guild.text_channels, name=MODERATORS_CHANNEL_NAME)
if not moderators_channel:
continue
try:
await moderators_channel.send(
f"👢 Kicked **{member}** (ID: {member.id}) for DMing the bot.\n"
f"> {message.content[:200] or '[no text content]'}"
)
except (discord.HTTPException, discord.Forbidden) as e:
logger.error('Failed to report DM kick: %s', e)
@bot.event
async def on_message(message):
"""Monitor messages in protected channels and delete non-moderator messages. Also check for autoreply rules."""
if message.author.bot:
return
# DMs have no guild and DMChannel has no .name, so handle them
# before anything that assumes a guild channel.
if message.guild is None:
try:
await handle_unsolicited_dm(message)
except Exception as e: # pylint: disable=broad-exception-caught
logger.error('Error handling DM from %s: %s', message.author, e)
return
# Runs before the autoreply and protected-channel checks below: when
# this deletes the message, there is nothing left to reply to.
try:
if await check_message_spam(message):
return
except Exception as e: # pylint: disable=broad-exception-caught
logger.error('Error checking message for spam: %s', e)
try:
await _check_autoreplies(message)
except (ImportError, AttributeError):
# Commands module may not be fully initialized yet
pass
except Exception as e:
logger.error('Error checking autoreply rules: %s', e)
if getattr(message.channel, 'name', None) in PROTECTED_CHANNELS:
# Matches the mod_only command gate (manage_messages permission)
# rather than a role literally named MODERATOR_ROLE_NAME, so
# protected-channel enforcement tracks the same authorization
# as command access.
is_moderator = getattr(
getattr(message.author, 'guild_permissions', None),
'manage_messages', False)
if not is_moderator:
try:
await message.delete()
logger.info(
'Deleted message from %s in protected channel %s: %s',
message.author.name,
message.channel.name,
message.content[:100] + '...' if len(message.content) > 100 else message.content
)
except discord.HTTPException as e:
logger.error(
'Failed to delete message from %s in %s: %s',
message.author.name,
message.channel.name,
e
)
await bot.process_commands(message)
def get_user_role_type(member):
"""Determine if a user is an adult, child, or neither based on their roles."""
role_names = {role.name for role in getattr(member, 'roles', [])}
if role_names & ADULT_ROLE_NAMES:
return 'adult'
if role_names & CHILD_ROLE_NAMES:
return 'child'
return 'neither'
# Members the chaperone itself muted, so we only ever lift our own
# mutes and never one a moderator applied by hand. Persisted, because
# a restart while someone is muted would otherwise strand them: the
# unmute path skips anyone missing from this set.
# Keyed by (guild_id, user_id), not a bare user id: the same person can
# be in voice in two guilds the bot serves, and a single-guild key meant
# one guild's mute suppressed the other's mute *and* its unmute.
_chaperone_muted = set()
# Voice channels currently in the flagged 1-adult/1-child state.
# Muting a member re-fires on_voice_state_update, so without this the
# same incident alerts the moderators two or three times. Not
# persisted — rebuilt by the startup sweep from live channel state.
_chaperone_flagged = set()
# Kept out of config.py: deployed configs are not tracked by git and
# would not have the constant after a pull.
CHAPERONE_MUTES_FILE = getattr(
config, 'CHAPERONE_MUTES_FILE',
os.path.join(os.path.dirname(os.path.abspath(__file__)),
'chaperone_mutes.json'))
def _load_chaperone_mutes():
"""Restore the set of members this feature muted before a restart."""
if not os.path.exists(CHAPERONE_MUTES_FILE):
return
try:
with open(CHAPERONE_MUTES_FILE, 'r', encoding='utf-8') as f:
raw = json.load(f)
legacy = 0
for entry in raw:
# New format is [guild_id, user_id]; the old one was a bare
# user id. A legacy entry can't name its guild, so it is
# dropped — the startup sweep re-flags anyone still in an
# unsafe channel, and the worst case is a stale mute a
# moderator clears once.
if isinstance(entry, (list, tuple)) and len(entry) == 2:
_chaperone_muted.add((int(entry[0]), int(entry[1])))
else:
legacy += 1
if legacy:
logger.warning(
'Dropped %d chaperone mute(s) in the pre-guild-key '
'format; the startup sweep will re-evaluate', legacy)
logger.info('Loaded %d outstanding chaperone mutes',
len(_chaperone_muted))
except (OSError, IOError, ValueError, TypeError) as e:
logger.error('Failed to load chaperone mutes: %s', e)
def _save_chaperone_mutes():
"""Persist outstanding chaperone mutes so a restart can lift them."""
# Never let a persistence problem abort the mute/unmute it is
# recording — the safety action matters more than the bookkeeping.
try:
_atomic_json_write(
CHAPERONE_MUTES_FILE,
[[int(gid), int(uid)] for gid, uid in _chaperone_muted])
except (OSError, IOError, TypeError, ValueError) as e:
logger.error('Failed to save chaperone mutes: %s', e)
async def sweep_chaperone_mutes():
"""Re-evaluate every populated voice channel at startup.
Rebuilds the flagged-channel set from live state and lifts mutes
left over from before the restart.
"""
if not config.VOICE_CHAPERONE_ENABLED:
return
for guild in bot.guilds:
for channel in guild.voice_channels:
if channel.members:
await check_voice_channel_safety(channel)
if _chaperone_muted:
logger.info(
'%d chaperone mutes still outstanding after startup sweep '
'(members not currently connected to voice)',
len(_chaperone_muted))
def _count_adults_children(channel):
"""Return (adults, children) among the non-bot members of a channel."""
adults = []
children = []
for member in channel.members:
if member.bot:
continue
role_type = get_user_role_type(member)
if role_type == 'adult':
adults.append(member)
elif role_type == 'child':
children.append(member)
return adults, children
async def _unmute_member(member, reason):
"""Lift a chaperone mute. Discord rejects this unless the member is
connected to voice, so leave them flagged and retry on rejoin."""
key = (member.guild.id, member.id)
if key not in _chaperone_muted:
return
if not member.voice or not member.voice.channel:
return
try:
await member.edit(mute=False)
_chaperone_muted.discard(key)
_save_chaperone_mutes()
logger.info('Unmuted %s (%s)', member.display_name, reason)
except discord.HTTPException as e:
logger.error('Failed to unmute %s: %s', member.display_name, e)
async def check_voice_channel_safety(channel): # pylint: disable=too-many-branches
"""Check if a voice channel has only one adult and one child, and take action if so.
When the channel returns to a safe state, any mute this feature
applied is lifted again — otherwise members stay server-muted
indefinitely and a moderator has to clear each one by hand.
Args:
channel: Discord voice channel object
"""
if not channel or not hasattr(channel, 'members'):
return
adults, children = _count_adults_children(channel)
unsafe = len(adults) == 1 and len(children) == 1
if not unsafe:
# Safe again (or empty) — release our mutes and re-arm alerting
was_flagged = channel.id in _chaperone_flagged
_chaperone_flagged.discard(channel.id)
for member in channel.members:
await _unmute_member(
member, f'{channel.name} no longer 1 adult + 1 child')
if was_flagged:
logger.info(
'Voice channel %s cleared; chaperone mutes lifted',
channel.name)
return
already_flagged = channel.id in _chaperone_flagged
_chaperone_flagged.add(channel.id)
for member in channel.members:
if member.bot or (channel.guild.id, member.id) in _chaperone_muted:
continue
try:
await member.edit(mute=True)
_chaperone_muted.add((channel.guild.id, member.id))
_save_chaperone_mutes()
logger.info('Muted %s in channel %s', member.display_name, channel.name)