簡體   English   中英

如何使 discord.py 機器人不接受來自 dms 的命令

[英]how to make a discord.py bot not accepts commands from dms

如何讓 discord.py 機器人不響應來自機器人 DM 的命令? 我只希望機器人在特定服務器上的特定頻道上響應消息。

如果您只想回復特定頻道上的消息並且您知道該頻道的名稱,則可以執行以下操作:

channel = discord.utils.get(ctx.guild.channels, name="channel name")
channel_id = channel.id

然后,您將檢查 id 是否與您希望它所在的一個頻道匹配。要獲取頻道或服務器的 id,您需要啟用discord developer mode 之后,您只需右鍵單擊服務器或頻道並復制 ID。

要獲取服務器的 id,您需要將這段代碼添加為命令:

@client.command(pass_context=True)
async def getguild(ctx):
    id = ctx.message.guild.id # the guild is the server
    # do something with the id (print it out)

獲得服務器 ID 后,您可以刪除該方法。

要檢查消息是由人還是機器人發送的,您可以在 on_message 方法中執行此操作:

def on_message(self, message):
    if (message.author.bot):
        # is a bot
        pass

因此,為了使機器人不響應 DM,請在每個命令后添加此代碼:

if message.guild:
  # Message comes from a server.
else:
  # Message comes from a DM.

這樣可以更好地將 DM 與服務器消息分開。 您剛才必須移動“await message.channel.send”function。

我假設您正在要求一個只聽您的命令的機器人。 好吧,在這種情況下,您可以創建一個檢查以查看消息是否由您發送。 可以使用,

@client.event
async def on_message(message):
if message.author.id == <#your user id>:
    await message.channel.send('message detected')
    ...#your code

你可以使用最簡單和最好的方法

@bot.command()
async def check(ctx):
    if not isinstance(ctx.channel, discord.channel.DMChannel):
       Your Work...

暫無
暫無

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

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