Files
bot.py
config.json
requirements.txt
Code
3 289
bot.py
import json
import logging
import os
from pathlib import Path
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("update_relay")
CONFIG_PATH = Path("config.json")
def load_relays():
try:
data = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
configured = data.get("relays", {})
if not isinstance(configured, dict):
raise ValueError("The 'relays' config value must be an object")
return {str(int(source)): int(target) for source, target in configured.items()}
except FileNotFoundError:
return {}
except (json.JSONDecodeError, TypeError, ValueError) as error:
logger.error("Could not read %s: %s", CONFIG_PATH, error)
return {}
def save_relays(relays):
CONFIG_PATH.write_text(
json.dumps({"relays": relays}, indent=2) + "\n",
encoding="utf-8",
)
def split_message(text, limit=2000):
chunks = []
while len(text) > limit:
split_at = text.rfind("\n", 0, limit + 1)
if split_at <= 0:
split_at = limit
chunks.append(text[:split_at])
text = text[split_at:].lstrip("\n")
if text:
chunks.append(text)
return chunks
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
relays = load_relays()
relay_group = app_commands.Group(name="relay", description="Manage update relays")
commands_synced = False
@relay_group.command(name="add", description="Relay a channel into another server's channel")
@app_commands.describe(
source_channel_id="Text channel ID in the server where you run this command",
destination_channel_id="Destination text channel ID; the bot must be in that server",
)
@app_commands.default_permissions(manage_guild=True)
@app_commands.checks.has_permissions(manage_guild=True)
async def relay_add(
interaction: discord.Interaction,
source_channel_id: app_commands.Range[int, 1],
destination_channel_id: app_commands.Range[int, 1],
):
await interaction.response.defer(ephemeral=True)
try:
source = await bot.fetch_channel(source_channel_id)
destination = await bot.fetch_channel(destination_channel_id)
except discord.NotFound:
await interaction.followup.send("I couldn't find one of those channels.", ephemeral=True)
return
except discord.Forbidden:
await interaction.followup.send("I don't have access to one of those channels.", ephemeral=True)
return
except discord.HTTPException:
logger.exception("Failed to look up relay channels")
await interaction.followup.send("Discord couldn't load those channels. Try again shortly.", ephemeral=True)
return
supported_channels = (discord.TextChannel, discord.Thread)
if not isinstance(source, supported_channels) or not isinstance(destination, supported_channels):
await interaction.followup.send("Both channels must be text channels or threads.", ephemeral=True)
return
if interaction.guild_id != source.guild.id:
await interaction.followup.send(
"Run this command in the server that contains the source channel.",
ephemeral=True,
)
return
source_bot_member = source.guild.me
destination_bot_member = destination.guild.me
if source_bot_member is None or destination_bot_member is None:
await interaction.followup.send("The bot must be in both servers.", ephemeral=True)
return
source_permissions = source.permissions_for(source_bot_member)
destination_permissions = destination.permissions_for(destination_bot_member)
if not source_permissions.view_channel or not source_permissions.read_message_history:
await interaction.followup.send(
"I need View Channel and Read Message History in the source channel.",
ephemeral=True,
)
return
can_send = (
destination_permissions.send_messages_in_threads
if isinstance(destination, discord.Thread)
else destination_permissions.send_messages
)
if not destination_permissions.view_channel or not can_send:
await interaction.followup.send(
"I need View Channel and permission to send messages in the destination.",
ephemeral=True,
)
return
updated_relays = dict(relays)
updated_relays[str(source.id)] = destination.id
try:
save_relays(updated_relays)
except OSError:
logger.exception("Could not save relay configuration")
await interaction.followup.send("I couldn't save that relay. Check the bot's file permissions.", ephemeral=True)
return
relays.clear()
relays.update(updated_relays)
await interaction.followup.send(
f"Now relaying **#{source.name}** from **{source.guild.name}** to **#{destination.name}** in **{destination.guild.name}**.",
ephemeral=True,
)
@relay_group.command(name="remove", description="Stop relaying a source channel")
@app_commands.describe(source_channel_id="Source channel ID to remove")
@app_commands.default_permissions(manage_guild=True)
@app_commands.checks.has_permissions(manage_guild=True)
async def relay_remove(interaction: discord.Interaction, source_channel_id: app_commands.Range[int, 1]):
if interaction.guild_id is None:
await interaction.response.send_message("Use this command in the source server.", ephemeral=True)
return
source = bot.get_channel(source_channel_id)
if source is not None and getattr(getattr(source, "guild", None), "id", None) != interaction.guild_id:
await interaction.response.send_message("That source channel isn't in this server.", ephemeral=True)
return
key = str(source_channel_id)
if key not in relays:
await interaction.response.send_message("There is no relay configured for that channel.", ephemeral=True)
return
updated_relays = dict(relays)
del updated_relays[key]
try:
save_relays(updated_relays)
except OSError:
logger.exception("Could not save relay configuration")
await interaction.response.send_message("I couldn't save that change. Try again later.", ephemeral=True)
return
relays.clear()
relays.update(updated_relays)
await interaction.response.send_message("Relay removed.", ephemeral=True)
@relay_group.command(name="list", description="Show relays configured from this server")
@app_commands.default_permissions(manage_guild=True)
@app_commands.checks.has_permissions(manage_guild=True)
async def relay_list(interaction: discord.Interaction):
if interaction.guild_id is None:
await interaction.response.send_message("Use this command in a server.", ephemeral=True)
return
entries = []
for source_id, destination_id in relays.items():
source = bot.get_channel(int(source_id))
if getattr(getattr(source, "guild", None), "id", None) != interaction.guild_id:
continue
destination = bot.get_channel(destination_id)
source_name = f"#{source.name}" if source else f"channel {source_id}"
destination_name = f"#{destination.name}" if destination else f"channel {destination_id}"
entries.append(f"{source_name} → {destination_name}")
message = "\n".join(entries) if entries else "No relays are configured from this server."
await interaction.response.send_message(message, ephemeral=True)