Discord多服务器欢迎机器人报NoneType无send属性错误如何解决?
错误原因
报错核心是执行channel.send时channel为None,常见诱因有3个:
- 数据类型不匹配:
setwelcome命令存储的频道ID是用户输入的字符串类型,但discord.utils.get匹配频道ID时要求传入整数,类型不一致无法命中对应频道,最终返回空值 - 未提前设置欢迎频道:机器人加入新服务器时默认给对应服务器存储的欢迎频道ID为空字符串,管理员未执行
setwelcome配置的场景下,自然无法查询到有效频道 - 权限或频道失效:如果配置的频道已被删除,或是机器人没有该频道的查看、发消息权限,也会导致频道查询结果为空
可行修复方案
按照优先级调整如下即可:
- 存取频道ID时统一转换为整数类型
- 发消息前增加空值判断,避免调用不存在对象的方法
- 增加未配置频道的兜底逻辑,可省略发消息或者给管理员发送提示
修改后的核心代码参考:
import json import discord # 读取时直接转换为整数,不存在则返回None def get_welcome(guild): with open('welcomechannels.json', 'r') as f: welcomechannels = json.load(f) channel_id = welcomechannels.get(str(guild.id)) return int(channel_id) if channel_id and channel_id.isdigit() else None @client.event async def on_guild_join(guild): with open('welcomechannels.json', 'r') as f: welcomechannels = json.load(f) # 新服务器默认存空字符串 welcomechannels[str(guild.id)] = '' with open('welcomechannels.json', 'w') as f: json.dump(welcomechannels,f) # 优化setwelcome命令,支持直接@频道,不用手动输ID @client.command() async def setwelcome(ctx, channel: discord.TextChannel = None): if not channel: await ctx.send("请@要设置的欢迎频道,例如 `/setwelcome #欢迎频道`") return guild = ctx.guild with open('welcomechannels.json', 'r') as f: welcomechannels = json.load(f) # 存储频道ID为字符串也可以,读取的时候转整数就行 welcomechannels[str(guild.id)] = str(channel.id) with open('welcomechannels.json', 'w') as f: json.dump(welcomechannels,f) await ctx.send('欢迎频道设置完成') @client.event async def on_member_join(member): guild = member.guild channel_id = get_welcome(guild) if not channel_id: return channel = discord.utils.get(member.guild.channels, id=channel_id) # 再次判断频道是否存在,以及机器人有发消息权限 if channel and channel.permissions_for(guild.me).send_messages: await channel.send(f'Welcome {member.mention}')
内容的提问来源于stack exchange,提问作者Hondaman727
相关产品推荐
相关产品推荐

