首页 > 解决方案 > Discord bot上的功能已定义错误

问题描述

通过添加新命令从第一个 Discord 机器人构建。在创建第二个命令时,我之前在代码中收到错误“函数已定义”,即使它位于不同的标题下。

@client.command()
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('!hello'):
        msg = 'Hello {0.author.mention}'.format(message)
        await client.send_message(message.channel, msg)

My first command above, worked fine.

@client.command()
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('!roll'):
        msg = 'So, {0.author.mention} you rolled for a {}'.format(random.randint(1,20))
        await client.send_message(message.channel, msg)

第二个有一个错误,说之前已经在第 10 行定义了异步(在第一个函数中)

标签: pythondiscord

解决方案


通过使用def,您正在定义一个函数。一个函数必须是唯一的,并且不能用相同的名称定义两次。

解决办法可以

@client.command()
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('!hello'):
        msg = 'Hello {0.author.mention}'.format(message)
        await client.send_message(message.channel, msg)
    elif message.content.startswith('!roll'):
        msg = 'So, {0.author.mention} you rolled for a {}'.format(random.randint(1,20))
        await client.send_message(message.channel, msg)

推荐阅读