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

discord.py V2.0:无ctx的斜杠命令join实现求助

Discord斜杠命令:实现机器人加入语音频道

用户需要将旧的前缀式join命令迁移为Discord斜杠命令,但现有教程大多基于旧的ctx上下文,因此寻求无需ctx的实现方案。以下是补全核心逻辑后的完整音乐Cog代码:

import requests
import asyncio
from youtube_dl import YoutubeDL
from rich import print
#---
import discord
from discord import app_commands
from discord.ext import commands
from discord import FFmpegPCMAudio
#---
YDL_OPTIONS = {
    'format': 'bestaudio/best', 
    'noplaylist': True,
    'quiet': True,
    'postprocessors': [{  # 修正拼写错误:prostprocessors → postprocessors
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '256',
    }]
}
FFMPEG_OPTIONS = {
    'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
    'options': '-vn'
}
#---

class music(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @app_commands.command(name = "join", description="Boten joinar din nuvarande röst-kanal!")
    async def join(self, interaction: discord.Interaction):
        # 获取调用命令的用户的语音状态
        user_voice = interaction.user.voice
        
        # 检查用户是否在语音频道中
        if not user_voice:
            await interaction.response.send_message("你需要先加入一个语音频道!", ephemeral=True)
            return
        
        target_channel = user_voice.channel
        guild = interaction.guild
        voice_client = guild.voice_client

        # 检查机器人是否已在目标频道
        if voice_client and voice_client.channel == target_channel:
            await interaction.response.send_message("我已经在这个语音频道里了!", ephemeral=True)
            return
        
        # 尝试加入频道
        try:
            # 如果机器人在其他频道,先断开连接
            if voice_client:
                await voice_client.disconnect()
            await target_channel.connect()
            await interaction.response.send_message(f"已加入频道:{target_channel.name}")
        except discord.errors.ClientException as e:
            await interaction.response.send_message(f"加入频道失败:{str(e)}", ephemeral=True)
        except discord.errors.Forbidden:
            await interaction.response.send_message("我没有权限加入这个语音频道!", ephemeral=True)

async def setup(bot):
    await bot.add_cog(music(bot))

核心逻辑说明

  • 替代ctx的用户语音状态获取:通过interaction.user.voice获取调用者的语音连接状态,等价于旧前缀命令中的ctx.author.voice。
  • 边界场景处理:
    • 检测用户是否未加入任何语音频道,给出针对性提示(ephemeral=True确保消息仅调用者可见)。
    • 避免机器人重复加入同一频道,减少无效操作。
  • 异常捕获:
    • 处理频道已满、权限不足等常见错误,返回友好提示。
    • 若机器人当前在其他频道,自动断开旧连接再加入新频道。
  • 配置修正:修复了YDL_OPTIONS中的拼写错误,确保youtube-dl能正常处理音频提取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:25:35