Answer the question
In order to leave comments, you need to log in
Discord Bot gives SOMETIMES an error when trying to play music in a voice channel, often when the file is over 4mb. Python. What's wrong?
Sometimes when playing music in the voice channel, an error appears. Moreover, the value of "Thread" is not necessarily 9, sometimes 29. It often happens if the downloaded file weighs more than 4 MB.
import discord
from discord.ext import commands
import youtube_dl
import os
import sys
import urllib.parse
import urllib.request
import re
client = commands.Bot(command_prefix="!")
sys.setrecursionlimit(4000)
print(sys.getrecursionlimit())
@client.event
async def on_ready():
channel = client.get_channel(912429157370167316)
await channel.send(f"Бот успешно запущен")
print('Bot ready')
@client.command()
@commands.cooldown(1, 5.00, commands.BucketType.guild)
async def yt(msg, *, search):
"""Запрос на поиск песни через YoyTube"""
query_string = urllib.parse.urlencode({
"search_query": search
})
html_content = urllib.request.urlopen(
"http://www.youtube.com/results?" + query_string
)
search_results = re.findall(r"watch\?v=(\S{11})", html_content.read().decode())
await msg.send("http://www.youtube.com/watch?v=" + search_results[0])
@client.command()
async def clear(ctx, amount=5):
"""Бот удаляет сообщения"""
if commands.has_permissions(manage_messages=True):
await ctx.channel.purge(limit=amount)
await ctx.send(f'Удалено')
return
@client.command()
async def play(ctx, url : str):
"""Запуск музыки через ссылку YouTube"""
song_there = os.path.isfile("song.mp3")
try:
if song_there:
os.remove("song.mp3")
except PermissionError:
await ctx.send("Дождитесь окончания текущего воспроизведения музыки или используйте команду 'stop' ")
return
voiceChannel = discord.utils.get(ctx.guild.voice_channels, name='Основной')
await voiceChannel.connect()
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
for file in os.listdir("./"):
if file.endswith(".mp3"):
os.rename(file, "song.mp3")
voice.play(discord.FFmpegPCMAudio("song.mp3"))
@client.command()
async def leave(ctx):
"""Бот покидает голосовой канал.Перезапуск функций бота"""
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice.is_connected():
await voice.disconnect()
else:
await ctx.send("Бот не подключен к голосовому каналу")
@client.command()
async def pause(ctx):
"""Ставит трек на паузу"""
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice.is_playing():
voice.pause()
else:
await ctx.send("В настоящее время звук не воспроизводится")
@client.command()
async def resume(ctx):
"""Продолжает воспроизведение трека"""
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if voice.is_paused():
voice.resume()
else:
await ctx.send("Трек не был остановлен")
@client.command()
async def stop(ctx):
"""Бот прекращает воспроизведение музыки """
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
voice.stop()
client.run('token')
Exception in voice thread Thread-9
Traceback (most recent call last):
File "C:\Users\sienk\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\player.py", line 603, in run
self._do_run()
File "C:\Users\sienk\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\player.py", line 596, in _do_run
play_audio(data, encode=not self.source.is_opus())
File "C:\Users\sienk\AppData\Local\Programs\Python\Python39\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] Сделана попытка выполнить операцию на объекте, не являющемся сокетом
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question