discord.py开发modmail机器人如何避免同用户DM重复创建文本频道
问题排查
你当前代码的核心错误如下:
- 未完成频道存在性校验就提前执行了
create_text_channel创建频道逻辑,导致每收到一条消息就强制新建频道 - Discord频道名称只支持字符串类型,你直接传入int类型的用户ID作为名称,
discord.utils.get匹配时会因为类型不匹配永远找不到对应频道 - 代码缩进错误,
if channel not in channels分支下的创建逻辑没有缩进,无论判断结果如何都会执行 - 分类获取逻辑存在变量名重复问题,
category = discord.utils.get(guild.categories, id = category.id)会因为调用时category还未完成赋值直接报错 - 多次重复编写频道创建代码,逻辑完全混乱
修正后代码
# 预先定义常量,替换为你自己的实际ID GUILD_ID = 替换为你的服务器ID整数 CATEGORY_ID = 替换为你的分类ID整数 @bot.event async def on_message(message): if message.author == bot.user: return # 只处理私聊消息 if isinstance(message.channel, discord.DMChannel): guild = bot.get_guild(GUILD_ID) # 把用户ID转成字符串作为频道名,匹配discord频道命名规则 user_channel_name = str(message.author.id) # 直接从目标分类下找频道,不用拉取全服频道,效率更高 category = discord.utils.get(guild.categories, id=CATEGORY_ID) # 查找对应用户的已有频道 exist_channel = discord.utils.get(category.channels, name=user_channel_name) # 构建用户消息 embed embedVar = discord.Embed( title=f'{message.author} 发送了新消息', description=message.content, color=0xff0000 ) # 如果没有对应频道就新建 if not exist_channel: new_channel = await guild.create_text_channel( name=user_channel_name, category=category ) # 发送管理员说明 embed embedMod = discord.Embed( title='管理员操作说明', description='!close - 关闭当前工单频道\n!DM - 匿名回复用户', color=0x00FF00 ) await new_channel.send(embed=embedMod) await new_channel.send(embed=embedVar) else: # 已有频道直接发消息 await exist_channel.send(embed=embedVar) await bot.process_commands(message)
逻辑说明
- 提前将用户ID转为字符串作为频道名称,保证查找和创建时名称规则统一
- 优先查找目标分类下的同名频道,不存在时才触发创建逻辑,避免重复新建
- 分类获取直接使用预先定义的常量ID,避免变量名冲突报错
- 分支逻辑清晰,创建和发送消息的逻辑完全拆分,不会出现重复执行的问题
内容的提问来源于stack exchange,提问作者Saahil Gupta
相关产品推荐
相关产品推荐

