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

开发支持老式MUD表情功能的Discord机器人相关问题求助

问题修复方案

现有代码的问题

  • 缩进错误:Python 强制要求函数内的代码缩进4个空格,你写的if/else逻辑完全没有缩进,会直接报语法错误无法运行
  • 触发者信息缺失:指定了目标用户的分支里,没有拼接触发指令的用户昵称,和你要的输出格式不符
  • 昵称兜底逻辑缺失:ctx.author.nickname仅在用户设置了服务器专属昵称时才有值,未设置的情况下会返回None导致报错,应该用ctx.author.display_name自动优先取昵称、没有就取用户名
  • 拼写错误:wierdo正确拼写为weirdo

修复后的代码

@bot.command()
async def prod(ctx, *, user: discord.Member = None):
    sender = ctx.author.display_name
    if user:
        await ctx.send(f"{sender} prods {user.mention} in the ribs, ouch")
    else:
        await ctx.send(f"{sender} prods themselves, what a weirdo")

批量扩展表情指令的方案

如果要加smile、swing这类大量同类指令,不用重复写函数,直接用配置字典统一管理模板即可:

# 配置所有表情指令的模板,key是指令名,value第一个元素是无目标模板,第二个是有目标模板
emote_templates = {
    "smile": [
        "{} smiles",
        "{} smiles at {}"
    ],
    "swing": [
        "{} swings around in a circle like a fool",
        "{} grabs {} by the hands and swings them around in a circle, weeee"
    ],
    "prod": [
        "{} prods themselves, what a weirdo",
        "{} prods {} in the ribs, ouch"
    ]
}

# 批量注册指令
for cmd_name, templates in emote_templates.items():
    @bot.command(name=cmd_name)
    async def emote_handler(ctx, *, user: discord.Member = None, templates=templates):
        sender = ctx.author.display_name
        if user:
            await ctx.send(templates[1].format(sender, user.mention))
        else:
            await ctx.send(templates[0].format(sender))

后续要加新的表情指令,只需要在emote_templates里加对应的键值对就行,不用额外写逻辑。

内容的提问来源于stack exchange,提问作者Bruce Taylor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 17:45:03