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

Discord机器人触发!命令时出现IndexError: String Index out of range错误

解决Discord机器人IndexError问题

问题根源

错误IndexError: string index out of range出现在if user_message[0] == '%':这一行,核心原因是当用户发送空消息(比如仅按回车、发送纯空白字符)时,user_message为空字符串,无法访问索引0。并非!hello命令本身有问题,只是空消息恰好触发了代码逻辑里的漏洞。

修复方案

在检查消息前缀之前,先过滤空消息或纯空白消息:
在on_message函数的日志打印语句后,添加判断逻辑,直接跳过空消息的处理:

if not user_message.strip():
    return

修改后的完整代码

import discord
import responses

async def send_message(message, user_message, is_private):
    try:
        response = responses.handle_response(user_message)
        await message.author.send(response) if is_private else await message.channel.send(response)
    except Exception as e:
        print(e)

def run_discord_bot():
    TOKEN = 'This is where the bots token would go'
    client = discord.Client(intents=discord.Intents.default())

    @client.event
    async def on_ready():
        print(f'{client.user} is now running!')

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

        username = str(message.author)
        user_message = str(message.content)
        channel = str(message.channel)

        print(f"{username} said: '{user_message}' ({channel})")

        # 新增:过滤空消息/纯空白消息,避免索引越界
        if not user_message.strip():
            return

        if user_message[0] == '%':
            user_message = user_message[1:]
            await send_message(message, user_message, is_private=True)
        else:
            await send_message(message, user_message, is_private=False)

    client.run(TOKEN)

额外优化建议

  • 可以把命令前缀(!和%)定义为常量,方便后续统一修改,比如:
    PUBLIC_PREFIX = '!'
    PRIVATE_PREFIX = '%'
    
    替换代码中硬编码的符号,提升代码可维护性。
  • 如果需要更灵活的命令解析(比如多前缀、参数处理),可以使用discord.ext.commands框架,它自带成熟的命令处理机制,能减少手动编写逻辑的漏洞。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:50:28