如何在Discord频道选择菜单中获取日志选择菜单的选中值
问题描述
在Discord的日志选择菜单中让用户选中一项操作后,需要在频道选择菜单中获取该选中的日志类型,但自行实现时遇到困难。以下是对应的discord.py代码片段,请求实现该功能的方法。
代码片段:
class log(discord.ui.Select): def __init__(self): options=[ discord.SelectOption(label="Логи сервера"), discord.SelectOption(label="Логи входа и выхода участников") ] super().__init__(placeholder="Выберите раздел.",max_values=1,min_values=1,options=options, custom_id="LOG") async def callback(self, interaction: discord.Interaction): if self.values[0] == "Логи сервера": await interaction.response.edit_message(view=channel_log()) if self.values[0] == "Логи входа и выхода участников": await interaction.response.edit_message(view=channel_log())
class channel(discord.ui.ChannelSelect): def __init__(self): super().__init__(placeholder="Выберите раздел.",channel_types=[discord.ChannelType.text], custom_id="HELP") async def callback(self, interaction: discord.Interaction): #for self.values[0] in logs(): print() cur.execute(f'INSERT INTO logs (message_log) VALUES ({self.values[0].id})') conn.commit() await interaction.response.edit_message(f"{self.values[0].id}") return
解决方案
核心是把日志选择菜单中选中的类型传递给频道选择菜单所在的视图,让频道选择的回调能访问到该值。以下是修改后的完整实现:
import discord # 假设cur和conn是已初始化的数据库游标与连接 class ChannelLogView(discord.ui.View): def __init__(self, selected_log_type): super().__init__() # 保存用户选中的日志类型 self.selected_log_type = selected_log_type # 将频道选择菜单添加到视图,并传入日志类型 self.add_item(ChannelSelect(selected_log_type)) class LogSelect(discord.ui.Select): def __init__(self): # 选项翻译为中文(可根据需求保留原语言) options=[ discord.SelectOption(label="服务器日志"), discord.SelectOption(label="成员进出日志") ] super().__init__( placeholder="请选择日志类型.", max_values=1, min_values=1, options=options, custom_id="LOG_SELECT" ) async def callback(self, interaction: discord.Interaction): # 获取用户选中的日志类型 selected_type = self.values[0] # 切换到包含频道选择菜单的视图,传入选中的类型 await interaction.response.edit_message(view=ChannelLogView(selected_type)) class ChannelSelect(discord.ui.ChannelSelect): def __init__(self, log_type): self.log_type = log_type # 保存传入的日志类型 super().__init__( placeholder="请选择目标频道.", channel_types=[discord.ChannelType.text], custom_id="CHANNEL_SELECT" ) async def callback(self, interaction: discord.Interaction): selected_channel = self.values[0] # 同时获取日志类型与选中频道 print(f"日志类型: {self.log_type}, 频道ID: {selected_channel.id}") # 使用参数化查询执行数据库插入,避免SQL注入风险 cur.execute( 'INSERT INTO logs (log_type, message_log) VALUES (?, ?)', (self.log_type, selected_channel.id) ) conn.commit() # 给用户反馈操作结果 await interaction.response.edit_message( content=f"已完成配置:{self.log_type} → 频道 {selected_channel.mention}" )
关键修改说明
- 新增
ChannelLogView视图类:作为频道选择菜单的容器,负责接收并保存从日志选择菜单传来的类型值 - 修改日志选择菜单的回调:不再直接创建空的频道视图,而是传入选中的日志类型实例化
ChannelLogView - 修改频道选择菜单的初始化:接收日志类型参数并保存,确保回调方法能访问到该值
- 修复SQL注入风险:原代码用字符串拼接SQL语句存在安全隐患,改用参数化查询替代
内容的提问来源于stack exchange,提问作者XakeR
相关产品推荐
相关产品推荐

