discord.py 1.7.3处理DM消息触发NoneType无id属性报错解决方案咨询
问题原因
- 报错核心原因:当Bot和目标用户从未进行过DM交互时,
message.author.dm_channel属性会返回None,直接访问.id就会触发AttributeError - 自定义异常捕获未生效的原因:报错的判断行写在
try代码块外部,异常触发时还没有进入捕获范围
修复方案
优先使用discord.py内置的通道类型判断识别DM消息,不需要读取dm_channel属性,逻辑更稳定,修改后的代码如下:
import discord import os import requests import json with open("config.json") as f: configData = json.load(f) token = configData["TOKEN"] client = discord.Client() @client.event async def on_message(message): # 先过滤Bot自己发送的消息,放在最开头避免无效处理 if message.author == client.user: return # 直接判断当前频道是否为DM私聊频道,替代原来的ID比对逻辑 if isinstance(message.channel, discord.DMChannel): msg = message.content msg_low = msg.lower() if msg_low.startswith('name'): try: print(message.content) await message.author.send("Hello {username} {id}".format(username = message.author.name, id = message.author.id)) except: print("problem")
如果要保留原来的dm_channel判断逻辑,也可以先做非空判断,仅修改判断行即可:
if message.author.dm_channel is not None and message.channel.id == message.author.dm_channel.id:
内容的提问来源于stack exchange,提问作者Joyanta J. Mondal
相关产品推荐
相关产品推荐

