Hey everyone! I’m working on my Discord bot and I was wondering if it’s possible to make it respond to commands sent via direct messages. I’m particularly interested in creating a command that would allow me to unban myself from all servers the bot is in.
I’m not sure where to start with this. I’ve tried searching online, but it’s hard to find specific info because terms like “discord.py”, “command”, and “DM” are so common.
What I’m looking for is:
A way for the bot to recognize DMs as commands
A method to make it only accept commands from me (my ID is stored in ownerID)
If possible, some guidance on creating that unban command
Here’s a sample of how my bot currently handles commands:
@bot.command()
async def roll_dice(ctx, sides: int):
if ctx.author.guild_permissions.send_messages or ctx.author.id == ownerID:
result = random.randint(1, sides)
await ctx.send(f'You rolled a {result} on a {sides}-sided die!')
else:
await ctx.send(f'Sorry {ctx.author.mention}, you can't use this command.')
I’ve actually implemented DM commands in my bot before. It’s totally doable, but requires a bit of tweaking to your existing setup. Instead of using @bot.command(), you’ll want to use the on_message event handler. This allows you to process messages regardless of where they come from.
For the owner-only commands, I’d recommend creating a separate function to check if the message author is you. Something like:
Then in your on_message event, you can do something like:
if message.guild is None and is_owner(message):
# Process DM command here
As for the unban command, you’d need to iterate through all the guilds the bot is in and call the unban method for each. Just be cautious with this kind of power!
I’ve implemented DM commands for bots before, and it’s definitely possible. You’ll need to use the on_message event instead of @bot.command() decorators. Here’s a basic structure:
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if isinstance(message.channel, discord.DMChannel) and message.author.id == ownerID:
if message.content.startswith('!unban'):
for guild in bot.guilds:
try:
await guild.unban(message.author)
await message.channel.send(f'Unbanned from {guild.name}')
except:
await message.channel.send(f'Failed to unban from {guild.name}')
await bot.process_commands(message)
This checks if the message is a DM and from the owner, then processes the command. Be careful with the unban command though – it’s quite powerful!
yeah, discord bots can deff respond to DMs! you’ll wanna use the on_message event instead of @bot.command() for DMs. check if message.guild is None to know its a DM. for the unban thing, you’d need to loop thru all the bot’s servers and call unban() for each. be careful with that tho!