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

Discord.py:用户在DM使用斜杠命令时如何获取Guild详情?

解决Discord机器人DM中获取Guild信息的问题

DM(私信)上下文本身没有关联的Guild信息,所以message.guild返回None是正常现象。要实现需求,得换思路从其他途径获取Guild,以下是几种可行方案:

  • 让用户在命令中指定目标服务器
    修改斜杠命令,添加一个必填的服务器选择选项,让用户主动指定要操作的Guild。以discord.py为例:

    @app_commands.command(name="your_command")
    @app_commands.describe(target_guild="选择要操作的服务器")
    async def your_command(interaction: discord.Interaction, target_guild: discord.Guild):
        # 直接拿到用户指定的Guild对象
        await interaction.response.send_message(f"你选择的服务器:{target_guild.name}(ID:{target_guild.id})")
    

    注:机器人必须已加入该服务器,否则选项列表中不会显示对应的Guild。

  • 基于共同服务器自动筛选或让用户选择
    先获取用户与机器人共同加入的服务器列表,再根据数量处理:

    @app_commands.command(name="your_command")
    async def your_command(interaction: discord.Interaction):
        # 筛选用户和机器人的共同服务器
        mutual_guilds = []
        for guild in interaction.client.guilds:
            try:
                # 验证用户是否在该服务器(避免缓存问题)
                await guild.fetch_member(interaction.user.id)
                mutual_guilds.append(guild)
            except discord.NotFound:
                continue
        
        if not mutual_guilds:
            await interaction.response.send_message("我们没有共同加入的服务器,无法执行操作")
            return
        
        # 只有一个共同服务器时直接使用
        if len(mutual_guilds) == 1:
            target_guild = mutual_guilds[0]
            await interaction.response.send_message(f"自动匹配服务器:{target_guild.name}")
        # 多个时用选择菜单让用户挑选
        else:
            select_options = [
                discord.SelectOption(label=guild.name, value=str(guild.id)) 
                for guild in mutual_guilds
            ]
            select_menu = discord.ui.Select(options=select_options)
            
            async def handle_select(inter: discord.Interaction):
                guild_id = int(select_menu.values[0])
                target_guild = interaction.client.get_guild(guild_id)
                await inter.response.send_message(f"你选择的服务器:{target_guild.name}")
            
            select_menu.callback = handle_select
            view = discord.ui.View()
            view.add_item(select_menu)
            await interaction.response.send_message("请选择要操作的服务器:", view=view)
    
  • 注意事项

    • 确保机器人拥有Guild Members Intent权限,否则无法获取服务器成员信息,导致共同服务器筛选失败
    • 若机器人刚加入服务器,可能需要等待缓存同步,使用fetch_member能避免缓存缺失的问题

内容的提问来源于stack exchange,提问作者Aarti Joshi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 19:50:11