You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 18:12:34