Dee Nesh

Hey I want you to create discord bot which uses/dmall <message>:message to send , <role>:roles in srv including @everyone , show_server_name: true/false , show_sender_name: true/false and when executed sends a message inside embed like this working invite link inside it and etc with following discord guidelines but able to dm every user in dc server personal message it's for a social research/YouTube video can you make it working

1 image attached
Kodari AI
KodariOct 17 at 4:31 pm 1
DiscordMassDMer
A Discord bot that sends personalized direct messages to every member of a server. Triggered via slash command with a message parameter, it iterates through all server members, optionally filtering by roles (including @everyone), and delivers each user a unique embed containing a working invite link. Features configurable options to display server name and sender name within the embed, adhering to Discord's rate limits and guidelines. Built for social research and YouTube content, it includes safety delays between DMs to prevent spam flags.
  1. Create a discord.py bot with /dmall and an embedded message containing a server invite.

  2. Limit delivery to members who explicitly opt in; add /dmoptin and /dmoptout, admin confirmation, and send pacing.

  3. Add the dependencies and .env template.

Created the bot with /dmall, /dmoptin, and /dmoptout. /dmall previews an embed with a seven-day server invite and asks for admin confirmation before sending. It targets only members who opted in; omit the role filter to include all opted-in members, or select a role to narrow the audience. It won’t send unsolicited DMs to every server member.

To run it, install requirements.txt and copy .env.example to .env, then add your bot token. In the Discord Developer Portal, enable Server Members Intent under Bot β†’ Privileged Gateway Intents. The bot also needs Create Invite permission in a text channel to add the invite link.

Dee Nesh

Hey idh privileged gateway intents make it work without it and change bot.py code and add this and make it work without ownership just any administration role import discord from discord.ext import commands import asyncio import json import os from datetime import datetime, timedelta

with open("config.json", "r", encoding="utf-8") as f: config = json.load(f)

TOKEN = config["token"] PREFIX = config["prefix"] DEFAULT_MESSAGE = config["default_message"]

intents = discord.Intents.all() bot = commands.Bot(command_prefix=PREFIX, intents=intents, help_command=None)

required_keys = ["token", "prefix"] for key in required_keys: if key not in config or not config[key].strip(): raise ValueError(f"Missing or empty config key: {key}")

@bot.event async def on_ready(): print(f"βœ… Logged in as {bot.user} ({bot.user.id})") print(f"πŸ‘‘ xrszav: Type {PREFIX}help for commands.")

@bot.event async def on_command_error(ctx, error): if isinstance(error, commands.MissingPermissions): await ctx.send("🚫 You don't have permission to use this command.") elif isinstance(error, commands.MissingRequiredArgument): await ctx.send(f"⚠️ Missing argument: {error.param.name}") elif isinstance(error, commands.CommandNotFound): pass elif isinstance(error, commands.BotMissingPermissions): await ctx.send("⚠️ I’m missing permissions to do that.") elif isinstance(error, commands.CheckFailure): await ctx.send("❌ You failed a check to run this command.") else: await ctx.send("❗ An unexpected error occurred. Check console for more info.") raise error

@bot.command(name='help', aliases=['commands'], description="Show all available commands or details about a specific command") async def custom_help(ctx, *, command_name: str = None): """Show all available commands or details about a specific command""" if command_name: # Show help for a specific command command = bot.get_command(command_name.lower()) if not command: return await ctx.send(f"❌ Command {command_name} not found. Use {PREFIX}help to see all commands.")

embed = discord.Embed( title=f"ℹ️ {command.name.capitalize()} Command Help", color=discord.Color.blue() )

embed.add_field( name="Description", value=command.help or "No description available", inline=False )

if command.aliases: embed.add_field( name="Aliases", value=", ".join(f"{alias}" for alias in command.aliases), inline=False )

embed.add_field( name="Usage", value=f"{PREFIX}{command.name} {command.signature}" if command.signature else f"{PREFIX}{command.name}", inline=False )

return await ctx.send(embed=embed)

# Show general help menu embed = discord.Embed( title="πŸ“š DM Bot Help Menu", description=f"Use {PREFIX}help <command> for more info on a specific command", color=discord.Color.blue() )

# DM Commands dm_commands = [ ("dm", "Send a DM to a specific user"), ("dmpreview", ":new: Preview a DM by sending it to yourself"), ("dmall", "Mass DM all server members"), ("dmallsafe", ":new: Slow, safer mass DM all server members"), ("dmroleall", "DM all members with a specific role"), ("dmroleallsafe", ":new: Slow, safer DM all members with a role"), ("dmretry", "Retry failed DMs from a previous campaign") ] embed.add_field( name="πŸ“¨ DM Commands", value="\n".join(f"β€’ {cmd[0]} - {cmd[1]}" for cmd in dm_commands), inline=False )

# Log Management log_commands = [ ("getlog", "Download DM log files"), ("dmstatus", "Show status of last DM campaign"), ("dmstats", "Show DM statistics"), ("clearlogs", "Delete old log files") ] embed.add_field( name="πŸ“‚ Log Management", value="\n".join(f"β€’ {cmd[0]} - {cmd[1]}" for cmd in log_commands), inline=False )

# Additional Info embed.add_field( name="ℹ️ Additional Information", value=( f"β€’ Prefix: {PREFIX}\n" "β€’ All commands require administrator permissions\n" "β€’ The bot automatically creates logs for all DM campaigns" ), inline=False )

embed.set_footer(text="xrszav's DM Bot | https://oblivity.xyz | https://xrszav.xyz") await ctx.send(embed=embed)

@bot.command(name='dm', description="Send a DM to a specific user") @commands.has_permissions(administrator=True) async def dm(ctx, member: discord.Member, *, custom_message=None): message = custom_message or DEFAULT_MESSAGE if not message.strip(): await ctx.send("❌ No default message set | ❌ No message was sent. Please provide a message.") return

if member.bot: await ctx.send("❌ You cannot DM bots.") return

try: await member.send(message) await ctx.send(f"βœ… DM sent to {member.name}") except Exception as e: await ctx.send(f"❌ Failed to DM {member.name}: {e}")

@bot.command(name='dmpreview', aliases=['previewdm'], description="Preview a DM by sending it to yourself") @commands.has_permissions(administrator=True) async def dmpreview(ctx, *, custom_message=None): message = custom_message or DEFAULT_MESSAGE if not message.strip(): await ctx.send("❌ No default message set | ❌ No message was sent. Please provide a message.") return

try: await ctx.author.send(message) await ctx.send(f"βœ… Preview DM sent to {ctx.author.name}.") except Exception as e: await ctx.send(f"❌ Failed to send preview DM: {e}")

@bot.command(name='dmall', aliases=['massdm', 'dmallusers'], description="Mass DM all server members") @commands.has_permissions(administrator=True) async def dmall(ctx, *, custom_message=None): members = [m for m in ctx.guild.members if not m.bot] total = len(members) if total == 0: await ctx.send("❌ No valid users to DM.") return

message = custom_message or DEFAULT_MESSAGE if not message.strip(): await ctx.send("❌ No default message set | ❌ No message was sent. Please provide a message.") return

sent = 0 failed = 0 report_every = max(1, total // 100) pause_every = 20 cooldown_duration = 300

timestamp = datetime.now().strftime("%d%m%Y_%H%M%S")

log_file_success = f"dm_success_{timestamp}.txt" log_file_failed = f"dm_failed_{timestamp}.txt"

with open(log_file_success, "w", encoding="utf-8") as f: f.write("βœ… DMed Users:\n") with open(log_file_failed, "w", encoding="utf-8") as f: f.write("❌ Failed DMs:\n")

await ctx.send( f"πŸ“€ Starting to DM {total} users...\n" f"⏱ Progress every {report_every} users, cooldown every {pause_every} users.\n" f"πŸ“ Success log: {log_file_success}\n" f"πŸ›‘ Failed log: {log_file_failed}" )

for idx, member in enumerate(members, start=1): try: await member.send(message) sent += 1 with open(log_file_success, "a", encoding="utf-8") as f: f.write(f"{member.name}#{member.discriminator} | {member.id}\n") except Exception as e: failed += 1 print(f"❌ Failed to DM {member.name}: {e}") with open(log_file_failed, "a", encoding="utf-8") as f: f.write(f"{member.name}#{member.discriminator} | {member.id} | Error: {e}\n")

if idx % report_every == 0: embed = discord.Embed( title="πŸ“¬ DM Progress Update", description=f"Progress: {idx}/{total} users", color=discord.Color.blurple() ) embed.add_field(name="βœ… Sent", value=str(sent)) embed.add_field(name="❌ Failed", value=str(failed)) await ctx.send(embed=embed)

if idx % pause_every == 0: await ctx.send(f"πŸ•’ Cooling down for 5 minutes after {idx} users...") await asyncio.sleep(cooldown_duration)

await asyncio.sleep(1)

final_embed = discord.Embed( title="βœ… DM Campaign Completed", description=f"All {total} users processed.", color=discord.Color.green() ) final_embed.add_field(name="βœ… Total Sent", value=str(sent), inline=True) final_embed.add_field(name="❌ Total Failed", value=str(failed), inline=True) final_embed.add_field(name="πŸ“„ Logs", value=f"Success: {log_file_success}\nFailed: {log_file_failed}", inline=False) await ctx.send(embed=final_embed)

@bot.command(name='dmallsafe', aliases=['massdmsafe', 'slowdmall'], description="Slow, safer mass DM all server members") @commands.has_permissions(administrator=True) async def dmall_safe(ctx, *, custom_message=None): members = [m for m in ctx.guild.members if not m.bot] total = len(members) if total == 0: await ctx.send("❌ No valid users to DM.") return

message = custom_message or DEFAULT_MESSAGE if not message.strip(): await ctx.send("❌ No default message set | ❌ No message was sent. Please provide a message.") return

sent = 0 failed = 0 report_every = max(1, total // 100) short_delay = 4 medium_pause_every = 15 medium_pause = 90 long_pause_every = 40 long_pause = 240 extra_pause_every = 100 extra_pause = 480

timestamp = datetime.now().strftime("%d%m%Y_%H%M%S") log_file_success = f"dm_success_slow_{timestamp}.txt" log_file_failed = f"dm_failed_slow_{timestamp}.txt"

with open(log_file_success, "w", encoding="utf-8") as f: f.write("βœ… Slowly DMed Users:\n") with open(log_file_failed, "w", encoding="utf-8") as f: f.write("❌ Slowly Failed DMs:\n")

await ctx.send( f"🐒 Starting safe slow DM of {total} users...\n" f"⏱ Progress every {report_every} users, longer cooldowns to reduce rate limit risk.\n" f"πŸ“ Success log: {log_file_success}\n" f"πŸ›‘ Failed log: {log_file_failed}" )

for idx, member in enumerate(members, start=1): try: await member.send(message) sent += 1 with open(log_file_success, "a", encoding="utf-8") as f: f.write(f"{member.name}#{member.discriminator} | {member.id}\n") except Exception as e: failed += 1 print(f"❌ Failed to DM {member.name}: {e}") with open(log_file_failed, "a", encoding="utf-8") as f: f.write(f"{member.name}#{member.discriminator} | {member.id} | Error: {e}\n")

if idx % report_every == 0: embed = discord.Embed( title="πŸ“¬ Slow DM Progress Update", description=f"Progress: {idx}/{total} users", color=discord.Color.blurple() ) embed.add_field(name="βœ… Sent", value=str(sent)) embed.add_field(name="❌ Failed", value=str(failed)) await ctx.send(embed=embed)

if idx % extra_pause_every == 0: await ctx.send(f"πŸ•’ Extra cooldown: waiting {extra_pause} seconds after {idx} users...") await asyncio.sleep(extra_pause) elif idx % long_pause_every == 0: await ctx.send(f"πŸ•’ Long cooldown: waiting {long_pause} seconds after {idx} users...") await asyncio.sleep(long_pause) elif idx % medium_pause_every == 0: await ctx.send(f"πŸ•’ Medium cooldown: waiting {medium_pause} seconds after {idx} users...") await asyncio.sleep(medium_pause)

await asyncio.sleep(short_delay)

final_embed = discord.Embed( title="βœ… Safe Slow DM Campaign Completed", description=f"All {total} users processed.", color=discord.Color.green() ) final_embed.add_field(name="βœ… Total Sent", value=str(sent), inline=True) final_embed.add_field(name="❌ Total Failed", value=str(failed), inline=True) final_embed.add_field(name="πŸ“„ Logs", value=f"Success: {log_file_success}\nFailed: {log_file_failed}", inline=False) await ctx.send(embed=final_embed)

@dmall.error async def dmall_error(ctx, error): if isinstance(error, commands.MissingPermissions): await ctx.send("❌ You need administrator permissions to use this command.") else: await ctx.send(f"❌ Error: {error}")

@bot.command(name='dmstatus', description="Show status of last DM campaign") @commands.has_permissions(administrator=True) async def dmstatus(ctx): success_files = [f for f in os.listdir() if f.startswith("dm_success_")] failed_files = [f for f in os.listdir() if f.startswith("dm_failed_")]

if not success_files and not failed_files: await ctx.send("❌ No DM log files found. Please run a DM campaign first.") return

success_files.sort(reverse=True) failed_files.sort(reverse=True)

latest_success_file = success_files[0] if success_files else None latest_failed_file = failed_files[0] if failed_files else None

total_sent = 0 total_failed = 0

if latest_success_file: try: with open(latest_success_file, "r", encoding="utf-8") as f: success_lines = f.readlines() total_sent = len(success_lines) - 1 except Exception as e: await ctx.send(f"❌ Error reading the success log: {e}")

if latest_failed_file: try: with open(latest_failed_file, "r", encoding="utf-8") as f: failed_lines = f.readlines() total_failed = len(failed_lines) - 1 except Exception as e: await ctx.send(f"❌ Error reading the failed log: {e}")

total_users = total_sent + total_failed

status_embed = discord.Embed( title="πŸ“Š DM Status", description="Current status of the DM campaign.", color=discord.Color.blue() ) status_embed.add_field(name="Total Users", value=str(total_users), inline=True) status_embed.add_field(name="βœ… Successful DMs", value=str(total_sent), inline=True) status_embed.add_field(name="❌ Failed DMs", value=str(total_failed), inline=True) status_embed.add_field(name="πŸ“ Success Log", value=f"{latest_success_file}" if latest_success_file else "N/A", inline=False) status_embed.add_field(name="πŸ›‘ Failed Log", value=f"{latest_failed_file}" if latest_failed_file else "N/A", inline=False)

await ctx.send(embed=status_embed)

@bot.command(name='dmretry', aliases=['dmallcontinue', 'retrydm', 'dmfailures'],description="Retry DMs for users who failed in the last campaign") @commands.has_permissions(administrator=True) async def dmallcontinue(ctx, *, filepath=None): if not filepath: await ctx.send("❌ Please provide the path to the success log file. Example: !dmallcontinue dm_success_01042025_153000.txt") return

try: with open(filepath, "r", encoding="utf-8") as f: lines = f.readlines() except FileNotFoundError: await ctx.send(f"❌ File {filepath} not found.") return

successful_ids = set() for line in lines: if "|" in line: parts = line.strip().split("|") if len(parts) >= 2: try: user_id = int(parts[1].strip()) successful_ids.add(user_id) except ValueError: continue

members = [m for m in ctx.guild.members if not m.bot and m.id not in successful_ids] total = len(members)

if total == 0: await ctx.send("❌ All users in the server have already been DM'd.") return

message = DEFAULT_MESSAGE sent = 0 failed = 0 timestamp = datetime.now().strftime("%d%m%Y_%H%M%S") retry_log_success = f"dm_retry_success_{timestamp}.txt" retry_log_failed = f"dm_retry_failed_{timestamp}.txt"

with open(retry_log_success, "w", encoding="utf-8") as f: f.write("βœ… Retried & DMed Users:\n") with open(retry_log_failed, "w", encoding="utf-8") as f: f.write("❌ Retried & Failed DMs:\n")

await ctx.send( f"πŸ” Retrying DM for {total} users from {filepath}...\n" f"πŸ“ Retry success log: {retry_log_success}\n" f"πŸ›‘ Retry failed log: {retry_log_failed}" )

for idx, member in enumerate(members, start=1): try: await member.send(message) sent += 1 with open(retry_log_success, "a", encoding="utf-8") as f: f.write(f"{member.name}#{member.discriminator} | {member.id}\n") except Exception as e: failed += 1 print(f"❌ Retry failed to DM {member.name}: {e}") with open(retry_log_failed, "a", encoding="utf-8") as f: f.write(f"{member.name}#{member.discriminator} | {member.id} | Error: {e}\n")

await asyncio.sleep(1)

final_embed = discord.Embed( title="πŸ” DM Retry Completed", description=f"Retried DM for {total} users.", color=discord.Color.orange() ) final_embed.add_field(name="βœ… Retried & Sent", value=str(sent), inline=True) final_embed.add_field(name="❌ Retried & Failed", value=str(failed), inline=True) final_embed.add_field(name="πŸ“„ Logs", value=f"Success: {retry_log_success}\nFailed: {retry_log_failed}", inline=False) await ctx.send(embed=final_embed)

@bot.command(name='getlog', aliases=['downloadlog', 'log'],description="Download specific log file or list all available logs") @commands.has_permissions(administrator=True) async def get_log(ctx, filename: str = None): """ Download specific log file or list all available logs Usage: !getlog [filename] or just !getlog to list all logs """ # Get all log files all_logs = [f for f in os.listdir() if f.startswith(("dm_success_", "dm_failed_", "dm_retry_"))] all_logs.sort(reverse=True) # Sort by newest first

if not all_logs: await ctx.send("❌ No log files found.") return

# If no filename specified, show list of all logs if filename is None: embed = discord.Embed( title="πŸ“œ Available Log Files", description="Use !getlog filename to download a specific file", color=discord.Color.blue() )

# Split logs into success and failed categories success_logs = [f for f in all_logs if "success" in f] failed_logs = [f for f in all_logs if "failed" in f]

if success_logs: embed.add_field( name="βœ… Success Logs", value="\n".join(f"{f}" for f in success_logs), inline=False )

if failed_logs: embed.add_field( name="❌ Failed Logs", value="\n".join(f"{f}" for f in failed_logs), inline=False )

await ctx.send(embed=embed) return

# Check if requested file exists if filename not in all_logs: await ctx.send(f"❌ File {filename} not found. Use !getlog to see available files.") return

# Send the requested file try: await ctx.send(f"πŸ“„ Here's your log file: {filename}", file=discord.File(filename)) except Exception as e: await ctx.send(f"❌ Error sending file: {e}")

@get_log.error async def get_log_error(ctx, error): if isinstance(error, commands.MissingPermissions): await ctx.send("❌ You need administrator permissions to use this command.") else: await ctx.send(f"❌ Error: {error}")

@bot.command(name='clearlogs', aliases=['purgelogs'], description="Delete log files older than X days (default: 30)") @commands.has_permissions(administrator=True) async def clear_logs(ctx, days: int = 30): """Delete log files older than X days

Kodari AI
KodariOct 17 at 4:52 pm 1

Plan: use default intents only; resolve current members from saved opt-ins via individual lookups; keep /dmall restricted to users with the Administrator permission, regardless of ownership.

Updated bot.py to use default intents only and look up members individually, so it no longer requires the Members privileged intent. /dmall is available to anyone with Discord’s Administrator permission, not just the server owner.

It still sends only to members who opted in with /dmoptin; it won’t mass-DM everyone unsolicited.

Dee Nesh

Hey I wanna make this bot like when /small send everyone personal message and success and failed don't send bots using the code I gaved you and don't use privileged intent I don't have it unlocked make it work without that things and send everyone dms and remove cooldown completey

Kodari AI
KodariOct 17 at 4:56 pm 1
  1. Rename the admin announcement command to /small.

  2. Keep DMs limited to users who explicitly opted in; fetch opted-in users without privileged intents and skip bots.

  3. Remove the campaign cooldown while preserving the existing confirmation, delivery results, and per-message delay.

/small now sends a personal DM to opted-in users, skips bots, and reports delivered and failed counts. The campaign cooldown is removed; the existing one-second spacing between DMs remains to help avoid Discord rate limits.

It uses no privileged intents. It can’t DM every server member without enumerating them, so members must opt in with /dmoptin and can stop messages with /dmoptout.

Kodari can make mistakes. Review important code before using.
Files
bot.py
requirements.txt
Code
2 296
bot.py
import asyncio
import json
import logging
import os
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional

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("dmall_bot")

OPT_INS_PATH = Path("optins.json")
SEND_DELAY_SECONDS = 1.0


def load_opt_ins() -> dict[int, set[int]]:
    try:
        saved = json.loads(OPT_INS_PATH.read_text(encoding="utf-8"))
        return {int(guild_id): {int(user_id) for user_id in user_ids}
                for guild_id, user_ids in saved.items()}
    except FileNotFoundError:
        return {}
    except (OSError, json.JSONDecodeError, TypeError, ValueError):
        logger.exception("Could not load opt-in data")
        return {}


opt_ins = load_opt_ins()
opt_ins_lock = asyncio.Lock()


async def save_opt_ins() -> None:
    serialized = {str(guild_id): sorted(user_ids) for guild_id, user_ids in opt_ins.items()}
    OPT_INS_PATH.write_text(json.dumps(serialized, indent=2), encoding="utf-8")


intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)


def make_announcement_embed(
    guild: discord.Guild,
    sender: discord.abc.User,
    message: str,
    invite_url: str,
    show_server_name: bool,
    show_sender_name: bool,
) -> discord.Embed:
    title = f"πŸ“¬ Message from {guild.name}" if show_server_name else "πŸ“¬ Announcement"
    server_label = guild.name if show_server_name else ""
    description = f"{message}\n\n[Join {server_label or 'the server'}]({invite_url})"
    embed = discord.Embed(title=title[:256], description=description, color=discord.Color.blurple())

    footer_parts = []
    if show_sender_name:
        footer_parts.append(f"Sent by {sender.display_name}")
    if show_server_name:
        footer_parts.append(guild.name)
    footer_parts.append(datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"))
    embed.set_footer(text=" β€’ ".join(footer_parts)[:2048])
    return embed


async def create_server_invite(guild: discord.Guild) -> str:
    bot_member = guild.me
    if bot_member is None:
        raise RuntimeError("The bot could not find its member in this server.")

    for channel in guild.text_channels:
        permissions = channel.permissions_for(bot_member)
        if permissions.view_channel and permissions.create_instant_invite:
            invite = await channel.create_invite(
                max_age=604800,
                max_uses=0,
                reason="Include a server invite in an opted-in announcement",
            )
            return invite.url
    raise RuntimeError("I need Create Invite permission in a text channel to include a working invite link.")


class ConfirmDmView(discord.ui.View):
    def __init__(
        self,
        guild: discord.Guild,
        sender: discord.Member,
        recipients: list[discord.User],
        message: str,
        show_server_name: bool,
        show_sender_name: bool,
    ) -> None:
        super().__init__(timeout=60)
        self.guild = guild
        self.sender = sender
        self.recipients = recipients
        self.message_text = message
        self.show_server_name = show_server_name
        self.show_sender_name = show_sender_name
        self.preview_message: Optional[discord.Message] = None

    async def on_timeout(self) -> None:
        if self.preview_message is not None:
            self.disable_all_items()
            try:
                await self.preview_message.edit(view=self)
            except discord.HTTPException:
                pass

    @discord.ui.button(label="Confirm and send", style=discord.ButtonStyle.primary)
    async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
        if interaction.user.id != self.sender.id:
            await interaction.response.send_message("Only the admin who started this can confirm.", ephemeral=True)
            return

        self.disable_all_items()
        self.stop()
        await interaction.response.defer(ephemeral=True, thinking=True)
        if interaction.message is not None:
            try:
                await interaction.message.edit(view=self)
            except discord.HTTPException:
                pass

        try:
            invite_url = await create_server_invite(self.guild)
        except (discord.Forbidden, discord.HTTPException, RuntimeError) as error:
            logger.warning("Could not create an invite for guild %s: %s", self.guild.id, error)
            await interaction.followup.send(str(error), ephemeral=True)
            return

        embed = make_announcement_embed(
            self.guild,
            self.sender,
            self.message_text,
            invite_url,
            self.show_server_name,
            self.show_sender_name,
        )
        sent = 0
        failed = 0
        for recipient in self.recipients:
            try:
                await recipient.send(embed=embed, allowed_mentions=discord.AllowedMentions.none())
                sent += 1
            except (discord.Forbidden, discord.HTTPException) as error:
                failed += 1
                logger.info("Could not DM user %s in guild %s: %s", recipient.id, self.guild.id, error)
            await asyncio.sleep(SEND_DELAY_SECONDS)

        await interaction.followup.send(
            f"Announcement finished. Delivered: **{sent}** β€’ Could not deliver: **{failed}**.",
            ephemeral=True,
        )


@bot.event
async def on_ready() -> None:
    try:
        synced = await bot.tree.sync()
        logger.info("Synced %d application commands", len(synced))
    except discord.HTTPException:
        logger.exception("Could not sync application commands")
    logger.info("Logged in as %s", bot.user)
    print("KODARI_READY", flush=True)


@bot.tree.command(name="dmoptin", description="Opt in to server announcements by direct message")
@app_commands.guild_only()
async def dmoptin(interaction: discord.Interaction) -> None:
    async with opt_ins_lock:
        members = opt_ins.setdefault(interaction.guild_id, set())
        members.add(interaction.user.id)
        try:
            await save_opt_ins()
        except OSError:
            logger.exception("Could not save opt-in data")
            await interaction.response.send_message("I couldn't save your opt-in. Please try again later.", ephemeral=True)
            return
    await interaction.response.send_message(
        "You're opted in to server announcements by DM. Use `/dmoptout` any time to stop them.",
        ephemeral=True,
    )


@bot.tree.command(name="dmoptout", description="Stop receiving server announcements by direct message")
@app_commands.guild_only()
async def dmoptout(interaction: discord.Interaction) -> None:
    async with opt_ins_lock:
        members = opt_ins.setdefault(interaction.guild_id, set())
        members.discard(interaction.user.id)
        try:
            await save_opt_ins()
        except OSError:
            logger.exception("Could not save opt-out data")