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

如何让discord.py机器人加入指定语音频道?

让discord.py机器人加入指定名称的语音频道

我来给你捋捋怎么实现这个需求,核心就是先定位到名为“x”的目标语音频道,再让机器人连接过去就行,下面给你具体的代码和细节说明:

基础实现(命令触发式)

可以写一个自定义命令,用户触发后机器人自动加入指定频道:

import discord
from discord.ext import commands

# 初始化机器人,记得开启必要的intents
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

@bot.command()
async def join_x(ctx):
    # 从当前服务器的语音频道列表里,筛选出名为"x"的频道
    target_channel = discord.utils.get(ctx.guild.voice_channels, name="x")
    
    # 先判断是否找到目标频道
    if not target_channel:
        await ctx.send("找不到名为'x'的语音频道哦,请检查频道名称是否正确!")
        return
    
    # 如果机器人已经在其他语音频道,直接移动过去
    if ctx.voice_client:
        await ctx.voice_client.move_to(target_channel)
    # 机器人不在任何语音频道的话,直接连接目标频道
    else:
        await target_channel.connect()
    
    await ctx.send(f"搞定!已经加入语音频道「{target_channel.name}」啦~")

# 替换成你的机器人TOKEN
bot.run("YOUR_BOT_TOKEN")

关键细节提醒

  • 匹配规则调整:默认discord.utils.get是精确匹配名称大小写的,如果想忽略大小写(比如频道是"X"也能匹配),可以把name="x"改成name__iexact="x"。
  • 权限必备:一定要给机器人分配权限!需要开启「连接语音频道」和「查看频道」的权限,不然机器人会因为权限不足无法加入频道。
  • 跨服务器兼容:上面的代码只会在用户触发命令的服务器里查找频道,如果你机器人在多服务器运行,也不用担心串频道的问题。

进阶:机器人启动自动加入频道

如果想让机器人一启动就自动加入指定频道,可以在on_ready事件里写逻辑:

@bot.event
async def on_ready():
    # 替换成目标服务器的ID和频道名称
    target_guild = bot.get_guild(123456789) # 这里填你的服务器ID
    target_channel = discord.utils.get(target_guild.voice_channels, name="x")
    
    if target_channel:
        await target_channel.connect()
        print(f"机器人已自动加入频道:{target_channel.name}")
    else:
        print("找不到指定的语音频道!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 18:57:55