Files
bot.py
README.md
requirements.txt
Code
3 263
bot.py
import asyncio
import json
import logging
import os
import re
import discord
from discord.ext import commands, tasks
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("message-bot")
intents = discord.Intents.default()
bot = commands.Bot(command_prefix=commands.when_mentioned, intents=intents)
voice_channels = {}
voice_lock = asyncio.Lock()
try:
with open("voice_channels.json", encoding="utf-8") as file:
voice_channels = json.load(file)
except FileNotFoundError:
pass
except (OSError, ValueError):
logger.exception("Could not load saved voice channels")
@tasks.loop(seconds=30)
async def maintain_voice():
async with voice_lock:
for guild_id, channel_id in list(voice_channels.items()):
guild = bot.get_guild(int(guild_id))
if guild is None:
continue
channel = guild.get_channel(int(channel_id))
if not isinstance(channel, (discord.VoiceChannel, discord.StageChannel)):
continue
client = guild.voice_client
try:
if client and not client.is_connected():
await client.disconnect(force=True)
client = None
if client is None:
await channel.connect(timeout=20, reconnect=True)
elif client.channel != channel:
await client.move_to(channel)
except (discord.DiscordException, asyncio.TimeoutError, OSError):
logger.exception("Could not restore voice connection for guild %s", guild_id)
@maintain_voice.before_loop
async def before_maintain_voice():
await bot.wait_until_ready()
async def send_error(interaction: discord.Interaction, message: str):
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)
else:
await interaction.response.send_message(message, ephemeral=True)
@bot.event
async def setup_hook():
await bot.tree.sync()
maintain_voice.start()
@bot.event
async def on_ready():
logger.info("Logged in as %s (ID: %s)", bot.user, bot.user.id)
print("KODARI_READY", flush=True)
@bot.tree.command(name="say", description="Send a message in this server channel.")
@discord.app_commands.guild_only()
@discord.app_commands.checks.has_permissions(manage_messages=True)
@discord.app_commands.describe(message="The message to send")
async def say(interaction: discord.Interaction, message: str):
"""Send a message in the current server channel."""
await interaction.response.defer(ephemeral=True)
await interaction.channel.send(message)
await interaction.followup.send("Message sent.", ephemeral=True)
@bot.tree.command(name="dm", description="Send a direct message to a server member.")
@discord.app_commands.guild_only()
@discord.app_commands.checks.has_permissions(manage_messages=True)
@discord.app_commands.describe(member="The server member to message", message="The message to send")
async def dm(interaction: discord.Interaction, member: discord.Member, message: str):
"""Send a direct message to a server member."""
try:
await member.send(message)
except discord.Forbidden:
await interaction.response.send_message(
f"I couldn't send a DM to {member.mention}.", ephemeral=True
)
return
await interaction.response.send_message(
f"Direct message sent to {member.mention}.", ephemeral=True
)
@bot.tree.command(name="joinvc", description="Join your current voice channel.")
@discord.app_commands.guild_only()
@discord.app_commands.checks.has_permissions(manage_messages=True)
async def joinvc(interaction: discord.Interaction):
"""Join the invoking member's current voice channel without a public reply."""
voice_state = interaction.user.voice
if voice_state is None or voice_state.channel is None:
await interaction.response.send_message(
"You must be in a voice channel to use this command.", ephemeral=True
)
return
channel = voice_state.channel
await interaction.response.defer(ephemeral=True)
try:
async with voice_lock:
voice_client = interaction.guild.voice_client
if voice_client and not voice_client.is_connected():
await voice_client.disconnect(force=True)
voice_client = None
if voice_client is None:
await channel.connect(timeout=20, reconnect=True)
elif voice_client.channel != channel:
await voice_client.move_to(channel)
voice_channels[str(interaction.guild.id)] = channel.id
with open("voice_channels.json", "w", encoding="utf-8") as file:
json.dump(voice_channels, file)
except (discord.DiscordException, asyncio.TimeoutError, OSError):
logger.exception("Could not join or save voice channel")
await interaction.followup.send(
"I couldn't join that voice channel. Check that I have permission to connect.",
ephemeral=True,
)
return
await interaction.followup.send(
f"Joined {channel.mention}.", ephemeral=True
)
@bot.tree.command(name="reply", description="Reply to a message in this server.")
@discord.app_commands.guild_only()
@discord.app_commands.checks.has_permissions(manage_messages=True)
@discord.app_commands.describe(
message_id="The message ID or Discord message link to reply to",
reply_message="The reply to send",
)
async def reply(
interaction: discord.Interaction, message_id: str, reply_message: str
):
"""Reply to a server message without posting the command publicly."""
match = re.search(r"/channels/(\d+)/(\d+)/(\d+)", message_id)
if match:
guild_id, channel_id, target_message_id = map(int, match.groups())
if guild_id != interaction.guild.id:
await interaction.response.send_message(
"The message must be from this server.", ephemeral=True
)
return
target_channel = interaction.guild.get_channel(channel_id)
if target_channel is None:
try:
target_channel = await bot.fetch_channel(channel_id)
except (discord.NotFound, discord.Forbidden, discord.HTTPException):
target_channel = None
else:
target_channel = interaction.channel
try:
target_message_id = int(message_id)
except ValueError:
await interaction.response.send_message(
"Provide a valid message ID or Discord message link.", ephemeral=True
)
return
if target_channel is None or getattr(target_channel, "guild", None) != interaction.guild:
await interaction.response.send_message(
"I couldn't find that message in this server.", ephemeral=True
)
return
try:
target_message = await target_channel.fetch_message(target_message_id)
await target_message.reply(reply_message)
except discord.NotFound:
await interaction.response.send_message(
"I couldn't find that message.", ephemeral=True
)
return