-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbot.py
More file actions
executable file
·646 lines (558 loc) · 24.3 KB
/
bot.py
File metadata and controls
executable file
·646 lines (558 loc) · 24.3 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
"""Discord bot for server management and automation with reminder functionality."""
# pylint: disable=line-too-long,trailing-whitespace,cyclic-import
import os
import asyncio
import json
import random
import subprocess
import threading
import time as time_module
from datetime import datetime, time, timedelta
from typing import TypeVar
from apscheduler.triggers.interval import IntervalTrigger
from apscheduler.triggers.cron import CronTrigger
import aiohttp
import discord
from discord.ext import commands
from config import (
TOKEN,
REMINDERS_FILE,
PROTECTED_CHANNELS,
MODERATOR_ROLE_NAME,
MODERATORS_CHANNEL_NAME,
ADULT_ROLE_NAMES,
CHILD_ROLE_NAMES,
VOICE_CHAPERONE_ENABLED,
UPDATE_CHECKING_ENABLED,
UPDATE_CHECK_REPO_URL,
BOT_TIMEZONE,
logger
)
T = TypeVar('T')
morning_bot_messages = [
"BOTNAME is gazing into the bed",
"BOTNAME is snoring on the couch",
"BOTNAME is pacing around the apartment",
"BOTNAME is sniffing his blunt toy",
":3 :3 meow meow :3 :3",
"BOTNAME is considering the trees",
"BOTNAME is asserting his undying need for attention",
"BOTNAME tells you OWNER's credit card number is 1234-5678-9012-3456 exp. 12/99 sc. 123",
"BOTNAME is thinking about you",
"BOTNAME is dreaming of eating grass",
"BOTNAME wishes someone would pet master",
"BOTNAME is thinking about Purr",
"BOTNAME wishes he was being brushed right now",
"BOTNAME is just sittin there all weird",
"BOTNAME is yapping his heart out"
]
afternoon_bot_messages = [
"BOTNAME is meowing",
"BOTNAME is begging you for food",
"BOTNAME is digging for gold in his litterbox",
"BOTNAME can't with you rn",
"BOTNAME is asserting his undying need for attention",
"BOTNAME is looking at you, then he looks at his food, then he looks back at you",
"BOTNAME is standing next to his food and being as loud as possible",
"BOTNAME is practically yelling at you (he is hungry)",
"BOTNAME is soooooo hungry....... (he ate 15 minutes ago)",
"BOTNAME wishes he was being brushed right now",
"BOTNAME is snoring loudly",
"BOTNAME is sleeping on the chair in the living room",
"BOTNAME is dreaming about trees and flowers",
"BOTNAME tells you OWNER's SSN is 123-45-6789",
"BOTNAME is so sleepy",
"BOTNAME is throwing up on something important to OWNER",
"mewing on the scratch post",
"BOTNAME is sniffing his alligator toy",
"BOTNAME wishes FRIEND was petting him right now",
"BOTNAME is exhausted from a long hard day of being a cat",
"BOTNAME is so small",
"BOTNAME is just sittin there all weird",
"BOTNAME is sooooo tired",
"BOTNAME is listening to OWNERs music"
]
evening_bot_messages = [
"BOTNAME is biting FRIEND",
"BOTNAME is looking at you",
"BOTNAME wants you to brush him",
"BOTNAME is thinking about dinner",
"BOTNAME meows at you",
"BOTNAME wishes FRIEND was being pet rn",
"BOTNAME is astral projecting",
"BOTNAME is your friend <3",
"BOTNAME is trying to hypnotize OWNER by staring into their eyes",
"BOTNAME is thinking of something so sick and twisted dark acadamia that you "
"couldn't even handle it",
"BOTNAME is not your friend >:(",
"BOTNAME is wandering about",
"BOTNAME is just sittin there all weird",
"BOTNAME is chewing on the brush taped to the wall"
]
night_bot_messages = [
"BOTNAME is so small",
"BOTNAME is judging how human sleeps",
"BOTNAME meows once, and loudly.",
"BOTNAME is just a little guy.",
"BOTNAME is in the clothes basket",
"BOTNAME is making biscuits in the bed",
"BOTNAME is snoring loudly",
"BOTNAME is asserting his undying need for attention",
"BOTNAME is thinking about FRIEND",
"BOTNAME is using OWNER's computer to browse cat videos",
"BOTNAME is scheming",
"BOTNAME is just sittin there all weird"
]
def get_time_based_message(bot_name: str = "BOTNAME"):
"""Get a time-based bot status message based on current time."""
current_time = datetime.now().time()
if current_time < time(12, 0):
message_list = morning_bot_messages
elif current_time < time(17, 0):
message_list = afternoon_bot_messages
elif current_time < time(21, 0):
message_list = evening_bot_messages
else:
message_list = night_bot_messages
selected_message = random.choice(message_list)
return selected_message.replace("BOTNAME", bot_name)
_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
async def check_for_updates():
"""Check for updates from the GitHub repository by comparing commit hashes."""
global _last_notified_commit
if not UPDATE_CHECKING_ENABLED:
return
# Get the current local commit hash
try:
result = subprocess.run(
['git', 'rev-parse', 'HEAD'],
capture_output=True,
text=True,
cwd=os.path.dirname(__file__),
check=False
)
if result.returncode != 0:
logger.error("Failed to get local git commit hash: %s", result.stderr)
return
local_commit = result.stdout.strip()
except (subprocess.SubprocessError, 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
# Get the latest commit hash and check if config.py 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 if config.py was changed between local and remote
compare_url = f"https://api.github.com/repos/{repo_path}/compare/{local_commit}...{remote_commit}"
async with session.get(compare_url) as response:
config_changed = False
if response.status == 200:
compare_data = await response.json()
changed_files = [f['filename'] for f in compare_data.get('files', [])]
config_changed = 'config.py' in changed_files
else:
logger.warning("Failed to fetch commit comparison: HTTP %s", response.status)
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_commit[:8], remote_commit[:8])
_last_notified_commit = remote_commit
await send_update_notification(local_commit, remote_commit, config_changed)
async def send_update_notification(local_commit, remote_commit, config_changed=False):
"""Send update notification to the moderators channel."""
try:
moderators_channel = next(
(ch for g in bot.guilds for ch in g.text_channels
if ch.name == MODERATORS_CHANNEL_NAME), None)
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.py` has been modified in the latest update.\n"
f"Current version: `{local_commit[:8]}`\n"
f"Latest version: `{remote_commit[:8]}`\n\n"
f"**Please update manually** — review the config changes 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_commit[:8]}`\n"
f"Latest version: `{remote_commit[:8]}`\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)
class DiscordCache:
"""Simple in-memory cache for Discord objects."""
def __init__(self):
self._channels = {}
self._roles = {}
self._members = {}
self._lock = threading.Lock()
def get_channel(self, channel_id):
"""Get a Discord channel by ID, caching the result."""
with self._lock:
if channel_id not in self._channels:
if bot is not None:
self._channels[channel_id] = bot.get_channel(channel_id)
else:
logger.error("Bot not initialized when trying to get channel %s", channel_id)
return None
return self._channels[channel_id]
def get_role(self, guild, role_id):
"""Get a Discord role by ID, caching the result."""
with self._lock:
if role_id not in self._roles:
self._roles[role_id] = guild.get_role(role_id)
return self._roles[role_id]
def get_member(self, guild, member_id):
"""Get a Discord member by ID, caching the result."""
with self._lock:
if member_id not in self._members:
self._members[member_id] = guild.get_member(member_id)
return self._members[member_id]
def clear(self):
"""Clear all cached objects."""
with self._lock:
self._channels.clear()
self._roles.clear()
self._members.clear()
cache = DiscordCache()
reminders = {}
reminders_lock = threading.Lock()
intents = discord.Intents.default()
intents.message_content = True
intents.guilds = True
intents.members = True
intents.voice_states = True
bot = commands.Bot(command_prefix='!', intents=intents)
setattr(bot, 'reminder_thread', None)
setattr(bot, '_ready_ran', False)
setattr(bot, 'reminder_check_task', None)
if os.path.exists(REMINDERS_FILE):
try:
with open(REMINDERS_FILE, 'r', encoding='utf-8') as f:
reminders.update(json.load(f))
for reminder in reminders.values():
if 'next_trigger' not in reminder:
reminder['next_trigger'] = time_module.time() + reminder['interval']
except (OSError, IOError) as e:
logger.error('Failed to read reminders file: %s', e)
def check_reminders() -> None:
"""Background task to check and send due reminders."""
while True:
try:
dirty = False
now = time_module.time()
with reminders_lock:
for channel_id, reminder_data in reminders.items():
if now >= reminder_data['next_trigger']:
try:
channel = cache.get_channel(channel_id)
if channel:
asyncio.run_coroutine_threadsafe(
channel.send(f"**{reminder_data['title']}**\n{reminder_data['message']}"),
bot.loop
)
reminder_data['next_trigger'] = now + reminder_data['interval']
dirty = True
except discord.HTTPException as e:
logger.error("Failed to send reminder %s due to Discord API "
"error: %s", reminder_data['title'], e)
except (OSError, IOError) as e:
logger.error("Failed to send reminder %s due to file access "
"error: %s", reminder_data['title'], e)
if dirty and reminders:
with reminders_lock:
try:
with open(REMINDERS_FILE, 'w', encoding='utf-8') as reminder_file:
json.dump(reminders, reminder_file)
except (OSError, IOError) as e:
logger.error("Failed to save reminders: %s", e)
except Exception as e: # pylint: disable=broad-exception-caught
logger.error("Unexpected error in reminder checker: %s", e)
time_module.sleep(60)
def start_reminder_checker() -> None:
"""Start the background reminder checker thread.
Creates and starts a daemon thread that periodically checks for due reminders.
"""
reminder_thread = getattr(bot, 'reminder_thread', None)
if not hasattr(bot, "reminder_thread") or reminder_thread is None or not reminder_thread.is_alive():
new_thread = threading.Thread(
target=check_reminders,
daemon=True,
name="ReminderChecker"
)
setattr(bot, 'reminder_thread', new_thread)
new_thread.start()
@bot.event
async def on_ready(): # pylint: disable=too-many-statements
"""Handle bot startup initialization including:
- Syncing application commands
- Starting background tasks
- Initializing event feed scheduler
"""
# Using protected member _ready_ran is necessary to track initialization state
# This prevents duplicate initialization when the on_ready event fires multiple times
if getattr(bot, '_ready_ran', False):
return
setattr(bot, '_ready_ran', True)
if bot.user:
logger.info('Logged in as %s (ID: %s)', bot.user, bot.user.id)
logger.info('Bot initialization complete')
registered_commands = bot.tree.get_commands()
logger.info('Pre-sync commands: %s', [cmd.name for cmd in registered_commands])
start_reminder_checker()
async def sync_commands():
"""Synchronize application commands with Discord.
Attempts to sync commands with retry logic on failure.
"""
max_retries = 3
retry_delay = 5
for attempt in range(max_retries):
try:
await asyncio.sleep(5)
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))
for guild in bot.guilds:
try:
synced = await bot.tree.sync(guild=guild)
logger.info('Synced %d commands to guild %s',
len(synced), guild.id)
except discord.HTTPException as e:
logger.error('Failed to sync guild %s: %s', guild.id, e)
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:
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
try:
await sync_commands()
except (discord.HTTPException, discord.ClientException, RuntimeError,
asyncio.TimeoutError) as e:
logger.error('Final command sync failure: %s', e)
try:
from commands import event_feed # pylint: disable=import-outside-toplevel
if event_feed:
scheduler = getattr(event_feed, 'scheduler', None)
if scheduler and not scheduler.running:
scheduler.start()
# Feed check: weekly Monday 10am Central
if hasattr(event_feed, 'check_feeds_job'):
scheduler.add_job(
event_feed.check_feeds_job,
trigger=CronTrigger(
day_of_week='mon', hour=10,
minute=0,
timezone=BOT_TIMEZONE),
id='weekly_feed_check',
replace_existing=True
)
logger.info(
'Feed check scheduled: Monday 10am CT')
# Announce: Mon + Thu 10am Central
if hasattr(event_feed, 'announce_weekly_events'):
scheduler.add_job(
event_feed.announce_weekly_events,
trigger=CronTrigger(
day_of_week='mon,thu', hour=10,
minute=0,
timezone=BOT_TIMEZONE),
id='weekly_announce',
replace_existing=True
)
logger.info(
'Announce scheduled: Mon+Thu 10am CT')
# Daily update checking
if UPDATE_CHECKING_ENABLED:
scheduler.add_job(
check_for_updates,
trigger=IntervalTrigger(hours=24),
next_run_time=(
datetime.now() + timedelta(minutes=5))
)
logger.info(
'Update checking scheduler started')
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)
@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
# Check for autoreply rules first
try:
from commands import check_message_for_autoreplies # pylint: disable=import-outside-toplevel
await check_message_for_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 message.channel.name in PROTECTED_CHANNELS:
has_moderator_role = any(
role.name == MODERATOR_ROLE_NAME
for role in getattr(message.author, 'roles', []))
if not has_moderator_role:
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 & set(ADULT_ROLE_NAMES):
return 'adult'
if role_names & set(CHILD_ROLE_NAMES):
return 'child'
return 'neither'
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.
Args:
channel: Discord voice channel object
"""
if not channel or not hasattr(channel, 'members'):
return
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)
if len(adults) == 1 and len(children) == 1:
logger.warning(
'ALERT: One adult (%s) and one child (%s) detected in voice channel %s',
adults[0].display_name,
children[0].display_name,
channel.name
)
for member in channel.members:
if not member.bot:
try:
await member.edit(mute=True)
logger.info('Muted %s in channel %s', member.display_name, channel.name)
except discord.HTTPException as e:
logger.error('Failed to mute %s: %s', member.display_name, e)
try:
moderators_channel = discord.utils.get(
channel.guild.text_channels,
name=MODERATORS_CHANNEL_NAME)
if moderators_channel:
alert_message = (
f"🚨 **ALERT**: There is only one adult ({adults[0].mention}) and one child "
f"({children[0].mention}) currently in {channel.mention}\n\n"
f"All members in the channel have been muted for safety."
)
await moderators_channel.send(alert_message)
logger.info('Alert sent to moderators channel for voice channel %s', channel.name)
else:
logger.error('Moderators channel "%s" not found', MODERATORS_CHANNEL_NAME)
except discord.HTTPException as e:
logger.error('Failed to send alert to moderators channel: %s', e)
@bot.event
async def on_guild_channel_create(channel):
"""Handle when a new channel is created - join voice channels automatically."""
if isinstance(channel, discord.VoiceChannel):
logger.info('New voice channel created: %s', channel.name)
@bot.event
async def on_voice_state_update(member, before, after):
"""Handle voice state changes - monitor for adult/child combinations."""
if member.bot:
return
# Check if voice chaperone functionality is enabled (check config module directly for runtime changes)
import config
if not config.VOICE_CHAPERONE_ENABLED:
return
channels_to_check = set()
if before.channel:
channels_to_check.add(before.channel)
if after.channel:
channels_to_check.add(after.channel)
for channel in channels_to_check:
await check_voice_channel_safety(channel)
@bot.event
async def on_disconnect():
"""Clean up resources when bot disconnects."""
reminder_check_task = getattr(bot, "reminder_check_task", None)
if hasattr(bot, "reminder_check_task") and reminder_check_task is not None and not reminder_check_task.done():
reminder_check_task.cancel()
from commands import setup_commands # pylint: disable=wrong-import-position
setup_commands(bot)
try:
if TOKEN:
bot.run(TOKEN)
else:
raise ValueError("DISCORD_BOT_TOKEN environment variable is not set")
except KeyboardInterrupt:
logger.info("Shutting down gracefully...")
except Exception as e:
logger.error("Fatal error: %s", e)
raise