如何在Discord.py中接收和发送消息到特定频道?

问题描述 投票:0回答:2

我正在开发一个命令,机器人会用

!name Barty
响应
Hello Barty

@bot.command()
async def name(ctx, arg):
  await ctx.send(f"hello {arg}")

但是,我面临的问题是机器人在任何频道中都会响应

!name foo
,而我只希望它在某些频道中响应。

我尝试过:

@bot.event
async def on_message(message):
  if message.channel.id == 1234567:
    @bot.command()
    async def name(ctx, arg):
      await ctx.send(f"hello {arg}")

这不起作用,我没有主意。

如何向给定通道发送命令并从中获取响应?

python discord discord.py
2个回答
5
投票

将定义代码移出 IF 语句:

@bot.command()
async def name(ctx, args):
    await ctx.send("hello {}".format(args)

当你做到了这一点,你应该能够做到;

if (message.channel.id == 'channel id'): 
    await message.channel.send('message goes here')

else:
    # handle your else here, such as null, or log it to ur terminal

还可以查看文档:https://discordpy.readthedocs.io

一旦发出命令,请在其中创建 IF 语句。


2
投票

message.channel.id 现在需要是整数,而不是字符串,因此您不需要使用 ''

    if (message.channel.id == 1234567): 
      await message.channel.send('message goes here')

  else:
    # handle your else here, such as null, or log in to ur terminal
© www.soinside.com 2019 - 2024. All rights reserved.