@Evgen_Drop

Сможете помочь с ошибкой при создании музыкального бота для Дискорда?

Каждый раз возникает ошибка при воспроизведении музыки в дискорд дольше чем 30 сек.
Код:
import discord
from discord.ext import commands
import config
import asyncpraw
import asyncio
import ffmpeg 

import youtube_dl
import os

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

@bot.event
async def on_readr():
    print('bot online!')

server, server_id, name_channel = None, None, None

domains = ['https://www.youtube.com', 'http://www.youtube.com', 'https://youtu.be', 'http://youtu.be']

async def check_domains(link):
    for x in domains:
        if link.startswith(x):
            return True
    return False


@bot.command()
async def play(ctx, *, command = None):
    """Воспроизводит музыку"""
    global server, server_id, name_channel
    author = ctx.author
    if command == None:
        server = ctx.guild
        name_channel = author.voice.channel.name
        voice_channel = discord.utils.get(server.voice_channels, name = name_channel)
    params = command.split(' ')
    if len(params) == 1:
        sourse = params[0]
        server = ctx.guild
        name_channel = author.voice.channel.name
        voice_channel = discord.utils.get(server.voice_channels, name=name_channel)
        print('param 1')
    elif len(params) == 3:
        server_id = params[0]
        voice_id = params[1]
        sourse = params[2]
        try:
            server_id = int(server_id)
            voice_id = int(voice_id)
        except:
            await crx.channel.send(f'{author.mention}, id сервера или войса должно быть челочисленным!')
            return
        print('param 3')
        server = bot.get_guild(server_id)
        voice_channel = discord.utils.get(server.voice_channels, id=voice_id)
    else:
        await ctx.channel.send(f'{author.mention} команда не корректна!')
        return

    voice = discord.utils.get(bot.voice_clients, guild = server)
    if voice is None:
        await voice_channel.connect()
        voice = discord.utils.get(bot.voice_clients, guild=server)
    
    if sourse == None:
        pass
    elif sourse.startswith('http'):
        if not await check_domains(sourse):
            await ctx.channel.send(f'{author.mention}, ссылка не является разрешенной!')
            return
        song_there = os.path.isfile('C:/BotDS/song.mp3')
        try:   
            if song_there:
                os.remove('C:/BotDS/song.mp3')
        except PermissionError:
            await ctx.channel.send('недостаточно прав для удаления')
            return


        ydl_opts = {
            'format': 'bestaudio/best',
            'postprocessors': [
                {
                    'key': 'FFmpegExtractAudio',
                    'preferredcodec': 'mp3',
                    'preferredquality': '192',
                }
            ],
        }

        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.download([sourse])
        for file in os.listdir('./'):
            if file.endswith('.mp3'):
                os.rename(file, 'song.mp3')
        voice.play(discord.FFmpegPCMAudio('C:/BotDS/song.mp3'))
    else:
        voice.play(discord.FFmpegPCMAudio(f'{sourse}'))

@bot.command()
async def leave(ctx):
    """выход из войса"""
    global server, name_channel
    voice = discord.utils.get(bot.voice_clients, guild=server)
    if voice.connected():
        await voice_disconnect()
    else:
        await ctx.channel.send(f'{ctx.author.menthion}, я уже отключен от войса!')

@bot.command()
async def pause(ctx):
    """пауза"""
    voice = discord.utils.get(bot.voice_clients, guild=server)
    if voice.is_playing():
        voice.pause()
    else:
        await ctx.channel.send(f'{ctx.author.menthin}, Музыке капут!')

@bot.command()
async def resume(ctx):
    voice = discord.utils.get(bot.voice_clients, guild=server)
    if voice.is_paused():
        voice.resume()
    else:
        await ctx.channel.send(f'{ctx.author.menthin}, Так уже!')

@bot.command()
async def stop(ctx):
    """ стоп музыке """
    voice = discord.utils.get(bot.voice_clients, guild=server)
    voice.stop()


Ошибка:
Exception in voice thread Thread-13
Traceback (most recent call last):
File "F:\python\lib\site-packages\discord\player.py", line 603, in run
self._do_run()
File "F:\python\lib\site-packages\discord\player.py", line 596, in _do_run
play_audio(data, encode=not self.source.is_opus())
File "F:\python\lib\site-packages\discord\voice_client.py", line 638, in send_audio_packet
self.socket.sendto(packet, (self.endpoint_ip, self.voice_port))
OSError: [WinError 10038] Сделана попытка выполнить операцию на объекте, не являющемся сокетом
  • Вопрос задан
  • 160 просмотров
Решения вопроса 1
@AlexInCube
Я делал музыкального бота на JavaScript и была похожая ситуация. Возникала когда бот перезаходил в голосовой канал.
Надо уничтожать соединения не с помощью .disconnect(), а с помощью .destroy()
А также на всех операциях с voice, нужно писать к примеру await voice.pause() Так как голосовой канал это асинхронщина.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

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

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