簡體   English   中英

Discord.py 檢查Channel是否為DM

[英]Discord.py Check if Channel is a DM

我正在創建一個我只想通過帶有機器人的 DM 執行的命令。 當前代碼可以將命令發送到任何通道,我想防止這種情況。

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

我也試過: discord.ChannelType == discord.ChannelType.private & discord.DMChannel

在 discord.py 中,直接消息通道對象來自class discord.channel.DMChannel 我們可以使用isinstance()檢查 object 是否來自 class :

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

添加dm_only檢查:

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

你可以試試:

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

我使用 discord.py 版本 1.3.3 並且if ctx.guild is False:對我不起作用。 在我看來,您應該使用 discord class discord.ChannelType ,這就是它的用途。 以下代碼適用於我

@client.command()
async def check(ctx, arg):
    if ctx.channel.type is discord.ChannelType.private:
        await ctx.send(arg)
@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

#use this code if you are using @client.event 
import discord

@client.event
async def on_message(message):
  if message.author == client.user:
    return
  if message.content.startswith("register"):
    if isinstance(message.channel, discord.DMChannel):
      await message.author.send("registration mode coming soon!")
  else:
    await message.channel.send("pls register in bot dm")
client.run(bot token)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM