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

Discord机器人开发:如何获取新连接指定语音频道的用户ID

Discord机器人解决方案:语音频道创建+成员跟踪+邀请消息更新

核心解决思路

要实现用户加入创建频道时立即获取ID,同时支持!invite指令动态更新成员提及,需要用全局字典跟踪每个创建频道的成员列表和对应的邀请消息,解决原代码中变量未定义、事件阻塞的问题。

修改后的完整代码

import discord
from discord.ext import commands

client = commands.Bot(command_prefix='!', intents=discord.Intents.all())

# 存储创建的语音频道ID -> 成员列表
channel_members = {}
# 存储创建的语音频道ID -> 对应的邀请消息对象
channel_invite_messages = {}

@client.command(name='invite')
async def invite(ctx: commands.Context):
    # 校验用户是否在机器人创建的语音频道内
    if not ctx.author.voice or ctx.author.voice.channel.id not in channel_members:
        await ctx.send("你得先在机器人创建的语音频道里才能发邀请!")
        return
    
    channel_id = ctx.author.voice.channel.id
    # 构造邀请Embed
    poster = discord.Embed(colour=0xFF5500)
    invite_title = ctx.message.content[7:] if len(ctx.message.content) > 7 else "语音频道邀请"
    member_mentions = "\n".join([member.mention for member in channel_members[channel_id]])
    poster.add_field(name=invite_title, value=member_mentions)
    
    # 发送消息并关联到对应频道
    msg = await ctx.send(embed=poster)
    channel_invite_messages[channel_id] = msg

@client.event
async def on_voice_state_update(member, before, after):
    trigger_channel_id = 1019214989829079060
    category_id = 1019215017150787604

    # 场景1:用户进入触发频道,创建专属语音频道
    if after.channel and after.channel.id == trigger_channel_id:
        guild = member.guild
        category = discord.utils.get(guild.categories, id=category_id)
        created_channel = await guild.create_voice_channel(
            name=f"{member.display_name}'s",
            category=category,
            user_limit=5
        )
        await created_channel.set_permissions(member, connect=True, mute_members=True, move_members=True)
        await member.move_to(created_channel)
        
        # 初始化该频道的成员列表
        channel_members[created_channel.id] = [member]
        
        # 监听频道为空事件,为空则删除频道并清理数据
        def check_empty(x, y, z):
            return x.guild == guild and y.channel == created_channel and len(created_channel.members) == 0
        await client.wait_for('voice_state_update', check=check_empty)
        await created_channel.delete()
        if created_channel.id in channel_members:
            del channel_members[created_channel.id]
        if created_channel.id in channel_invite_messages:
            del channel_invite_messages[created_channel.id]
        return
    
    # 场景2:用户加入机器人创建的频道,实时更新成员列表和邀请消息
    if after.channel and after.channel.id in channel_members:
        if member not in channel_members[after.channel.id]:
            channel_members[after.channel.id].append(member)
            
            # 若存在邀请消息,立即编辑更新提及内容
            if after.channel.id in channel_invite_messages:
                msg = channel_invite_messages[after.channel.id]
                embed = msg.embeds[0]
                member_mentions = "\n".join([m.mention for m in channel_members[after.channel.id]])
                embed.set_field_at(0, name=embed.fields[0].name, value=member_mentions)
                await msg.edit(embed=embed)

# 替换为你的机器人Token
client.run("YOUR_BOT_TOKEN")

关键修改说明

  • 全局字典跟踪:用channel_members记录每个频道的成员,channel_invite_messages关联对应邀请消息,解决原代码变量未定义的问题。
  • 实时获取成员ID:用户加入创建频道时,事件会立即触发并将成员加入列表,同时自动更新已发送的邀请消息。
  • 事件逻辑拆分:将创建频道和成员加入的逻辑分开,避免原代码中wait_for阻塞后续事件的问题。
  • 边界处理:添加了用户不在目标频道无法发邀请的校验,以及成员重复加入的去重处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:05:24