Как сделать бота для музыки в дискорде python
Перейти к содержимому

Как сделать бота для музыки в дискорде python

  • автор:

Проигрывание музыки из файла

Приветствую всех, решил вот создать своего бота, для того что бы он проигрывал одну песню которая загружена у меня на компьютере, но не понимаю как сделать его через библиотеки дискорда может у кого есть идеи как это воплотить. Если код пришлете то буду доволен как слон!

Добавлено через 29 минут
Это пример того что я сам пытался сделать

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
@bot.command() async def play(ctx): song_there = os.path.isfile('song.mp3') try: if song_there: os.remove('song.mp3') print('[log] Udalil') except PermissionError: print('[log] Nety file') await ctx.send('Ща бед апл будет, тише') voice = get(bot.voice_clients, guild = ctx.guild) for file in os.listdir('./'): if file.endswith('.mp3'): name = file voice.play(discord.play('song.mp3'), after = lambda e: print(f'[log] zakonchil')) voice.source = discord(voice.source) voice.source.volume = 0.07 song_name = name.rsplit('-', 2) await ctx.send(f'Играет бэд эппл: ')

Лучшие ответы ( 1 )
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:

Проигрывание музыки
Помогите пожалуйста, вот создал Windows forms все сделал, теперь я хочу сделать, чтоб при его.

Проигрывание музыки.
Есть ли среди функций WinAPI или может быть в каких-нибудь библиотеках для Си(не Си++) функции для.

Проигрывание музыки из интернета
В общем, надо что-то вроде mediap.setDataSource("http://ссылка на канал аудио"); .

Проигрывание музыки на сайте
Народ как мне сделать что бы треки проигрывались друг за другом без остановки вот с помощью этого.

Проигрывание музыки в MASM 32
Mihael Здравствуйте,помогите сделать меню к программе, для проигрывания музыки в MASM 32 .486.

Регистрация: 15.08.2021
Сообщений: 60

Лучший ответ

Сообщение было отмечено eL3ctr0 как решение

Решение

1. Устанавливаем библиотеку дискорд
2. Устанавливаем ffmpeg
3. Пишем код

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
import asyncio import discord from discord.ext import commands 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""" await ctx.send(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""" query = "---ФАЙЛ---"#Сюда указываем полный путь на файл (C:\Users\Admin\Music\song.mp3) ctx.voice_client.play(query, after=lambda e: print(e)) await ctx.send(f'Сейчас играет: ') @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(f"Changed volume to %") @commands.command() async def stop(self, ctx): """Stops and disconnects the bot from voice""" await ctx.voice_client.disconnect() @play.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.") bot = commands.Bot(command_prefix=commands.when_mentioned_or("$$"),#Тут можно поменять префикс вашего бота description='Relatively simple music bot example') @bot.event async def on_ready(): print(f'Logged in as (ID: )') print('------') bot.add_cog(Music(bot)) bot.run('ТОКЕН')#Тут указывает токен вашего бота

Вместо полного пути на файл можно указать только название файла с его расширением, но он должен лежать вместе с вашим кодом в одном каталоге.

Музыкальный бот для 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. 

Saved searches

Use saved searches to filter your results more quickly

Cancel Create saved search

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

�� Русский музыкальный бот Python

Luffich/st-comunity-music

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Switch branches/tags
Branches Tags
Could not load branches
Nothing to show
Could not load tags
Nothing to show

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Cancel Create

  • Local
  • Codespaces

HTTPS GitHub CLI
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more about the CLI.

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Как создать Discord-бота на Python. �� (Discord.py)

Приветик всем! ��
С вами я, Данил. Сегодня, мы с вами создадим своего собственного бота на языке программирования Python. Если кто не знает, что такое Python, почитать можно по ссылке:

7.1K открытий

Что ж, если вы все готовы, то начинаем! ��

Во первых, импортируем библиотеку которая называется Discord (Discord.py).

Для этого напишем вот такой простенький скрипт:

Там нажимаем кнопку New Application.

Ну что, удачи! Всем пока! ��

10 комментариев
Написать комментарий.

Окей. В следующий раз попробую немного поподробнее рассказать. Всё для вас дорогие читатели. 🙂

Развернуть ветку
Аккаунт удален
Развернуть ветку
Аккаунт удален
Развернуть ветку

а нет инструкции или ссылки, как мне можно, используя, например, URLs из текстового сайта, сохранить все файлы себе на компьютер (на любом диске, это неважно), но при этом сохранив внутреннюю структуру подпапок и файлов?

идеально:
я указываю путь на локально компе к текстовому файлы, содержимое которого, — строки внешних URLs, ведущие к файлам

скрипт должен создать массив всех ссылок, скачать каждый файл и сохранить их, используя относительный адрес, локально, чтобы сохранилась структура

после выполнения скрипта, например, на диске D создать папку site с содержимым:
file1
file4
folder1/file1
folder2/file2
folder3/file3

то есть, это такой себе парсер, используя текстовый файл


если есть готовые варианты, когда вместо текстового файла используется браузер, тоже подходит. просто в таком случае, мне кажется, что нужно использовать драйвер браузера типа как для селениума, чтобы эмулировать его работу и сохранять все get запросы в виде url (ибо банально один javascript файл может инициировать другие запросы друг за другом только во время загрузки iframe, например). короче говоря, я не совсем в таком случае понимаю, как, имея одну ссылку после загрузки которой идет обращение к множеству файлов вытащить весь список этих урлов программно. потому я подумал, что текстовик с готовым набором будет попроще для подобного парсера для начала

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *