Discord.py Check if Channel is a DM
I am creating a command that i only want to be executable through a DM with the bot. The current code makes it possible to send the command to any channel, i want to prevent this.
@client.command()
async def check(ctx, arg):
if discord.ChannelType.private:
await ctx.send(arg)
I've also tried: discord.ChannelType == discord.ChannelType.private & discord.DMChannel
In discord.py, direct message channel objects come from class discord.channel.DMChannel
. We can check if an object comes from a class using isinstance()
:
@client.command()
async def check(ctx, arg):
if isinstance(ctx.channel, discord.channel.DMChannel):
await ctx.send(arg)
Add a dm_only
check:
@client.command()
@commands.dm_only()
async def check(ctx, arg):
await ctx.send(arg)
You could try:
@client.command()
async def check(ctx, arg):
if ctx.guild is False:
await ctx.send(arg)
I use discord.py version 1.3.3 and if ctx.guild is False:
doesn't work for me.
In my opinion you should use the discord class discord.ChannelType, that's what it is there for.
The following code works for me
@client.command()
async def check(ctx, arg):
if ctx.channel.type is discord.ChannelType.private:
await ctx.send(arg)