Музыкальный бот для Discord на Python
Написал музыкального бота, который при команде -play (link) входит в голосовой канал, но не включает музыку, а выдает ошибку Код:
import discord from discord.ext import commands import pafy import logging import youtube_dl logging.basicConfig(filename='bot.log', level=logging.INFO) TOKEN = 'token' PREFIX = '-' intents = discord.Intents.all() intents.members = True bot = commands.Bot(command_prefix=PREFIX, intents=intents) @bot.event async def on_ready(): print(f'Logged in as ') @bot.event async def on_message(message): if message.content.lower() == 'привет': await message.channel.send('Привет!') await bot.process_commands(message) @bot.command() async def play(ctx, url: str): if not ctx.author.voice: return await ctx.send("Вы не подключены к голосовому каналу!") voice_channel = ctx.author.voice.channel if ctx.voice_client is None: vc = await voice_channel.connect() else: await ctx.voice_client.move_to(voice_channel) vc = ctx.voice_client video = pafy.new(url) best = video.getbestaudio() source = await discord.FFmpegOpusAudio.from_probe(best.url, method='fallback') vc.play(source) @bot.command() async def leave(ctx): if ctx.voice_client: await ctx.guild.voice_client.disconnect() else: await ctx.send("Бот не подключен к голосовому каналу.") logging.info('Bot Online') bot.run(TOKEN)
Ошибка:
ERROR discord.ext.commands.bot Ignoring exception in command play Traceback (most recent call last): File "a:\Work\piton\discord3\venv\lib\site-packages\youtube_dl\YoutubeDL.py", line 815, in wrapper return func(self, *args, **kwargs) File "a:\Work\piton\discord3\venv\lib\site-packages\youtube_dl\YoutubeDL.py", line 836, in __extract_info ie_result = ie.extract(url) File "a:\Work\piton\discord3\venv\lib\site-packages\youtube_dl\extractor\common.py", line 534, in extract ie_result = self._real_extract(url) File "a:\Work\piton\discord3\venv\lib\site-packages\youtube_dl\extractor\youtube.py", line 1794, in _real_extract 'uploader_id': self._search_regex(r'/(?:channel|user)/([^/?]+)', owner_profile_url, 'uploader id') if owner_profile_url else None, File "a:\Work\piton\discord3\venv\lib\site-packages\youtube_dl\extractor\common.py", line 1012, in _search_regex raise RegexNotFoundError('Unable to extract %s' % _name) youtube_dl.utils.RegexNotFoundError: Unable to extract uploader id; please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "a:\Work\piton\discord3\venv\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped ret = await coro(*args, **kwargs) File "a:\Work\piton\discord3\main.py", line 37, in play info = ytdl.extract_info(url, download=False) File "a:\Work\piton\discord3\venv\lib\site-packages\youtube_dl\YoutubeDL.py", line 808, in extract_info return self.__extract_info(url, ie, download, extra_info, process) File "a:\Work\piton\discord3\venv\lib\site-packages\youtube_dl\YoutubeDL.py", line 824, in wrapper self.report_error(compat_str(e), e.format_traceback()) File "a:\Work\piton\discord3\venv\lib\site-packages\youtube_dl\YoutubeDL.py", line 628, in report_error self.trouble(error_message, tb) File "a:\Work\piton\discord3\venv\lib\site-packages\youtube_dl\YoutubeDL.py", line 598, in trouble raise DownloadError(message, exc_info) youtube_dl.utils.DownloadError: ERROR: Unable to extract uploader id; please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "a:\Work\piton\discord3\venv\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke await ctx.command.invoke(ctx) File "a:\Work\piton\discord3\venv\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke await injected(*ctx.args, **ctx.kwargs) # type: ignore File "a:\Work\piton\discord3\venv\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: DownloadError: ERROR: Unable to extract uploader id; please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output.
Хочу сделать музыкального бота для дискорд на пайтон чтобы он воспроизводил видео из ютуба в войс чате и выдаёт ошибку что делать??
но выдаёт ошибку:
Traceback (most recent call last):
File «C:\Users\Влад\Desktop\ботик\music.py», line 6, in
client = commands.Bot(command_prefix=’!’)
TypeError: __init__() missing 1 required keyword-only argument: ‘intents’
import discord import youtube_dl from discord.ext import commands # Создаем экземпляр клиента Discord client = commands.Bot(command_prefix='!') # Функция для загрузки и проигрывания аудио из YouTube async def play_song(ctx, url): # Создаем экземпляр загрузчика YouTube ydl_opts = with youtube_dl.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(url, download=False) url2 = info['formats'][0]['url'] # Подключаемся к голосовому каналу voice_channel = ctx.author.voice.channel voice_client = await voice_channel.connect() # Проигрываем аудио в голосовом канале source = await discord.FFmpegOpusAudio.from_probe(url2, method='fallback') player = voice_client.play(source) # Ожидаем окончания проигрывания await ctx.send(f'Сейчас играет: ') while not player.is_done(): await asyncio.sleep(1) # Отключаемся от голосового канала await voice_client.disconnect() # Команда для проигрывания музыки @client.command() async def play(ctx, url): await play_song(ctx, url) # Запуск бота client.run('Токен бота') # Укажите токен вашего бота Discord
- Вопрос задан 27 февр. 2023
- 180 просмотров
4 комментария
Простой 4 комментария
Создаём Discord-бота на Python
Сегодня мы напишем Discord-бота с помощью Python и discord.py. А также посмотрим на примеры ботов.
Всем привет, сегодня мы напишем Discord-бота на Python и discord.py + бонусом посмотрим на примеры ботов. Приступим ?
Перед работой
Перед тем, как начать, вам нужны:
- Python 3;
- discord.py;
- Discord-аккаунт и свой сервер.
Для установки discord.py воспользуйтесь пакетным менеджером:
pip3 install discord.py
Создаём нашего бота
Перейдите на Developer Portal и нажмите на New application.
Вы создали своё приложение, на странице приложение перейдите в Bot >> Add Bot и создайте своего Discord-бота.
Сохраните токен бота! Дальше он нам понадобится!
Если всё прошло успешно, поздравляю, половина дела сделана ?
Добавление бота на сервер
Теперь можно добавить бота на сервер.
Перейдите в OAuth2 >> URL Generator, в Scopes выбираем Bot и ниже — права бота, копируем сгенерированный URL. Вставляем в браузер, и добавляем на наш сервер.
Эхо-бот
Напишем традиционного эхо-бота, и разберём каждую строчку кода.
import discord from discord.ext import commands config = < 'token': 'your-token', 'prefix': 'prefix', >bot = commands.Bot(command_prefix=config['prefix']) @bot.event async def on_message(ctx): if ctx.author != bot.user: await ctx.reply(ctx.content) bot.run(config['token'])
import discord from discord.ext import commands
Нужные нам импорты.
config =
Вспомогательный словарь config в котором храним токен и префикс команд (далее расскажу зачем нужен префикс команд).
bot = commands.Bot(command_prefix=config['prefix'])
Создаём нашего бота, в аргументе передаём префикс.
@bot.event
Декоратор, предназначенный для обработки событий, подробнее здесь.
async def on_message(ctx):
Создаём асинхронную функцию, с параметром ctx, представляет из себя сообщение.
if ctx.author != bot.user:
Проверка, не является ли автор сообщения нашим Discord-ботом. Дело в том, что если бот отправит сообщение, это будет новым событием, и тогда получается цикл.
await ctx.reply(ctx.content)
Отвечаем на сообщение (ctx.reply), в аргументы передаём сообщение (ctx.content).
bot.run(config['token'])
Запускаем нашего бота, в аргументы передаём токен бота.
Надеюсь вы разобрались с кодом, и мы можем переходить далее.
Обработка команд
Перед тем, как обрабатывать команды, нам пригодится наш префикс.
import random import discord from discord.ext import commands config = < 'token': 'your-token', 'prefix': '$', >bot = commands.Bot(command_prefix=config['prefix']) @bot.command() async def rand(ctx, *arg): await ctx.reply(random.randint(0, 100)) bot.run(config['token'])
@bot.command()
Декоратор обработки команд
async def rand(ctx, *arg):
Асинхронная функция rand
await ctx.reply(random.randint(0, 100))
Отвечаем на сообщение, в аргументы передаём случайное число от 0 до 100
Бонус
import random import discord from discord.ext import commands config = < 'token': 'your-token', 'prefix': '$', >bot = commands.Bot(command_prefix=config['prefix']) @bot.command() @commands.has_role("Хозяин") async def rand(ctx, *arg): await ctx.reply(random.randint(0, 100)) bot.run(config['token'])
import discord from discord.ext import commands config = < 'token': 'your-token', 'prefix': '$', >bot = commands.Bot(command_prefix=config['prefix']) @bot.command() async def kick(ctx, user : discord.User(), *arg, reason='Причина не указана'): await bot.kick(user) await ctx.send('Пользователь был изгнан по причине ""') bot.run(config['token'])
Как сделать музыкального бота в Discord?
Сразу извиняюсь, если вопрос глупый, но я не могу понять из-за чего эта ошибка. Сам бот заходит в голосовой канал и подсвечивает, т.е. работает, но ничего не слышно.

import asyncio import discord import youtube_dl from discord.ext import commands # Suppress noise about console usage from errors youtube_dl.utils.bug_reports_message = lambda: '' ytdl_format_options = < 'format': 'bestaudio/best', 'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s', 'restrictfilenames': True, 'noplaylist': True, 'nocheckcertificate': True, 'ignoreerrors': False, 'logtostderr': False, 'quiet': True, 'no_warnings': True, 'default_search': 'auto', 'source_address': '0.0.0.0' # bind to ipv4 since ipv6 addresses cause issues sometimes >ffmpeg_options = < 'options': '-vn' >ytdl = youtube_dl.YoutubeDL(ytdl_format_options) class YTDLSource(discord.PCMVolumeTransformer): def __init__(self, source, *, data, volume=0.5): super().__init__(source, volume) self.data = data self.title = data.get('title') self.url = data.get('url') @classmethod async def from_url(cls, url, *, loop=None, stream=False): loop = loop or asyncio.get_event_loop() data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream)) if 'entries' in data: # take first item from a playlist data = data['entries'][0] filename = data['url'] if stream else ytdl.prepare_filename(data) return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data) class Music(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def join(self, ctx, *, channel: discord.VoiceChannel): """Joins a voice channel""" if ctx.voice_client is not None: return await ctx.voice_client.move_to(channel) await channel.connect() @commands.command() async def play(self, ctx, *, query): """Plays a file from the local filesystem""" source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(query)) ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None) await ctx.send('Now playing: <>'.format(query)) @commands.command() async def yt(self, ctx, *, url): """Plays from a url (almost anything youtube_dl supports)""" async with ctx.typing(): player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True) ctx.voice_client.play(player, after=lambda e: print('Player error: %s' % e) if e else None) await ctx.send('Now playing: <>'.format(player.title)) @commands.command() async def stream(self, ctx, *, url): """Streams from a url (same as yt, but doesn't predownload)""" async with ctx.typing(): player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True) ctx.voice_client.play(player, after=lambda e: print('Player error: %s' % e) if e else None) await ctx.send('Now playing: <>'.format(player.title)) @commands.command() async def volume(self, ctx, volume: int): """Changes the player's volume""" if ctx.voice_client is None: return await ctx.send("Not connected to a voice channel.") ctx.voice_client.source.volume = volume / 100 await ctx.send("Changed volume to <>%".format(volume)) @commands.command() async def stop(self, ctx): """Stops and disconnects the bot from voice""" await ctx.voice_client.disconnect() @play.before_invoke @yt.before_invoke @stream.before_invoke async def ensure_voice(self, ctx): if ctx.voice_client is None: if ctx.author.voice: await ctx.author.voice.channel.connect() else: await ctx.send("You are not connected to a voice channel.") raise commands.CommandError("Author not connected to a voice channel.") elif ctx.voice_client.is_playing(): ctx.voice_client.stop() def setup(client): client.add_cog(Music(client)) print('Music: activated')
Ignoring exception in command yt: Traceback (most recent call last): File "C:\Users\volva\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "C:\Users\volva\Desktop\botTest\cogs\music.py", line 82, in yt player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True) File "C:\Users\volva\Desktop\botTest\cogs\music.py", line 52, in from_url return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data) File "C:\Users\volva\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\player.py", line 225, in __init__ super().__init__(source, executable=executable, args=args, **subprocess_kwargs) File "C:\Users\volva\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\player.py", line 138, in __init__ self._process = self._spawn_process(args, **kwargs) File "C:\Users\volva\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\player.py", line 147, in _spawn_process raise ClientException(executable + ' was not found.') from None discord.errors.ClientException: ffmpeg was not found. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\volva\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke await ctx.command.invoke(ctx) File "C:\Users\volva\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "C:\Users\volva\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ClientException: ffmpeg was not found.
- Вопрос задан более двух лет назад
- 9645 просмотров