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

Discord.py机器人切换Slash命令后不响应,请求技术排查

Discord机器人无响应问题排查与Slash命令迁移方案

一、现有前缀命令失效的核心原因

你代码中定义了两个on_message事件处理函数,discord.py只会执行最后一个定义的函数,导致第一个on_message里的await client.process_commands(message)未被调用,所有前缀命令($date、$cours等)完全无法触发,这就是机器人无响应的直接原因。

修复方法:合并on_message函数

将两个on_message的逻辑整合为一个,同时处理彩蛋和前缀命令:

@client.event
async def on_message(message):
    # 忽略机器人自身发送的消息
    if message.author == client.user:
        return
    
    # 处理42彩蛋逻辑
    if message.content.startswith('42'):
        embedVar = discord.Embed(
            title="42",
            description="La solution à la grande question sur la vie, l'univers , et le reste, assurément...",
            color=0x3853B4)
        await message.channel.send(embed=embedVar)
    
    # 处理前缀命令
    await client.process_commands(message)

二、迁移到Slash命令的完整步骤

要实现Slash命令,需使用discord.py的app_commands模块(Command Tree),以下是具体实现方案:

1. 导入必要模块

在代码开头添加:

from discord import app_commands

2. 改写为Slash命令格式

将原有前缀命令替换为Slash命令,适配交互对象:

# Slash版/date命令
@client.tree.command(name="date", description="Afficher la date du jour")
async def slash_date(interaction: discord.Interaction):
    todaydate = date.today()
    d1 = todaydate.strftime("%d/%m/%Y")
    await interaction.response.send_message(f'Nous sommes le {d1}')

# Slash版/cours命令,带参数校验
@client.tree.command(name="cours", description="Afficher l'emploi du temps pour aujourd'hui ou demain")
@app_commands.describe(jour="Choisissez 'today' ou 'demain'")
async def slash_cours(interaction: discord.Interaction, jour: str):
    jour = jour.lower()
    if jour == 'today':
        await display_courses_slash(interaction, date.today())
    elif jour == 'demain':
        await display_courses_slash(interaction, date.today() + timedelta(days=1))
    else:
        await interaction.response.send_message(
            "Argument non reconnu. Utilisez 'today' ou 'demain'."
        )

# 适配Slash命令的课程展示函数
async def display_courses_slash(interaction: discord.Interaction, target_date):
    courses = []
    horaires = []
    locations = []

    e = open('Agenda/groupeD.ics', 'rb')
    ecal = Calendar.from_ical(e.read())

    todaydate = target_date
    d2 = todaydate.strftime("%Y%m%d")
    datejour = todaydate.strftime("%d/%m/%Y")

    for event in ecal.walk('VEVENT'):
        Aevent = event.get("DTSTART")
        step = Aevent.dt
        d3 = step.strftime("%Y%m%d")
        horaire = step.strftime("%Hh%M")
        location = event.get("LOCATION")

        if d3 == d2:
            courses.append(event.get("SUMMARY"))
            horaires.append(horaire)
            locations.append(location)

    e.close()

    embedVar = discord.Embed(title=f"Emploi du temps {datejour}",
                            description=f"{'Aujourd\'hui' if target_date == date.today() else 'Demain'} vous avez : ",
                            color=0x3853B4)
    if len(courses) > 0:
        embedVar.add_field(name=courses[0],
                           value=f"{horaires[0]} en **{locations[0].lower()}**",
                           inline=False)
        if len(courses) > 1:
            embedVar.add_field(name=courses[1],
                               value=f"{horaires[1]} en **{locations[1].lower()}**",
                               inline=False)
    else:
        embedVar.add_field(name="Pas de cours",
                           value=f"Aucun cours pour {datejour}.",
                           inline=False)

    await interaction.response.send_message(embed=embedVar)

# Slash版/ping命令
@client.tree.command(name="ping", description="Vérifier la latence du bot")
async def slash_ping(interaction: discord.Interaction):
    await interaction.response.send_message(f'Pong! {round(client.latency * 1000)}ms')

3. 同步Slash命令

在on_ready事件中添加命令同步逻辑,优先选择服务器内同步(生效快,适合测试):

@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')
    # 替换为你的服务器ID(整数类型)
    guild = discord.Object(id=VOTRE_GUILD_ID)
    # 将全局命令同步到指定服务器
    client.tree.copy_global_to(guild=guild)
    await client.tree.sync(guild=guild)
    # 若需要全局同步,删除上面两行,仅保留:await client.tree.sync()
    print("Slash命令已同步")

4. 权限配置

在Discord开发者平台的OAuth2->URL Generator中,勾选applications.commands权限,重新生成邀请链接并邀请机器人到服务器。

三、部署注意事项

在Repl.it上部署时,确保discord.py、icalendar等依赖已正确安装;UptimeRobot的监控链接保持正常,避免机器人离线。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 04:47:03