Discord机器人模组申请:按钮交互下私信用户及多问题回复实现
Discord机器人模组申请按钮私信与多问题处理方案
一、修复按钮发送私信的问题
你原代码里的DMChannel.send用法错误,直接通过interaction.user对象调用send()方法就能给用户发私信,同时建议增加异常处理,避免因用户关闭私信权限导致报错。修正后的按钮回调代码如下:
@button(label="Apply Here!", style=discord.ButtonStyle.green) async def apply(self, interaction: discord.Interaction, button: Button): await interaction.response.defer() await interaction.followup.send(content="Please await a dm from the bot!", ephemeral=True) # 发送私信 try: await interaction.user.send("Hello! Let's start your moderator application.") except discord.Forbidden: await interaction.followup.send("无法给你发送私信,请检查你的隐私设置!", ephemeral=True)
二、实现多提问并保存回复内容
可以通过wait_for监听用户的私信回复,循环提出预设问题,将用户的答案存入字典或列表中保存。以下是完整的按钮回调修改示例:
@button(label="Apply Here!", style=discord.ButtonStyle.green) async def apply(self, interaction: discord.Interaction, button: Button): await interaction.response.defer() await interaction.followup.send(content="Please await a dm from the bot!", ephemeral=True) # 预设问题列表 questions = [ "你申请成为模组的原因是什么?", "你有过相关的管理经验吗?", "如果遇到用户冲突,你会如何处理?" ] answers = {} try: # 发送初始消息 await interaction.user.send("欢迎提交模组申请!接下来我会问你几个问题,请依次回复:") # 循环提问并收集答案 for idx, question in enumerate(questions, 1): await interaction.user.send(f"问题{idx}:{question}") # 等待用户回复,超时时间设为5分钟(可调整) msg = await self.client.wait_for( "message", check=lambda m: m.author == interaction.user and isinstance(m.channel, discord.DMChannel), timeout=300 ) answers[f"问题{idx}"] = msg.content # 所有问题完成后发送确认消息,也可以将answers保存到数据库/文件 await interaction.user.send("感谢你的申请!我们会尽快审核。") # 这里可以添加将answers保存到数据库或本地文件的逻辑 print(f"用户{interaction.user.name}的申请答案:{answers}") except discord.Forbidden: await interaction.followup.send("无法给你发送私信,请检查你的隐私设置!", ephemeral=True) except asyncio.TimeoutError: await interaction.user.send("申请超时,请重新发起申请。")
三、注意事项
- 确保机器人有发送私信的权限,且用户没有屏蔽机器人或关闭私信接收权限。
wait_for的check参数要严格验证消息来源,避免接收其他用户的消息。- 如需持久化保存答案,可以使用SQLite、MongoDB等数据库,或写入JSON文件。
内容的提问来源于stack exchange,提问作者Harri
相关产品推荐
相关产品推荐

