realatmoz

It's a bot that saves a backup of the server from the channels and roles and everything in the server and updates every day and if major changes like many channels have been deleted, it asks the staff for confirmation to save. And each server is given a code, so if the server is destroyed, you can make a new server and invite it then run a command with the server code and it rebuilds all data from that server here and it has a file filled with messages which you can view if you want if you need to. And there's also a feature that tracks all existing members before a huge change like a raided server and it sends the invite to all members from the original server to the new server. Each backup has an ID which is displayed in the logs each time the backup is apllied. It has a /guide command which shows a guide on how to setup and a /setup command which sets up the bot to work on the server, it asks for options like Logs channel which lets the bot show the safe confirmation screens, then roles that can manage the save (set working default for all admins on a server), then the gap between auto back ups, that's all the options needed for setup command. The /backup command will show an embed with a confirmation screen listing all changes since last backup and asks are you sure and if you click yes, it adds it to the backup. /server_token (only works for admins) which displays the Server token which the bot uses for you to use the backup on another server. /clone [server ID], [invite all previous members recorded: yes/no] which lets you clone the backup into another server. /invite all which invites back all members who left since last backup. And /restore [backup id] which rewinds a change. Is it possible for you to make it? <redacted> is the token.

Kodari AI
KodariSep 13 at 2:52 pm 2
ServerVault
A Discord bot that automatically backs up server structure (channels, roles, members) daily. Each backup gets a unique ID, and major changes trigger staff confirmation before saving. Servers receive a token for cross-server cloning via /clone, with optional member reinvitation. Includes /setup for configuration, /backup to review changes, /restore to rewind, /invite_all to re-invite departed members, and /guide for instructions.
  1. Create the Discord bot, SQLite persistence, snapshot/restore engine, and slash-command workflow.

  2. Add secure environment/config files and documentation for setup, backups, cloning, restoring, and member invitations.

  3. Keep the exposed token out of the project; rotate it in the Discord Developer Portal before running the bot.

Implemented the Discord server backup bot from scratch.

  • Added SQLite persistence for settings, backups, server tokens, and member tracking.

  • Added /guide, /setup, /backup, /server_token, /clone, /restore, and /invite_all.

  • Added automatic scheduled backups with configurable intervals.

  • Added confirmation prompts for manual backups, cloning, and destructive restores.

  • Added server structure snapshots for roles, categories, channels, permissions, and recent readable messages.

  • Added member departure tracking and optional recovery invitations.

  • Added .env.example, .gitignore, requirements.txt, and setup documentation.

The token you provided is exposed and should be revoked immediately in the Discord Developer Portal. Generate a new token, place it in .env, enable the Server Members Intent, and run:

Shell
pip install -r requirements.txt
python bot.py
Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
config.py
database.py
README.md
requirements.txt
snapshots.py
Code
7 946
bot.py
from __future__ import annotations

import asyncio
import logging
import secrets
from datetime import datetime, timezone
from typing import Awaitable, Callable

import discord
from discord import app_commands
from discord.ext import commands, tasks

import config
from database import Database
from snapshots import apply_snapshot, create_snapshot, summarize_changes

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
log = logging.getLogger("backup-bot")

intents = discord.Intents.none()
intents.guilds = True
intents.members = True


class BackupBot(commands.Bot):
    def __init__(self) -> None:
        super().__init__(command_prefix="!", intents=intents)
        self.db = Database(config.DATABASE_PATH)

    async def setup_hook(self) -> None:
        await self.db.initialize()
        await self.tree.sync()
        self.automatic_backups.start()

    async def close(self) -> None:
        self.automatic_backups.cancel()
        await self.db.close()
        await super().close()

    @tasks.loop(minutes=15)
    async def automatic_backups(self) -> None:
        now = datetime.now(timezone.utc)
        for settings in await self.db.list_settings():
            guild = self.get_guild(settings["guild_id"])
            if guild is None:
                continue
            latest = await self.db.get_latest_backup(guild.id)
            if latest:
                created = datetime.fromisoformat(latest["created_at"])
                if (now - created).total_seconds() < settings["backup_interval_hours"] * 3600:
                    continue
            try:
                snapshot = await create_snapshot(guild)
                changes = summarize_changes(latest["snapshot"] if latest else None, snapshot)
                backup_id = await self.db.insert_backup(
                    guild.id, now.isoformat(), "automatic", snapshot, changes
                )
                await send_log(
                    guild,
                    f"Automatic backup **#{backup_id}** saved.\n" + "\n".join(changes[:8]),
                )
            except (discord.Forbidden, discord.HTTPException) as error:
                log.warning("Automatic backup failed for %s: %s", guild.id, error)

    @automatic_backups.before_loop
    async def before_automatic_backups(self) -> None:
        await self.wait_until_ready()


bot = BackupBot()


def now_iso() -> str:
    return datetime.now(timezone.utc).isoformat()


async def send_log(guild: discord.Guild, content: str) -> None:
    settings = await bot.db.get_settings(guild.id)
    if not settings or not settings["logs_channel_id"]:
        return
    channel = guild.get_channel(settings["logs_channel_id"])
    if isinstance(channel, discord.TextChannel):
        try:
            await channel.send(content)
        except (discord.Forbidden, discord.HTTPException):
            log.info("Could not write to configured log channel in %s", guild.id)


async def manager_allowed(interaction: discord.Interaction) -> bool:
    if interaction.guild is None or not isinstance(interaction.user, discord.Member):
        await interaction.response.send_message("This command can only be used in a server.", ephemeral=True)
        return False
    settings = await bot.db.get_settings(interaction.guild.id)
    if settings is None:
        await interaction.response.send_message(
            "Run `/setup` first. Server administrators can use it without prior setup.", ephemeral=True
        )
        return False
    member = interaction.user
    if member.guild_permissions.administrator:
        return True
    manager_role_id = settings["manager_role_id"]
    if manager_role_id and any(role.id == manager_role_id for role in member.roles):
        return True
    await interaction.response.send_message("You are not allowed to manage backups.", ephemeral=True)
    return False


class ConfirmationView(discord.ui.View):
    def __init__(
        self,
        owner_id: int,
        confirm_callback: Callable[[discord.Interaction], Awaitable[None]],
    ) -> None:
        super().__init__(timeout=120)
        self.owner_id = owner_id
        self.confirm_callback = confirm_callback

    async def interaction_check(self, interaction: discord.Interaction) -> bool:
        if interaction.user.id != self.owner_id:
            await interaction.response.send_message("Only the person who started this action can confirm it.", ephemeral=True)
            return False
        return True

    @discord.ui.button(label="Confirm", style=discord.ButtonStyle.danger)
    async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
        button.disabled = True
        await self.confirm_callback(interaction)
        self.stop()

    @discord.ui.button(label="Cancel", style=discord.ButtonStyle.secondary)
    async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
        await interaction.response.edit_message(content="Cancelled.", embed=None, view=None)
        self.stop()


@bot.event
async def on_ready() -> None:
    log.info("Logged in as %s (%s)", bot.user, bot.user.id if bot.user else "unknown")
    for guild in bot.guilds:
        for member in guild.members:
            await bot.db.upsert_member(guild.id, member.id, str(member), now_iso())


@bot.event
async def on_member_join(member: discord.Member) -> None:
    await bot.db.upsert_member(member.guild.id, member.id, str(member), now_iso())


@bot.event
async def on_member_remove(member: discord.Member) -> None:
    await bot.db.mark_member_left(member.guild.id, member.id, now_iso())


@bot.tree.command(name="guide", description="Show the backup bot setup guide")
async def guide(interaction: discord.Interaction) -> None:
    embed = discord.Embed(
        title="Server Backup Guide",
        description=(
            "1. An administrator runs `/setup`.\n"
            "2. Choose a logs channel, an optional manager role, and the automatic backup interval.\n"
            "3. Use `/backup` for a reviewed manual backup. Automatic backups run on the configured schedule.\n"
            "4. Use `/server_token` to obtain the recovery token. Keep it private.\n"
            "5. In a replacement server, run `/clone` with the source token or server ID.\n"
            "6. `/restore` rebuilds a server from one of its own backup IDs after confirmation.\n"
            "7. `/invite_all` sends a temporary invite by DM to recorded members who left."
        ),
        color=discord.Color.blurple(),
    )
    embed.set_footer(text="Discord permissions and user DM settings can limit restoration and invitations.")
    await interaction.response.send_message(embed=embed, ephemeral=True)


@bot.tree.command(name="setup", description="Configure backup logs, managers, and automatic backups")
@app_commands.describe(
    logs_channel="Channel for backup confirmation and activity logs",
    manager_role="Optional role allowed to manage backups; administrators always retain access",
    backup_interval_hours="Automatic backup interval from 1 to 168 hours",
)
async def setup(
    interaction: discord.Interaction,
    logs_channel: discord.TextChannel,
    backup_interval_hours: float,
    manager_role: discord.Role | None = None,
) -> None:
    if interaction.guild is None or not isinstance(interaction.user, discord.Member):
        await interaction.response.send_message("This command can only be used in a server.", ephemeral=True)
        return
    if not interaction.user.guild_permissions.administrator:
        await interaction.response.send_message("Only server administrators can run setup.", ephemeral=True)
        return
    if not 1 <= backup_interval_hours <= 168:
        await interaction.response.send_message("The backup interval must be between 1 and 168 hours.", ephemeral=True)
        return

    current = await bot.db.get_settings(interaction.guild.id)
    server_token = current["server_token"] if current else secrets.token_urlsafe(24)