Files
bot.py
requirements.txt
Code
2 572
bot.py
import asyncio
import json
import logging
import os
import random
import re
import unicodedata
from pathlib import Path
import discord
from discord import app_commands
from discord.ext import tasks
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("vc_bot")
STATE_FILE = Path("voice_state.json")
MENTION_FILTER_STATE_FILE = Path("mention_filter_state.json")
FILTER_TERMS_FILE = Path("filter_terms.json")
AUTO_REACT_RULES_FILE = Path("auto_react_rules.json")
def load_saved_channels() -> dict[str, int]:
try:
data = json.loads(STATE_FILE.read_text(encoding="utf-8"))
return {str(guild_id): int(channel_id) for guild_id, channel_id in data.items()}
except FileNotFoundError:
return {}
except (OSError, json.JSONDecodeError, AttributeError, TypeError, ValueError):
logger.exception("Could not load saved voice channels")
return {}
saved_channels = load_saved_channels()
try:
active_mention_filters = {
int(guild_id)
for guild_id in json.loads(MENTION_FILTER_STATE_FILE.read_text(encoding="utf-8"))
}
except FileNotFoundError:
active_mention_filters = set()
except (OSError, json.JSONDecodeError, TypeError, ValueError):
logger.exception("Could not load active mention filters")
active_mention_filters = set()
try:
saved_filter_terms = {
int(guild_id): [term for term in terms if isinstance(term, str) and term.strip()]
for guild_id, terms in json.loads(FILTER_TERMS_FILE.read_text(encoding="utf-8")).items()
if isinstance(terms, list)
}
except FileNotFoundError:
saved_filter_terms = {}
except (OSError, json.JSONDecodeError, AttributeError, TypeError, ValueError):
logger.exception("Could not load custom filter terms")
saved_filter_terms = {}
try:
auto_react_rules = {
int(guild_id): (rule["term"], rule["emoji"])
for guild_id, rule in json.loads(AUTO_REACT_RULES_FILE.read_text(encoding="utf-8")).items()
if isinstance(rule, dict)
and isinstance(rule.get("term"), str)
and rule["term"].strip()
and isinstance(rule.get("emoji"), str)
and rule["emoji"].strip()
}
except FileNotFoundError:
auto_react_rules = {}
except (OSError, json.JSONDecodeError, AttributeError, TypeError, ValueError, KeyError):
logger.exception("Could not load auto-reaction rules")
auto_react_rules = {}
active_senders: dict[int, tuple[int, float]] = {}
sender_messages = (
"I am having a asthma attack.",
"Oopsie, my fault.",
"Dead chat, time to wait.",
"I cannot breathe.",
"Air is great.",
)
default_filter_terms = ("Niijii", "Niji", "N1j1", "@itsmeniijii")
leet_translation = str.maketrans({"1": "i", "3": "e", "4": "a", "5": "s", "7": "t", "0": "o"})
mention_filter_gif = "https://tenor.com/view/ryuuge-kisaki-blue-archive-kawaii-anime-cute-gif-18305142251573597861"
max_filter_terms = 25
def save_channels() -> None:
STATE_FILE.write_text(json.dumps(saved_channels, indent=2), encoding="utf-8")
def save_mention_filter_state() -> None:
MENTION_FILTER_STATE_FILE.write_text(
json.dumps(sorted(active_mention_filters), indent=2),
encoding="utf-8",
)
def save_filter_terms() -> None:
FILTER_TERMS_FILE.write_text(
json.dumps({str(guild_id): terms for guild_id, terms in saved_filter_terms.items()}, indent=2),
encoding="utf-8",
)
def save_auto_react_rules() -> None:
AUTO_REACT_RULES_FILE.write_text(
json.dumps(
{
str(guild_id): {"term": term, "emoji": emoji}
for guild_id, (term, emoji) in auto_react_rules.items()
},
indent=2,
),
encoding="utf-8",
)
def normalize_filter_term(text: str) -> str:
normalized = unicodedata.normalize("NFKC", text).casefold()
compact = "".join(character for character in normalized if character.isalnum())
return compact.translate(leet_translation)
def contains_filter_term(text: str, terms: tuple[str, ...] | list[str]) -> bool:
normalized_text = normalize_filter_term(text)
return any(
normalized_term in normalized_text
for term in terms
if (normalized_term := normalize_filter_term(term))
)
intents = discord.Intents.none()
intents.guilds = True
intents.voice_states = True
intents.message_content = True
bot = discord.Client(intents=intents)
tree = app_commands.CommandTree(bot)
@tree.command(name="join", description="Join your current voice channel and remember it")
async def join(interaction: discord.Interaction) -> None:
if interaction.guild is None or not isinstance(interaction.user, discord.Member):
await interaction.response.send_message("Use this command in a server.", ephemeral=True)
return
voice_state = interaction.user.voice
if voice_state is None or not isinstance(voice_state.channel, (discord.VoiceChannel, discord.StageChannel)):
await interaction.response.send_message("Join a voice channel first.", ephemeral=True)
return
channel = voice_state.channel
try:
voice_client = interaction.guild.voice_client
if voice_client is not None and voice_client.is_connected():
await voice_client.move_to(channel)
else:
await channel.connect(timeout=30, reconnect=True)
saved_channels[str(interaction.guild.id)] = channel.id
save_channels()
await interaction.response.send_message(f"Connected to **{channel.name}**. I’ll try to rejoin if I disconnect.", ephemeral=True)
except (discord.DiscordException, asyncio.TimeoutError, OSError):
logger.exception("Could not join voice channel %s", channel.id)
await interaction.response.send_message("I couldn’t join that voice channel. Check that I have permission to connect.", ephemeral=True)
@tree.command(name="leave", description="Leave voice and forget the saved channel")
async def leave(interaction: discord.Interaction) -> None:
if interaction.guild is None:
await interaction.response.send_message("Use this command in a server.", ephemeral=True)
return
saved_channels.pop(str(interaction.guild.id), None)
save_channels()
voice_client = interaction.guild.voice_client
if voice_client is not None:
await voice_client.disconnect(force=True)
await interaction.response.send_message("Disconnected and cleared the saved voice channel.", ephemeral=True)
@tree.command(name="replace-message", description="Delete a linked message and replace it with a notice")
@app_commands.describe(message_link="Link to the message you want to replace")
@app_commands.checks.has_permissions(manage_messages=True)
async def replace_message(interaction: discord.Interaction, message_link: str) -> None:
if interaction.guild is None:
await interaction.response.send_message("Use this command in a server.", ephemeral=True)
return
match = re.fullmatch(
r"https?://(?:www\.)?(?:discord\.com|discordapp\.com)/channels/(\d+)/(\d+)/(\d+)/?",
message_link.strip(),
)
if match is None:
await interaction.response.send_message("That doesn’t look like a valid Discord message link.", ephemeral=True)
return