itsmeniijii

Make me a discord bot that can message in a server and direct messages too with a simple command

Kodari AI
KodariSep 4 at 1:36 am 1
DualMessengerBot
A Discord bot that responds to commands in both server channels and direct messages. Users trigger the bot with a simple command prefix, and the bot replies with a confirmation message in the same context where the command was issued. The bot handles both guild-based messages and private DMs seamlessly, using Discord's API to detect message context and route responses accordingly. Includes basic command parsing, error handling for missing permissions, and logging for message activity.

Created a Discord bot with:

  • !say <message> — sends a message in the current server channel.

  • !dm @user <message> — sends a direct message.

  • Permission checks requiring Manage Messages.

  • Error handling and logging.

  • .env token configuration.

  • Setup instructions in README.md.

Files created:

  • bot.py

  • requirements.txt

  • .env.example

  • README.md

itsmeniijii

Using the slash commands instead of ! or ?

Kodari AI
KodariSep 4 at 2:16 am 1

Converted the bot to slash commands:

  • /say message:<text> — sends a message in the current server channel.

  • /dm member:<user> message:<text> — sends a direct message to a server member.

  • Removed the old ! command handling.

  • Added automatic global slash-command syncing.

  • Updated setup instructions and removed unnecessary privileged intents.

itsmeniijii

Remove the history of who used the command when using the say command

Kodari AI
KodariSep 4 at 2:22 am 1

Updated /say so:

  • The message is posted as a standalone bot message in the server channel.

  • The confirmation is ephemeral and only visible to the command user.

  • The bot does not log or store who used the command.

Discord’s built-in “user used /say” interaction history cannot be deleted or hidden by bots.

itsmeniijii

Make it able to join vc using a command and still not able to be seen by who used the command

Kodari AI
KodariSep 4 at 2:42 am 1
  1. Add /joinvc to join or move to the invoking member’s voice channel.

  2. Keep the command response ephemeral so nothing is posted publicly in the text channel.

  3. Add the voice dependency and setup permissions to the README.

Added /joinvc:

  • Joins the voice channel you are currently in.

  • Moves the bot if it is already connected elsewhere.

  • Sends no public text-channel message.

  • Uses an ephemeral confirmation.

  • Requires Manage Messages and the bot’s Connect permission.

  • Added PyNaCl, required for voice support.

Discord does not allow bots to hide the fact that a slash command was invoked from the invoking user’s own command history.

itsmeniijii

Make it able to reply to a message in a server

Kodari AI
KodariSep 4 at 2:58 pm 1
  1. Add a /reply slash command that replies to a server message by message ID or Discord message link.

  2. Keep the command’s confirmation ephemeral while the bot’s reply appears as a normal threaded Discord reply.

  3. Document the new command.

Added /reply as a slash command.

Usage:

Plain Text
/reply message_id:<message ID or Discord message link> reply_message:<your reply>

The bot will:

  • Reply directly to the specified server message.

  • Accept either a message ID or copied Discord message link.

  • Keep the confirmation visible only to the command user.

  • Reject messages from other servers.

  • Require Manage Messages permission.

itsusniijii

Make it able to stay in VC 24/7

Kodari AI
KodariTue at 11:19 pm 3

I’ll save the selected voice channel and reconnect after restarts or disconnects, while keeping /joinvc confirmations private.

/joinvc now remembers the selected channel and attempts to reconnect after a disconnect or bot restart. Its confirmation remains private.

The bot must be hosted and running to stay connected; Discord or network interruptions may still cause brief disconnects.

itsusniijii

fix the /joinvc as it keeps disconnecting "discord.errors.connection.closed: shard ID none websocket closed with 4017"

Kodari AI
KodariTue at 11:31 pm 2

I’ll update the voice dependencies for Discord’s current encryption protocol and fix /joinvc handling of stale connections.

Updated the bot to use discord.py’s current voice encryption support and reconnect stale voice sessions.

Restart or redeploy the bot so the updated dependencies install. /joinvc confirmations remain private.

Kodari can make mistakes. Review important code before using.
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