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

Discord.py机器人仅单个命令生效问题求助

问题原因

你定义了两个on_message事件处理函数,Discord.py中同一个事件的多个装饰器定义会导致后定义的覆盖先定义的,所以只有最后一个对应$status的on_message生效,$help的逻辑被完全覆盖,自然没有响应。

修复方案

有两种可行的修复方式,根据需求选择:

方式一:合并到同一个on_message事件

把两个命令的逻辑放到同一个on_message函数里,用条件判断区分命令,同时建议加上机器人自我消息过滤(避免机器人响应自己发送的消息):

import discord
import os
from discord.ext.commands import Cog
from discord.ext.commands import command, has_permissions, has_role
import sqlite3
from mcstatus import JavaServer

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    # 过滤机器人自身消息,避免循环触发
    if message.author == client.user:
        return
    
    if message.content.startswith('$help'):
        # 替换为你原本的embed代码
        embed = discord.Embed(title="帮助菜单", description="可用命令:\n$help - 查看帮助\n$status <服务器IP> - 查询MC服务器在线人数")
        await message.channel.send(embed=embed) 
    elif message.content.startswith('$status'):
        a = message.content.split(" ", 1)
        # 增加参数格式校验
        if len(a) < 2:
            await message.channel.send("请输入正确格式:$status <服务器IP>")
            return
        ip = a[1]
        try:
            server = JavaServer.lookup(ip)
            status = server.status()
            await message.channel.send(f"当前服务器在线人数:{status.players.online}")
        except Exception as e:
            await message.channel.send(f"查询失败:{str(e)}")

client.run(TOKEN)

方式二:改用commands.Bot框架(推荐)

你已经导入了discord.ext.commands相关模块,改用这个框架更规范,命令之间不会冲突,还能自动处理前缀、参数解析等:

import discord
from discord.ext import commands
import sqlite3
from mcstatus import JavaServer

# 设置命令前缀为$,并启用必要的Intents
bot = commands.Bot(command_prefix='$', intents=discord.Intents.default())

@bot.event
async def on_ready():
    print('We have logged in as {0.user}'.format(bot))

@bot.command()
async def help(ctx):
    # 替换为你原本的embed代码
    embed = discord.Embed(title="帮助菜单", description="可用命令:\n$help - 查看帮助\n$status <服务器IP> - 查询MC服务器在线人数")
    await ctx.send(embed=embed)

@bot.command()
async def status(ctx, ip: str):
    try:
        server = JavaServer.lookup(ip)
        status = server.status()
        await ctx.send(f"当前服务器在线人数:{status.players.online}")
    except Exception as e:
        await ctx.send(f"查询失败:{str(e)}")

bot.run(TOKEN)

注意:使用commands.Bot需要确保在Discord开发者后台的Bot选项中开启了Message Content Intent,否则机器人无法读取消息内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:15:50