Discord机器人加载JSON配置异常:无法发送上线消息至指定频道
Discord机器人就绪消息发送失败排查与解决
一、先排查JSON文件加载逻辑
- 重点检查ping.py中channel.json的路径是否正确:因为ping.py在
Cogs目录,而JSON文件在Data Storage目录,相对路径需写成../Data Storage/channel.json,直接写Data Storage/channel.json会找不到文件。 - 示例正确加载代码:
import json import os # 基于当前文件位置定位JSON文件 current_dir = os.path.dirname(os.path.abspath(__file__)) json_path = os.path.join(current_dir, "../Data Storage/channel.json") with open(json_path, "r") as f: data = json.load(f) # 频道ID必须转成整数,Discord API只接受整数类型ID BOT_CHANNEL_ID = int(data["BOT_CHANNEL_ID"]) # 加打印确认是否读取成功 print(f"已加载频道ID: {BOT_CHANNEL_ID}")
二、确认就绪事件的写法与触发
- Cog中的就绪事件必须用
@commands.Cog.listener()装饰器,不能用@bot.event(后者在Cog中不会触发),正确写法:
from discord.ext import commands class Ping(commands.Cog): def __init__(self, bot): self.bot = bot # 把JSON加载逻辑放在这里或者Cog初始化时 @commands.Cog.listener() async def on_ready(self): try: channel = self.bot.get_channel(BOT_CHANNEL_ID) if channel: await channel.send("机器人已就绪!") else: print(f"找不到ID为{BOT_CHANNEL_ID}的频道") except Exception as e: # 强制捕获并打印所有错误 print(f"发送消息出错: {str(e)}")
三、验证频道ID与机器人权限
- 确认channel.json中的
BOT_CHANNEL_ID是有效频道ID:可以手动把ID直接写进代码测试(比如BOT_CHANNEL_ID = 1234567890),排除JSON加载的问题。 - 检查机器人在目标频道的权限:必须拥有查看频道和发送消息权限,否则即使ID正确也无法发送。
四、确认Cog是否被正确加载
- 检查main.py中加载Cog的代码是否正确:
import discord from discord.ext import commands import os from dotenv import load_dotenv # 加载.env文件 load_dotenv(os.path.join("Data Storage", ".env")) TOKEN = os.getenv("DISCORD_TOKEN") # 启用必要的Intents intents = discord.Intents.default() intents.message_content = True intents.guilds = True bot = commands.Bot(command_prefix="!", intents=intents) async def load_cogs(): # 加载Cog的路径是模块路径,即Cogs.ping await bot.load_extension("Cogs.ping") @bot.event async def on_ready(): await load_cogs() print("机器人已上线") bot.run(TOKEN)
- 如果Cog未加载,里面的
on_ready事件根本不会触发,自然不会发送消息。
五、检查Intents配置
- 确保main.py中启用了
message_content和guilds这两个Intents:前者是发送普通消息的必要权限,后者是获取服务器频道信息的基础,缺少任何一个都可能导致消息发送失败。
内容的提问来源于stack exchange,提问作者user23185791
相关产品推荐
相关产品推荐

