Discord.py检查Channel是否为DM

时间:2019-11-22 04:45:20

标签: python discord.py

我正在创建一个命令,我只希望可以通过带有bot的DM执行该命令。当前代码可以将命令发送到任何通道,我想防止这种情况。

@client.command()
async def check(ctx, arg):
    if discord.ChannelType.private:
        await ctx.send(arg)

我也尝试过: discord.ChannelType == discord.ChannelType.private discord.DMChannel

5 个答案:

答案 0 :(得分:6)

在discord.py中,直接消息通道对象来自class discord.channel.DMChannel。我们可以使用isinstance()检查对象是否来自类:

@client.command()
async def check(ctx, arg):
    if isinstance(ctx.channel, discord.channel.DMChannel):
        await ctx.send(arg)

答案 1 :(得分:1)

添加dm_only支票:

@client.command()
@commands.dm_only()
async def check(ctx, arg):
    await ctx.send(arg)

答案 2 :(得分:0)

您可以尝试:

@client.command()
async def check(ctx, arg):
    if ctx.guild is False:
        await ctx.send(arg)

答案 3 :(得分:0)

我使用discord.py版本1.3.3,而createInstance()对我不起作用。 我认为您应该使用不和谐类discord.ChannelType,这就是它的用途。 以下代码对我有用

IllegalArgumentException

答案 4 :(得分:0)

@client.command()
async def check(ctx, arg):
    if str(ctx.type) == "private":
        await ctx.send(arg)

https://discordpy.readthedocs.io/en/latest/api.html#discord.ChannelType

相关问题