Discord机器人加入服务器写入JSON注册公会实现多服欢迎命令报错求助
问题排查与修复方案
核心错误点
- 属性调用错误:
discord.Guild类本身没有channel属性,你代码中guild.channel.id属于无效调用,运行会直接抛出AttributeError导致事件中断。如果你要关联服务器维度的配置,应该用guild.id作为键存储数据;如果你是要获取服务器默认系统频道的ID,应该用guild.system_channel.id,但要注意部分服务器没有设置默认系统频道,会返回None,需要额外做判空处理。 - 缺少文件初始化逻辑:如果
welcome.json文件不存在、为空或者格式错误,json.load()会直接抛出解析异常,导致写入流程终止。 - 权限配置遗漏:即使代码中开启了全意图,你还需要登录 Discord 开发者后台,在你的机器人应用的「Bot」设置页,打开 Privileged Gateway Intents 下的
Server Members Intent和Guilds Intent开关,否则机器人无法接收on_guild_join事件回调。
修复后代码
import discord from discord.ext import commands import json import os intents = discord.Intents.all() fright = commands.Bot( command_prefix="!!", activity = discord.Activity(type=discord.ActivityType.listening, name="discord.gg/antis"), status=discord.Status.do_not_disturb, intents=intents ) @fright.event async def on_ready(): print('on') @fright.event async def on_guild_join(guild): # 先判断文件是否存在,不存在就初始化空字典 if not os.path.exists('welcome.json'): cha = {} else: try: with open('welcome.json', 'r') as f: cha = json.load(f) except json.JSONDecodeError: # 文件内容损坏时也重置为空字典 cha = {} # 用公会ID作为键存储,后续可以扩展为存储欢迎频道ID、欢迎语等结构 cha[str(guild.id)] = "test" with open('welcome.json', 'w') as f: json.dump(cha, f, indent=4)
扩展说明
如果你后续要存储每个服务器的欢迎频道、自定义欢迎语,你可以把值改成字典结构,示例如下:
cha[str(guild.id)] = { "welcome_channel_id": None, "welcome_msg": "欢迎加入服务器!" }
内容的提问来源于stack exchange,提问作者aDorzz
相关产品推荐
相关产品推荐

