在Python中,如何声明在Discord bot中分离预期参数的对象?

2024-09-30 01:23:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在用python创建一个discord bot,并尝试为它提供创建一个字典的功能,其中包含要在我的MC服务器中传送到的所有坐标。用户应该输入!然后添加与坐标相对应的点的标题,然后添加discord聊天中的实际坐标,如下所示:

!add Main Building,-312 74 -31

我希望bot接受两个参数,并添加一个作为字典的键,另一个作为用逗号分隔的值,但是现在bot假设第一个参数以第一个空格结尾。上述命令将在字典中返回此值:

"Main": "House"

如何区分参数之间用逗号分隔

以下是我遇到问题的代码:

@bot.command(name='add', help='Adds TP Name and TP Coordinates')
async def roll(ctx, tpName, tpCoords):
    tps[tpName] = tpCoords
    tpGroup = [
        tpName
        ,tpCoords
    ]
    await ctx.send('Adding coordinates',': '.join(tpGroup), "to the TP coordinate list")

Tags: 功能服务器add参数字典mainbotmc
2条回答

添加一个名为*的参数,这样两个参数内部都可以有空格,没有问题,不需要逗号

一个选项是基于函数中的逗号来解析参数

假设定义了tps dict,您可以尝试以下操作:

另外,ctx.send()需要格式化的消息

@bot.command(name='add', help='Adds TP Name and TP Coordinates')
async def roll(ctx, *, info_in=None):
    if not info_in or ',' not in info_in:
        await ctx.send('Please include coordinates in correct format')
        return
    tpName = info_in.split(',')[0]
    tpCoords = info_in.split(',')[1].lstrip()
    tps[tpName] = tpCoords
    tpGroup = [
        tpName
        , tpCoords
    ]
    msg = 'Adding coordinates' + ': '.join(tpGroup) + " to the TP coordinate list"
    await ctx.send(msg)

结果:

enter image description here

相关问题 更多 >

    热门问题