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

Python开发Discord Bot:启动指定频道发消息报错求助

问题解决:Discord Bot启动时发送指定消息到频道

错误原因

on_ready 是Discord Bot初始化完成后触发的事件,它本身没有ctx(上下文)参数。你给函数添加了ctx参数,但Discord.py调用这个事件时不会传递该参数,所以触发了「缺少必要位置参数ctx」的错误。另外,on_ready触发时Bot还未绑定任何频道上下文,你原来写的ctx.channel.id逻辑本身就不成立。

正确实现代码

先确保你已经定义好整数类型的status_channel_id(目标频道的ID),然后替换成以下代码:

@bot.event
async def on_ready():
    # 通过ID获取目标频道对象
    status_channel = bot.get_channel(status_channel_id)
    # 检查频道是否存在(避免ID错误或无权限导致报错)
    if status_channel:
        await status_channel.send("[WOL] : Working")
    print("Bot启动完成")

可选优化:避免重复发送消息

on_ready可能在Bot重连时被多次触发,如果不想重复发送启动消息,可以加个标记变量:

has_sent_start_msg = False

@bot.event
async def on_ready():
    global has_sent_start_msg
    if not has_sent_start_msg:
        status_channel = bot.get_channel(status_channel_id)
        if status_channel:
            await status_channel.send("[WOL] : Working")
            has_sent_start_msg = True
        print("Bot启动完成")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 18:52:06