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

如何让discord.py机器人自动执行自身命令?

解决discord.py机器人重启后无法触发支持命令的问题

你的代码里用channel.send("sec>support-info")无法触发命令,核心原因是discord.py默认会忽略机器人自身发送的消息,所以机器人不会监听自己发的命令文本。

下面是两种可行的解决办法:

方法一:直接调用命令核心逻辑(推荐)

把命令的业务逻辑抽成独立函数,在on_ready里直接调用,不需要通过发送消息触发。这样既高效又能避免消息循环问题。

示例代码:

# 抽离支持信息的核心发送逻辑
async def send_support_message(channel: discord.TextChannel):
    # 这里写你原本在support-info命令里的逻辑
    await channel.send("这是支持系统的相关信息:xxx")

# 斜杠命令调用核心函数
@bot.tree.command(name="support-info")
async def support_info(interaction: discord.Interaction):
    await send_support_message(interaction.channel)
    await interaction.response.send_message("支持信息已发送到当前频道")

@bot.event
async def on_ready():
    print("Bot is ready!")
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command(s)")
        channel = bot.get_channel(999949771735306282)
        # 直接调用核心函数发送支持信息
        await send_support_message(channel)
    except Exception as err:
        print(err)

方法二:允许机器人处理自身消息

如果必须通过发送命令文本触发,需要修改on_message事件,取消对自身消息的忽略。但要注意做好逻辑判断,避免机器人无限触发自己的命令。

示例代码:

@bot.event
async def on_message(message):
    # 处理机器人自己发送的消息
    if message.author == bot.user:
        # 判断是否是目标命令
        if message.content == "sec>support-info":
            # 执行支持信息发送逻辑
            await message.channel.send("这是支持系统的相关信息:xxx")
        # 必须调用process_commands才能处理其他命令
        await bot.process_commands(message)
    else:
        await bot.process_commands(message)

@bot.event
async def on_ready():
    print("Bot is ready!")
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command(s)")
        channel = bot.get_channel(999949771735306282)
        await channel.send("sec>support-info")
    except Exception as err:
        print(err)

优先推荐方法一,因为直接调用函数的方式更可控,不会引入不必要的消息监听开销,也能避免潜在的循环触发问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:06:00