-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmuzzled.py
More file actions
10601 lines (8558 loc) · 391 KB
/
Copy pathmuzzled.py
File metadata and controls
10601 lines (8558 loc) · 391 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
import os
import sys
import re
import time
import math
import json
import ast
import base64
import random
import shutil
import string
import sqlite3
import traceback
import subprocess
import asyncio
import requests
import pronouncing
import zipfile
from datetime import datetime, timedelta, timezone
from collections import deque
import discord
from discord.ext import commands, tasks
from discord.ui import View, Button, Select
from discord import Option, Message
from discord.commands import context
from dotenv import load_dotenv
from gtts import gTTS
# Custom project-specific import
import shared
from shared import (
with_config,
unpack_config,
unpack_config_for_guild,
safe_send,
)
# Py-cord specific imports
from discord.commands import Option, SlashCommandGroup, slash_command
from discord.commands.context import AutocompleteContext
Version_Number = "2.3.1"
Version_Notes = "ping update"
# Main version / subversion / patch
ARCHIVE_DIR = "archive"
os.makedirs(ARCHIVE_DIR, exist_ok=True)
os.makedirs("cogs", exist_ok=True)
# Assuming you have this global connection already
global_conn = sqlite3.connect("db/global.db")
def create_last_sent_table():
cur = global_conn.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS prison_status_last_sent (
guild_id INTEGER PRIMARY KEY,
last_sent TEXT
)
""")
global_conn.commit()
async def run_launch_and_report(bot):
proc = await asyncio.create_subprocess_exec(
sys.executable, "launch.py",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await proc.communicate()
output = stdout.decode() + "\n" + stderr.decode()
channel = bot.get_channel(LOG_CHANNEL_ID)
if channel is None:
print("❌ Log channel not found!")
return
if proc.returncode != 0:
# Discord message limit ~2000 chars, chunk output if too long
chunk_size = 1900
for i in range(0, len(output), chunk_size):
await channel.send(f"```\n{output[i:i+chunk_size]}\n```")
else:
await channel.send("✅ launch.py ran successfully with no errors.")
def get_available_databases(bot):
dbs = {"Global (global)": "db/global.db"}
servers_path = "db/servers"
if os.path.isdir(servers_path):
for filename in os.listdir(servers_path):
if filename.endswith(".db"):
server_id = filename[:-3]
try:
guild = bot.get_guild(int(server_id))
name = guild.name if guild else f"Unknown Server"
label = f"{name} ({server_id})"
dbs[label] = os.path.join(servers_path, filename)
except Exception:
continue
return dbs
# Autocomplete function for database names
async def database_autocomplete(ctx: discord.AutocompleteContext):
databases = get_available_databases(ctx.interaction.client)
return list(databases.keys())[:25] # Discord limits choices to 25
def ensure_prefix_column():
try:
shared.c.execute("PRAGMA table_info(server_config)")
existing_columns = [row[1] for row in shared.c.fetchall()]
if "prefix" not in existing_columns:
shared.c.execute("ALTER TABLE server_config ADD COLUMN prefix TEXT DEFAULT '!>'")
shared.conn.commit()
print("✅ Added 'prefix' column to server_config")
except Exception as e:
print(f"[ensure_prefix_column] Error: {e}")
async def load_prefixes():
shared.prefixes = {} # Make sure this dict exists
shared.c.execute("SELECT guild_id, prefix FROM server_config")
rows = shared.c.fetchall()
for guild_id, prefix in rows:
shared.prefixes[guild_id] = prefix or "!>" # default prefix if null
def get_prefix(bot, message):
if not message.guild:
return "!>"
return shared.prefixes.get(message.guild.id, "!>")
bot = commands.Bot(command_prefix=get_prefix, intents=discord.Intents.all())
class DiscordLogger:
def __init__(self, bot, channel_id):
self.bot = bot
self.channel_id = channel_id
self._buffer = ""
self._channel = None
def write(self, message):
self._buffer += message
if "\n" in self._buffer:
asyncio.run_coroutine_threadsafe(self.send(self._buffer), self.bot.loop)
self._buffer = ""
def flush(self):
pass # Required for file-like compatibility
async def send(self, text):
if not self._channel:
self._channel = self.bot.get_channel(self.channel_id)
if self._channel and text.strip():
chunks = [text[i:i+1900] for i in range(0, len(text), 1900)] # Discord limit
for chunk in chunks:
try:
await self._channel.send(f"```\n{chunk.strip()}\n```")
except Exception:
pass # Avoid feedback loops if Discord fails
YOUR_SERVER_ID = 1362071490048032935 # your user ID or bot server ID
async def log_error_to_channels(
bot,
error,
context_label="unspecified",
ctx=None,
guild=None,
channel=None,
user=None,
extra_info=None
):
# Resolve context from ctx if provided
if ctx:
guild = ctx.guild
channel = ctx.channel
user = ctx.author
guild_id = guild.id if guild else None
guild_name = guild.name if guild else "DM or Unknown"
user_str = f"{user} (`{user.id}`)" if user else "Unknown User"
# Build basic error description
if isinstance(error, Exception):
error_text = f"`{type(error).__name__}: {error}`"
else:
error_text = f"`{error}`"
command_name = getattr(ctx.command, "qualified_name", context_label) if ctx else context_label
error_message = (
f"⚠️ **Error in `{command_name}`**\n"
f"Server: {guild_name} (`{guild_id}`)\n"
f"User: {user_str}\n"
f"Error: {error_text}"
)
if extra_info:
error_message += f"\nℹ️ **Extra Info:** {extra_info}"
try:
with sqlite3.connect("db/global.db") as conn:
c = conn.cursor()
c.execute("SELECT guild_id, log_channel_id FROM server_config")
all_logs = dict(c.fetchall()) # {guild_id: log_channel_id}
# Send to this guild's log channel
if guild_id in all_logs:
log_channel = bot.get_channel(all_logs[guild_id])
if log_channel:
await log_channel.send(error_message)
# Send to your dev/owner server's log channel too
if guild_id != YOUR_SERVER_ID and YOUR_SERVER_ID in all_logs:
your_log_channel = bot.get_channel(all_logs[YOUR_SERVER_ID])
if your_log_channel:
await your_log_channel.send(error_message)
except Exception as e:
print(f"[log_error_to_channels] Failed to log error: {e}")
print(f"Original error: {error}")
# ------ DB Table Setup
TABLE_COLUMNS = {
"gagged_users": ["user_id", "type", "status"],
"double_type_users": ["user_id"],
"prison_users": ["user_id", "channel_id", "balance"],
"user_auth": ["user_id", "auth_level"],
"cooldown_users": ["user_id", "cooldown"],
"solitary_confinement": ["user_id", "thread_id", "archive_date"],
"enforced_words": ["user_id", "word", "initial_time", "added_time"],
"enforcement_offenses": ["user_id", "count"],
"banned_words": ["user_id", "word", "initial_time", "added_time"],
"ignored_users": ["user_id"],
"user_settings": ["user_id", "enforcement_action"],
"line_assignments": ["assignment_id", "user_id", "line", "lines_required", "penalty_lines", "last_submission", "assigned_by"],
"active_line_writers": ["user_id", "line", "lines_required", "lines_written", "penalty_lines", "assignment_id", "assigned_by"],
"user_wallets": ["user_id", "balance"],
"bets": ["id", "initiator_id", "opponent_id", "amount", "game", "status", "created_at"],
"daily_claims": ["user_id", "last_claim", "claim_count", "streak_days"],
"timer_logs": ["id", "user_id", "timer_name", "start_time"],
"command_logs": ["id", "user_id", "command", "timestamp", "arguments"],
"allowed_users": ["user_id", "channel_id"],
"locked_users": ["user_id", "locked_by"],
"pishock_users": ["user_id", "code", "shock_min", "shock_max", "vibrate_min", "vibrate_max", "duration_min", "duration_max", "line_writing_shock_intensity", "line_writing_shock_duration", "enforcement_action_shock_intensity", "enforcement_action_shock_duration", "lightning_reaction_shock_intensity", "lightning_reaction_shock_duration"],
"lovense_users": ["user_id", "token"],
"solitary_pings": ["thread_id", "last_ping"],
"bot_status": ["id", "restart_status"],
"pot": ["id", "pot"],
"command_bans": ["user_id"],
"word_length_limits": ["user_id", "min_length", "max_length"]
}
async def table_autocomplete(ctx: AutocompleteContext):
current = (ctx.value or '').lower()
return [name for name in TABLE_COLUMNS if current in name.lower()][:25]
async def column_autocomplete(ctx: AutocompleteContext):
table = ctx.options.get("table_name")
current = (ctx.value or '').lower()
if not table or table not in TABLE_COLUMNS:
return []
return [col for col in TABLE_COLUMNS[table] if current in col.lower()][:25]
# ------------------- Configuration -------------------
load_dotenv(dotenv_path="tetherbot.env")
# Read values from the environment
BOT_TOKEN = os.getenv('BOT_TOKEN')
PRISON_CHANNEL_ID = int(os.getenv('PRISON_CHANNEL_ID'))
DEFAULT_AUTH_MODE = os.getenv('DEFAULT_AUTH_MODE')
TEST_SERVER_ID = 1362071490048032935
'''
LINE_WRITING_ID = int(os.getenv('LINE_WRITING_ID'))
COUNTING_ID = 1366615223221485621 # Channel ID for counting
GAMBLING_ID = 1366615223221485621 # Channel ID for gambling
SOLITARY_ROLE_ID = int(os.getenv('SOLITARY_ROLE_ID'))
PRISONER_ROLE_ID = int(os.getenv('PRISONER_ROLE_ID'))
SC_ROLE_ID = int(os.getenv('SC_ROLE_ID'))
DEFAULT_AUTH_MODE = os.getenv('DEFAULT_AUTH_MODE')
BOTSTATUS_ID = 1368298892847747093 # Channel ID for bot status updates
TASK_CHANNEL_ID = 1364615676907618354
LOG_CHANNEL_ID = 1376990411742117919
'''
# Configuration (USE ENVIRONMENT VARIABLES IN PRODUCTION!)
PISHOCK_USERNAME = (os.getenv('PISHOCK_USERNAME')) # PiShock username
PISHOCK_API_KEY = (os.getenv('PISHOCK_API_KEY')) # PiShock API key
# Lovense API stuff
Lovense_Token = (os.getenv('Lovense_Token'))
Lovense_Key = (os.getenv('Lovense_Key'))
Lovense_IV = (os.getenv('Lovense_IV'))
# Replace with your actual user ID
BOT_OWNER_ID = 1146469921270792326
def is_bot_owner():
def predicate(ctx):
return ctx.author.id == BOT_OWNER_ID
return commands.check(predicate)
Mod = {1146469921270792326, 169981533187211264, 964573737477341235, 927628071706689636, 186523925264465920, 754523779887136799}
additional_lock_managers = {
380625660277948426 # Another one
}
AUTHORIZED_LOCK_MANAGERS = Mod | additional_lock_managers
async def is_user_server_mod(bot, guild_id, user_id):
# Bot owner always allowed
if user_id == BOT_OWNER_ID:
return True
guild = bot.get_guild(guild_id)
if guild:
member = guild.get_member(user_id)
if member and member.guild_permissions.administrator:
return True
try:
with sqlite3.connect("db/global.db") as conn:
cur = conn.cursor()
cur.execute("SELECT 1 FROM moderators WHERE guild_id = ? AND user_id = ?", (guild_id, user_id))
return cur.fetchone() is not None
except Exception as e:
# Optionally log the error
print(f"[is_user_server_mod] DB error: {e}")
return False
def is_server_mod():
async def predicate(ctx):
return await is_user_server_mod(ctx.bot, ctx.guild.id, ctx.author.id)
return commands.check(predicate)
ALLOWED_QUICK_CHAT = {
# General
"I got it!",
"Need boost!",
"Take the shot!",
"Defending...",
"Go for it!",
"Centering!",
"All yours.",
"In position.",
"Incoming!",
"Faking.",
"Bumping!",
"Demoing!",
# Compliments
"Nice shot!",
"Great pass!",
"Thanks!",
"What a save!",
"Nice one!",
"Well played.",
"Great clear!",
"Nice block!",
"Nice demo!",
"Great bump!",
"Savage!",
# Reactions
"OMG!",
"Noooo!",
"Wow!",
"Close one!",
"Whew.",
"Siiiick!",
"Holy cow!",
"Calculated.",
"Whoops...",
"Okay.",
"Everybody dance!",
# Apologies
"Sorry!",
"No problem.",
"Oops!",
"My bad.",
# Post-game
"Good game!",
"gg",
"That was fun!",
"Rematch!",
# Tactical
"Pressing.",
"Cheating up.",
"Rotating.",
"Heads up!",
"To you!",
"You got this!"
}
RESTRICTED_USER_ID = 1 # Replace with your target Discord user ID
# ------------------- Database Setup -------------------
conn = sqlite3.connect('db/global.db')
shared.conn = conn
c = conn.cursor()
shared.c = c
# Create tables
clicker_users = {824747106370584599, 169981533187211264, 380625660277948426, 1146469921270792326, 1292644804831875073, 885014775245975573}
from shared import PerGuildDict
bot_paused = False
WEBHOOK_NAME = "GagWebhook"
is_restarting = False # Global variable to track if bot is restarting
COST_TO_START = 1
FREEDOM_DURATION = 30 * 60
MAX_FREEDOM_DURATION = 2 * 60 * 60 # 2 hours in seconds
SECONDS_PER_BUCK = 2
temporarily_freed = {}
COUNT_TO = 100
freedom_pot = 0
COMMAND_LIMIT = 5
TIME_WINDOW = 10 # seconds
# ------------------- Bot Setup -------------------
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True
intents.reactions = True
intents.members = True
bot = commands.Bot(
command_prefix=get_prefix,
intents=intents,
help_command=None,
case_insensitive=True
)
# Save the original method
original_add_reaction = Message.add_reaction
# Monkey-patch with the silent check
async def patched_add_reaction(self, emoji):
try:
if not shared.silent_command_running:
return await original_add_reaction(self, emoji)
except Exception as e:
print(f"Failed to add reaction: {e}")
return None
Message.add_reaction = patched_add_reaction
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CheckFailure):
return # Blocked or not allowed — already handled in check
elif isinstance(error, commands.MissingPermissions):
await ctx.send("⛔ You don't have permission to use this command!")
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send("⚠️ Missing required arguments!")
else:
await log_error_to_channels(bot=bot, error=error, ctx=ctx)
@bot.event
async def on_application_command_error(ctx, error):
if isinstance(error, commands.CheckFailure):
# Only suppress CheckFailure from the command ban check
if str(error) == "User is blocked from using commands.":
return
else:
await ctx.respond("❌ You don't meet the requirements to run this command.", ephemeral=True)
else:
await log_error_to_channels(bot=bot, error=error, ctx=ctx)
URL_REGEX = re.compile(r'https?://\S+')
NITRO_EMOJI_REGEX = re.compile(r'<a?:\w+:\d+>')
LOG_CHANNEL_ID = 1376990411742117919
@bot.event
async def on_ready():
BOTSTATUS_ID = 1368298892847747093
print(f"Logged in as {bot.user}")
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name="with chewtoys!"))
status_channel = bot.get_channel(LOG_CHANNEL_ID)
# Redirect stdout/stderr to Discord logging
sys.stdout = DiscordLogger(bot, LOG_CHANNEL_ID)
sys.stderr = sys.stdout
# Check global bot_status for restart flag
shared.c.execute("SELECT restart_status FROM bot_status WHERE id = 1")
restart_status = shared.c.fetchone()
ensure_prefix_column()
# Send online status if not a restart
if not (restart_status and restart_status[0] == "restarting"):
new_channel_name = "✅bot-online"
channel = bot.get_channel(BOTSTATUS_ID)
if channel:
embed = discord.Embed(
title="👋 BOT IS ONLINE!",
description=f"`Version: {Version_Number}`",
color=0x00ffcc
)
embed.set_footer(text=Version_Notes)
await channel.send(embed=embed)
try:
if channel.name != new_channel_name:
await channel.edit(name=new_channel_name)
print(f"Renamed channel to: {new_channel_name}")
except Exception as e:
print(f"Failed to rename channel: {e}")
else:
print("Channel not found or bot lacks access.")
# Clear restart flag if previously set
if restart_status and restart_status[0] == "restarting":
shared.c.execute("UPDATE bot_status SET restart_status = NULL WHERE id = 1")
shared.conn.commit()
# Ensure server_config columns exist
ensure_cog_columns_from_files()
await load_prefixes()
if not process_command_logs.is_running():
process_command_logs.start()
# --- Load per-guild memory state ---
for guild in bot.guilds:
guild_id = guild.id
db = shared.get_server_db(guild_id)
cur = db.cursor()
# Gagged users
cur.execute("SELECT user_id, type FROM gagged_users WHERE status = 'active'")
gagged = {row[0]: row[1] for row in cur.fetchall()}
shared.gagged_users[guild_id].update(gagged)
# PiShock users (global dict)
cur.execute("SELECT user_id, code FROM pishock_users")
pishock_code = {row[0]: row[1] for row in cur.fetchall()}
shared.user_pishock_codes[guild_id].update(pishock_code)
# Prison users
cur.execute("SELECT user_id, channel_id FROM prison_users")
prison = {row[0]: row[1] for row in cur.fetchall()}
shared.prison_users[guild_id].update(prison)
# Cooldown users
cur.execute("SELECT user_id, cooldown FROM cooldown_users")
cooldown_rows = cur.fetchall()
for row in cooldown_rows:
shared.cooldown_users[guild_id][row[0]] = row[1]
shared.last_message_times[guild_id][row[0]] = 0
# Solitary confinement
cur.execute("SELECT user_id, thread_id FROM solitary_confinement")
solitary = {row[0]: row[1] for row in cur.fetchall()}
shared.solitary_confinement[guild_id].update(solitary)
# Enforced words
cur.execute("SELECT user_id, word, initial_time, added_time FROM enforced_words")
enforced_count = 0
for row in cur.fetchall():
user_id, word, initial_time, added_time = row
shared.enforced_words[guild_id].setdefault(user_id, {})[word.lower()] = {
"initial_time": initial_time,
"added_time": added_time
}
enforced_count += 1
# Enforcement offenses
cur.execute("SELECT user_id, count FROM enforcement_offenses")
shared.enforcement_offenses[guild_id].update({row[0]: row[1] for row in cur.fetchall()})
# Banned words
cur.execute("SELECT user_id, word, initial_time, added_time FROM banned_words")
banned_count = 0
for row in cur.fetchall():
user_id, word, initial_time, added_time = row
shared.banned_words[guild_id].setdefault(user_id, {})[word.lower()] = {
"initial_time": initial_time,
"added_time": added_time
}
banned_count += 1
# Ignored users
cur.execute("SELECT user_id FROM double_type_users")
for row in cur.fetchall():
shared.double_type_users[guild_id].add(row[0])
# Ignored users
cur.execute("SELECT user_id FROM ignored_users")
for row in cur.fetchall():
shared.ignored_users[guild_id].add(row[0])
cur.execute("SELECT user_id, min_length, max_length FROM word_length_limits")
for row in cur.fetchall():
user_id, min_length, max_length = row
shared.word_length_limits[guild_id][user_id] = {
"min_length": min_length,
"max_length": max_length
}
# Line writing sessions
cur.execute("SELECT user_id, line, lines_required, lines_written FROM active_line_writers")
writer_count = 0
for row in cur.fetchall():
uid, line, req, written = row
shared.line_writing_sessions[guild_id][uid] = {
"line": line,
"lines_required": req,
"lines_written": written
}
writer_count += 1
# Locked users
cur.execute("SELECT user_id, locked_by FROM locked_users")
locked_count = 0
for user_id, locked_by in cur.fetchall():
shared.locked_users[guild_id].add(user_id)
shared.locked_by_map[guild_id][user_id] = locked_by
locked_count += 1
# Assemble smart stat line
stat_parts = []
if gagged: stat_parts.append(f"{len(gagged)} gagged users")
if prison: stat_parts.append(f"{len(prison)} prisoned users")
if solitary: stat_parts.append(f"{len(solitary)} solitary records")
if enforced_count: stat_parts.append(f"{enforced_count} enforced words")
if banned_count: stat_parts.append(f"{banned_count} banned words")
if locked_count: stat_parts.append(f"{locked_count} locked users")
if writer_count: stat_parts.append(f"{writer_count} writing assignments")
stats_str = ", ".join(stat_parts) if stat_parts else "no active data"
print(f"✅ {guild.name} ({guild_id}) — {stats_str}")
# --- Load all Cogs ---
all_cogs = [f"cogs.{name}" for name in list_toggleable_cogs()]
for cog in all_cogs:
try:
bot.load_extension(cog)
print(f"✅ Loaded {cog}")
except Exception as e:
error_msg = f"❌ Failed to load `{cog}`: {e}"
traceback_str = traceback.format_exc()
print(error_msg)
print(traceback_str)
if status_channel:
await status_channel.send(
f"{error_msg}\n```{traceback_str[-1500:]}```"
)
# Update server count channel name if changed
try:
server_count_channel = bot.get_channel(1380259276974461081)
if server_count_channel:
current_count = len(bot.guilds)
expected_name = f"{current_count}-servers"
if server_count_channel.name != expected_name:
await server_count_channel.edit(name=expected_name)
print(f"🔢 Updated server count channel to '{expected_name}'")
except Exception as e:
print(f"[Server Count] Failed to update channel name: {e}")
# Final summary
if not send_prison_status_periodically.is_running():
send_prison_status_periodically.start()
create_last_sent_table()
print("✅ on_ready complete.")
@bot.event
async def on_typing(channel, user, when):
# Replace with your actual IDs
'''
target_user_id = 927628071706689636
# Check user and guild match
if user.id == target_user_id and channel.guild and channel.guild.id == TEST_SERVER_ID:
await channel.send(f"{user.mention} I see you typing... 👀", delete_after=5)
'''
@bot.event
async def on_message_edit(before, after):
# Avoid bot messages and partials
if after.author.bot or not after.content:
return
if before.content == after.content:
return
# Reuse your enforcement logic
await on_message_or_edit(after, edited = True)
@bot.event
async def on_message(message):
await on_message_or_edit(message, edited = False)
async def on_message_or_edit(message, edited: bool = False):
try:
if not message.author.bot and message.guild:
# ✅ Load server-specific database
guild_id = message.guild.id
user_id = message.author.id
db = shared.get_server_db(guild_id)
c = db.cursor()
config = shared.get_server_config(message.guild.id) # or message.guild.id
conn = c.connection
if not config:
if message.author.guild_permissions.administrator:
try:
await message.author.send(
f"⚠️ No configuration found for **{message.guild.name}**.\n"
f"Please use `/setup_ids` in your server to set the required channels and roles."
f"Also join the support server for more information and help setting up this bot. https://discord.gg/zeESfuRMf8"
)
except discord.Forbidden:
# User has DMs off or blocked the bot
pass
return
# Now your variables match the original names
(
PRISON_CHANNEL_ID,
LINE_WRITING_ID,
COUNTING_ID,
GAMBLING_ID,
SOLITARY_ROLE_ID,
PRISONER_ROLE_ID,
SC_ROLE_ID,
BOTSTATUS_ID,
TASK_CHANNEL_ID,
LOG_CHANNEL_ID
) = shared.unpack_config_from_obj(config)
if message.channel.id == LOG_CHANNEL_ID:
await bot.process_commands(message)
return
shared.returnvar = False
global bot_paused
if bot_paused and not message.content.startswith('!>pause'):
return # Ignore all messages except the unpause command
if message.author.bot:
return
original_author = message.author
original_content = message.content
user_id = message.author.id
guild_id = message.guild.id if message.guild else None
# If user has a pending silent command in this guild:
key = (message.guild.id if message.guild else None, message.author.id)
if key in shared.pending_silent_commands:
# Prevent recursion
if getattr(shared, "silent_command_running", False):
# If flag is set, we're already running a silent command, skip to normal processing
return await bot.process_commands(message)
shared.silent_command_running = True
try:
run_as, silent_cmd = shared.pending_silent_commands[key]
if message.guild and message.guild.id == key[0]:
run_as = message.author
original_author = message.author
original_content = message.content
try:
message.author = run_as
message.content = silent_cmd
ctx = await bot.get_context(message)
original_ctx_author = ctx.author
ctx.author = run_as
del shared.pending_silent_commands[key]
await bot.invoke(ctx)
finally:
# Restore everything
message.author = original_author
message.content = original_content
ctx.author = original_ctx_author
finally:
shared.silent_command_running = False
if "*click*" in message.content.lower() or "*clicks*" in message.content.lower():
mp3_file_path = "non-suspicious sound.mp3"
# Check if the mp3 file exists and send it if it does
if os.path.exists(mp3_file_path):
# Rename the file when sending (without changing the original filename in the directory)
await message.channel.send(file=discord.File(mp3_file_path, filename="wruf.mp3"))
return
if "!>bark" in message.content.lower() or "!>bork" in message.content.lower():
bark_file_path = "bark.png"
if os.path.exists(bark_file_path):
await message.channel.send(file=discord.File(bark_file_path, filename="bark.png"))
return
if "!>rigged" in message.content.lower() or "!>unfair" in message.content.lower():
rigged_file_path = "rigged.png"
if os.path.exists(rigged_file_path):
await message.channel.send(file=discord.File(rigged_file_path, filename="rigged.png"))
return
if "*collar*" in message.content.lower() or "!>collar" in message.content.lower():
collar_file_path = "collar.mp3"
# Check if the mp3 file exists and send it if it does
if os.path.exists(collar_file_path):
# Rename the file when sending (without changing the original filename in the directory)
await message.channel.send(file=discord.File(collar_file_path, filename="jingle.mp3"))
return
if (
message.attachments and
message.author.id == 1146469921270792326 and
isinstance(message.channel, discord.DMChannel)
):
timestamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
for attachment in message.attachments:
filename = attachment.filename.lower()
try:
# Handle database update
if filename.endswith(".db"):
timestamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
os.makedirs("archive", exist_ok=True)
if filename == "global.db":
# Backup and replace global DB
shutil.copy("db/global.db", f"archive/global_{timestamp}.db")
await attachment.save("db/global.db")
await message.channel.send("✅ Global database updated and archived.")
elif filename.isdigit() and os.path.exists(f"db/servers/{filename}"):
# Backup and replace a known server DB
shutil.copy(f"db/servers/{filename}", f"archive/{filename[:-3]}_{timestamp}.db")
await attachment.save(f"db/servers/{filename}")
await message.channel.send(f"✅ Server DB `{filename}` updated and archived.")
else:
# Save unknown/new DB files in db/
await attachment.save(f"db/{filename}")
await message.channel.send(f"📦 Unknown DB `{filename}` saved to `db/`.")
# Handle Python files
elif filename.endswith(".py"):
if filename == "muzzled.py" or filename == "muzzled_reset.py":
shutil.copy("muzzled.py", f"archive/muzzled_{timestamp}.py")
await attachment.save("muzzled.py")
await message.channel.send("✅ muzzled.py updated. Restarting...")
subprocess.Popen([sys.executable, "launch.py"])
sys.exit(0)
elif filename == "muzzled_safe.py":
await attachment.save("muzzled_safe.py")
await message.channel.send("✅ muzzled_safe.py updated in the main folder.")
elif filename == "watchdog.py":
await attachment.save("watchdog.py")
await message.channel.send("✅ watchdog.py updated in the main folder.")
elif filename == "launch.py":
await attachment.save("launch.py")
await message.channel.send("✅ launch.py updated in the main folder.")
elif filename == "launch_safe.py":
await attachment.save("launch_safe.py")
await message.channel.send("✅ launch_safe.py updated in the main folder.")
elif filename == "shared.py":
await attachment.save("shared.py")
await message.channel.send("✅ shared.py updated in the main folder.")
else:
cog_path = os.path.join("cogs", filename)
await attachment.save(cog_path)
await message.channel.send(f"✅ Python file `{filename}` saved to `cogs/`.")
elif filename == "disabled_cogs.json":
shutil.copy("disabled_cogs.json", f"archive/disabled_cogs_{timestamp}.json")
await attachment.save("disabled_cogs.json")
await message.channel.send("✅ `disabled_cogs.json` updated and archived.")
# Handle .env file
elif filename.endswith(".env"):
shutil.copy("tetherbot.env", f"archive/tetherbot_{timestamp}.env")
await attachment.save("tetherbot.env")
await message.channel.send("✅ `.env` file saved as `tetherbot.env` and archived.")
subprocess.Popen([sys.executable, "launch.py"])
sys.exit(0)
# Default handler
else:
save_path = os.path.join(os.getcwd(), attachment.filename)
await attachment.save(save_path)
await message.channel.send(f"✅ File `{attachment.filename}` saved.")
subprocess.Popen([sys.executable, "launch.py"])
sys.exit(0)
except Exception as e:
await message.channel.send(f"❌ Failed to process `{filename}`: {e}")
if bot.user in message.mentions:
await message.add_reaction("<:goofy:1367975113835810816>")
# Skip messages that just created threads
if message.thread is not None:
return # message was used to create a thread
if message.type not in (discord.MessageType.default, discord.MessageType.reply):
return
# if random.randint(1, 1_000_000_000_000) == 1:
# user = await bot.fetch_user(927628071706689636)
# await message.guild.ban(user)
# await message.channel.send(f"🔨 Against all odds, user `{user}` (`{user.id}`) has been banned.")
# return
# Skip forced filter logic if message is in DMs
if not message.guild:
forced_filtered = False
else: