You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py中!maps命令参数异常:无法正确生成图片URL

问题解决:Discord机器人!maps命令生成正确图片URL

问题根源

你的f-string语法使用错误:f-string不支持{0}、{1}这类索引式占位符(那是.format()的专属用法),直接写{0}会被当成字符串字面量输出,导致生成的URL里出现0和1,而非实际的命令参数。

修复方案

args是接收命令参数的元组,你需要直接通过索引获取对应参数值,再插入到f-string中:

将第10行的f-string语句修改为:

await ctx.channel.send(f'https://ants-api.qwq.xyz/static/antmaps/{args[0]}/{args[0]}.{args[1]}.png')

另外建议增加参数长度判断,避免用户只输入一个参数时触发索引错误,在else块开头补充:

if len(args) < 2:
    await ctx.channel.send("请输入完整的Rod和druh参数!")
    return

完整修改后的代码片段

@bot.command(brief="test")
async def maps(ctx, *args):
    if not args:
        await ctx.channel.send("Nenapsal jsi Rod/ Rod a druh! \nVysvětlivka:")
        await ctx.channel.send(
            "https://cdn.discordapp.com/attachments/661985293834125342/808308254081417227/acz_map_command.png"
        )

    else:
        if len(args) < 2:
            await ctx.channel.send("请输入完整的Rod和druh参数!")
            return
        await ctx.channel.send('Mapa výskytu: *{}*'.format(
            ' '.join(args).capitalize()))
        await ctx.channel.send(f'https://ants-api.qwq.xyz/static/antmaps/{args[0]}/{args[0]}.{args[1]}.png')
        await ctx.channel.send('AntWiki: *{}*'.format(
            ' '.join(args).capitalize()))
        await ctx.channel.send(
            'https://antwiki.org/wiki/{}'.format(
                '_'.join(args).capitalize()))

说明

  • 当用户输入!maps Common ant时,会生成目标URL:https://ants-api.qwq.xyz/static/antmaps/Common/Common.ant.png
  • 新增的参数长度判断可防止用户输入参数不足时抛出IndexError异常,提升机器人健壮性

内容的提问来源于stack exchange,提问作者Jakub Šidlík

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 23:05:22