discord.py 如何制作一个在不同频道做不同事情的命令

时间:2021-06-10 19:37:59

标签: python discord discord.py

我正在制作一个游戏 Discord 机器人,它有不同的频道作为不同的“区域”,但我希望相同的命令根据使用的频道来做不同的事情。

这就是我现在所拥有的:

@client.command()
async def fish(ctx):
  author = ctx.message.author
  channel = ctx.message.channel
  if channel == 'pallet-town' or channel == 'viridian-city' or channel == 'route-4':
    await ctx.send(f"{author.mention}, do you want to use your old, good, or super rod?")
  else:
    await ctx.send('No water here!')

然而,这会返回“这里没有水!”即使我在上述渠道之一。有谁知道为什么会这样?我需要改用频道 ID 吗?

2 个答案:

答案 0 :(得分:2)

channel 是一个 discord.TextChannel 实例,您将它与字符串进行比较,这永远不会True,只需将 channel 转换为字符串:

async def fish(ctx):
    author = ctx.message.author
    channel = ctx.message.channel
    if str(channel) == 'pallet-town' or str(channel) == 'viridian-city' or str(channel) == 'route-4':
        await ctx.send(f"{author.mention}, do you want to use your old, good, or super rod?")
    else:
        await ctx.send('No water here!')

PS:你可以真正缩短代码:

if str(channel) in ["pallet-town", "viridian-city", "route-4"]:
    ...

答案 1 :(得分:1)

按照您当前配置的方式,您正在检查 Channel 对象是否等于字符串 'pallet-town' 等。您需要检查该对象的 .name 属性频道等于你的字符串。

您应该可以只替换该行:

channel = ctx.message.channel

与:

channel = ctx.message.channel.name