Wolf_Yout
@Wolf_Yout

Disnake Как воспроизвести файл в голосовом канале?

Мой код(Взял с рандомного сайта и переделал под себя)
class songs():
	async def join_to_channel(ctx):
		voice = ctx.author.voice
		if not voice: return "nothingChannel"
		if voice:
			await voice.channel.connect()
			return "Success"

	async def exit(ctx):
		voice_state = ctx.guild.voice_client
		if voice_state.is_connected():
			await voice_state.disconnect()
			return "Success"
		else:
			return "notConnected"

	async def stop(ctx):
		voice_state = ctx.guild.voice_client
		if voice_state.is_playing():
			await voice_state.stop()
			await exit(ctx)
			return "Success"
		else:
			return "noMusic"


	async def play_song_file(ctx):
		voice_state = ctx.guild.voice_client
		if not voice_state:
			voice = ctx.author.voice
			if not voice: return "nothingChannel"
			if voice:
				await voice.channel.connect()

		voice_state = ctx.guild.voice_client
		voice_state.play(disnake.FFmpegAudio(executable="ffmpeg.exe", source="music.mp3", after=None))
		return "Success"

	async def pause(ctx):
		voice_state = ctx.guild.voice_client
		if voice_state.is_playing():
			await voice_state.pause()
			return "Success"
		else:
			return "noMusic"

	async def resume(ctx):
		voice_state = ctx.guild.voice_client
		if voice_state.is_playing():
			if voice_state.is_paused():
				await voice_state.resume()
				return "Success"
			else:
				return "notPaused"
		else:
			return "notMusic"
		
		

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

	@commands.slash_command(name="test",description="Команда для проверки состояния бота")
	async def test(self, ctx):
		await ctx.send("Всё - ок!")

	@commands.slash_command(name="join",description="Вызвать бота к подключению к вам.")
	async def join(self, ctx):
		await ctx.response.defer()
		st = await songs.join_to_channel(ctx)
		if st == "nothingChannel":
			return await ctx.send(embed=disnake.Embed(title="<a:wrongCheckmark:1047126198330859580> Ошибка",description="Для этого, зайдите в канал",color=disnake.Color.red()))
		elif st == "Success":
			await ctx.send(embed=disnake.Embed(title="<a:correctCheckmark:1047126198330859580>",color=0x228b22))
	
	@commands.slash_command(name="play",description="Начать воспроизведение файла")
	async def play(self, ctx):
		await ctx.response.defer()
		st = await songs.play_song_file(ctx)
		if st == "nothingChannel":
			return await ctx.send(embed=disnake.Embed(title="<a:wrongCheckmark:1047126198330859580> Ошибка",description="Для этого, зайдите в голосовой канал!",color=disnake.Color.red()))
		elif st == "Success":
			return await ctx.send(embed=disnake.Embed(title="<a:correctCheckmark:1047126198330859580>",color=0x228b22))

	@commands.slash_command(name="stop",description="Остановить музыку")
	async def stop_music(self, ctx):
		await ctx.response.defer()
		st = await songs.stop(ctx)
		if st == "noMusic":
			return await ctx.send(embed=disnake.Embed(title="<a:wrongCheckmark:1047126198330859580> Ошибка",description="Но сейчас же ничего не играет...",color=0x228b22))
		elif st == "Success":
			return await ctx.send(embed=disnake.Embed(title="<a:correctCheckmark:1047126198330859580>",color=0x228b22))

	@commands.slash_command(name="exit",description="Покинуть канал")
	async def exit_channel(self, ctx):
		await ctx.response.defer()
		st = await songs.exit(ctx)
		if st == "notConnected":
			return await ctx.send(embed=disnake.Embed(title="<a:wrongCheckmark:1047126198330859580> Ошибка",description="Я итак не подключен.",color=0x228b22))
		elif st == "Success":
			return await ctx.send(embed=disnake.Embed(title="<a:correctCheckmark:1047126198330859580>",color=0x228b22))

Бот заходит ко мне в голосовой канал, но играть НЕ начинает, а в консоли тем временем такая ошибка:
Exception ignored in: <function AudioSource.__del__ at 0x000001FFD826C3A0>
Traceback (most recent call last):
  File "C:\Users\Вульф\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\player.py", line 100, in __del__
    self.cleanup()
  File "C:\Users\Вульф\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\player.py", line 221, in cleanup
    self._kill_process()
  File "C:\Users\Вульф\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\player.py", line 172, in _kill_process
    proc = self._process
AttributeError: 'FFmpegAudio' object has no attribute '_process'
Ignoring exception in slash command 'play':
Traceback (most recent call last):
  File "C:\Users\Вульф\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\slash_core.py", line 730, in invoke
    await call_param_func(self.callback, inter, self.cog, **kwargs)
  File "C:\Users\Вульф\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\params.py", line 1022, in call_param_func
    return await maybe_coroutine(safe_call, function, **kwargs)
  File "C:\Users\Вульф\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\utils.py", line 599, in maybe_coroutine
    return await value
  File "C:\Users\Вульф\OneDrive\Документы\Python Projects\VEX admin\main.py", line 83, in play
    st = await songs.play_song_file(ctx)
  File "C:\Users\Вульф\OneDrive\Документы\Python Projects\VEX admin\main.py", line 39, in play_song_file
    voice_state.play(disnake.FFmpegAudio(executable="ffmpeg.exe", source="/music.mp3", after=None))
TypeError: __init__() missing 1 required keyword-only argument: 'args'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Вульф\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\interaction_bot_base.py", line 1353, in process_application_commands
    await app_command.invoke(interaction)
  File "C:\Users\Вульф\AppData\Local\Programs\Python\Python39\lib\site-packages\disnake\ext\commands\slash_core.py", line 739, in invoke
    raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() missing 1 required keyword-only argument: 'args'
  • Вопрос задан
  • 1120 просмотров
Пригласить эксперта
Ответы на вопрос 1
gnifajio
@gnifajio
Совершенствуюсь каждый день
Для воспроизведения аудио файла в голосовом канале с помощью библиотеки Discord.py вам нужно сначала импортировать необходимые модули:
import discord
from discord.ext import commands
import os

Затем, создайте экземпляр бота и добавьте команду для воспроизведения аудио:

bot = commands.Bot(command_prefix='!')

@bot.command()
async def play(ctx, *, file_name: str):
    voice_channel = ctx.message.author.voice.channel
    if not voice_channel:
        await ctx.send("Вы не находитесь в голосовом канале!")
        return

    # Подключаемся к голосовому каналу
    vc = await voice_channel.connect()

    # Получаем аудиофайл из папки 'audio_files'
    audio_file = f'audio_files/{file_name}.mp3'
    if not os.path.isfile(audio_file):
        await ctx.send(f"Файл {file_name}.mp3 не найден.")
        return

    # Создаем поток аудио
    source = discord.FFmpegPCMAudio(audio_file)
    # Начинаем воспроизведение аудио
    vc.play(source)

Теперь, когда вы находитесь в голосовом канале, вы можете воспроизвести аудиофайл, отправив команду !play file_name, где file_name - название файла без расширения .mp3.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы