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

如何为自制Discord鼓励机器人添加自定义功能并修复代码问题

Discord鼓励机器人功能修复方案

原代码核心问题

  • 未对$new命令做触发判断,直接拆分消息取参数会在输入不符合格式时抛出索引越界错误
  • 删除函数名拼写错误:delete_encouragment应为delete_encouragement,拼写错误会直接触发函数未定义报错
  • 缺少参数合法性校验:用户删除时输入非数字、索引超出鼓励语列表范围都会导致程序崩溃
  • 多命令判断未做互斥,多余的判断逻辑会浪费运行资源
  • 鼓励语列表直接输出数组格式,用户查看体验差

修复后可运行代码

# $new 新增鼓励语逻辑
if msg.startswith("$new "):
    # 先判断拆分后是否有有效内容,避免索引报错
    msg_parts = msg.split("$new ", 1)
    if len(msg_parts) < 2 or not msg_parts[1].strip():
        await message.channel.send("请在$new后填写要添加的鼓励语内容")
        return
    encouraging_message = msg_parts[1].strip()
    update_encouragements(encouraging_message)
    await message.channel.send("新鼓励语添加成功")

# $del 删除鼓励语逻辑
elif msg.startswith("$del "):
    encouragements = db.get("encouragements", [])
    if not encouragements:
        await message.channel.send("当前还没有添加任何鼓励语")
        return
    # 校验输入的索引是否合法
    msg_parts = msg.split("$del ", 1)
    if len(msg_parts) < 2:
        await message.channel.send("请在$del后填写要删除的鼓励语序号")
        return
    try:
        index = int(msg_parts[1].strip())
    except ValueError:
        await message.channel.send("请输入有效的数字序号")
        return
    if index < 0 or index >= len(encouragements):
        await message.channel.send(f"序号无效,当前鼓励语序号范围是0到{len(encouragements)-1}")
        return
    delete_encouragement(index)
    encouragements = db["encouragements"]
    # 格式化输出列表
    output = "\n".join([f"{i}. {content}" for i, content in enumerate(encouragements)])
    await message.channel.send(f"删除成功,当前鼓励语列表:\n{output}")

# $list 查看鼓励语列表逻辑
elif msg.startswith("$list"):
    encouragements = db.get("encouragements", [])
    if not encouragements:
        await message.channel.send("当前还没有添加任何鼓励语")
        return
    output = "\n".join([f"{i}. {content}" for i, content in enumerate(encouragements)])
    await message.channel.send(f"当前鼓励语列表:\n{output}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 02:09:02