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

Как написать музыкального бота для дискорда python

  • автор:

Python Discord Bot: Play Music and Send Gifs

In this tutorial, we’ll make a Python Discord bot that can play music in the voice channels and send GIFs. Discord is an instant messaging and digital distribution platform designed for creating communities. Users can easily enter chat rooms, initiate video calls, and create multiple groups for messaging friends.

We’ll skip the basics and jump straight over to the music playing. Check out this Medium article to catch up on the basics of setting up your bot. In the end, our Python Discord bot will look like the cover image of this article!

Before we dive in: remember to allow Administrator permissions for the bot.

Thanks to Rohan Krishna Ullas, who wrote this guest tutorial! Make sure to check out his Medium profile for more articles from him. If you want to write for Python Land too, please contact us.

Table of Contents

Part 1: Importing all the libraries

First, create a virtual environment and install the requirements:

Next, let’s set up the .env file for our project. Create a .env file so that we can separate the environment configuration variables (these are variables whose values are set outside the program) from the main code:

Then use Python import to load all the needed modules in the main file app.py :

The module youtube_dl is an open-source download manager for video and audio content from YouTube and other video hosting websites.

Now we need to set intents for our bot. Intents allow a bot to subscribe to specific buckets of events, allowing developers to choose which events the bot listens to and to which it doesn’t. For example, sometimes we want the bot to listen to only messages and nothing else.

Part 2: Using youtube_dl to download audio

The next step in building our Python Discord bot is dealing with the part that actually downloads the audio file from the video link we provide. Please note that this bo is just a demonstration. It’s not illegal to download from YouTube for personal use according to this article, but it might be against the YouTube Terms Of Service. Please be sensible and use this for personal use only.

The from_url() method of YTDLSource class takes in the URL as a parameter and returns the filename of the audio file which gets downloaded. You can read the youtube_dl documentation at their GitHub repository.

Part 3: Adding commands to the Python Discord bot

Now let’s add the join() method to tell the bot to join the voice channel and the leave() method to tell the bot to disconnect:

Here we first check if the user who wants to play music has already joined the voice channel or not. If not, we tell the user to join first.

Awesome! Give yourself a pat on the back if you’ve reached this far! You’re doing great. In the next step, we’ll add the following methods:

  • play()
  • pause()
  • resume()
  • stop()

At this point, we need to have the ffmpeg binary in the base directory. It can be downloaded from https://ffmpeg.org/. In this case, I used the exe since I’m using a Windows machine.

Part 4: Running the Python Discord bot locally

Add the final piece of code to start the bot and it’s done:

To deploy the bot locally, activate the virtual environment and run the app.py file:

Bonus: send GIFs on start-up and print server details

In this bonus section, we will set up our bot to listen to events such as start-up. This example sends a previously downloaded GIF image to the text channel when the bot is activated:

To print server details such as owner name, the number of users, and a server id, we can add a bot command ‘where_am_i’:

This is what this will look like:

Printing server details — Image by author

You can view and clone the complete results from my Discord-Bot GitHub Repository.

That’s it! We made a Python Discord bot. Thank you for reading, and don’t hesitate to leave a reply or ask your questions in the comments section.

Get certified with our courses

Learn Python properly through small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

Как создать музыкального бота в Discord с использованием Python

В этой статье мы рассмотрим, как создать музыкального бота для Discord с использованием языка программирования Python и библиотеки discord.py .

Шаг 1: Установка необходимых библиотек

Установите библиотеку discord.py и youtube_dl с помощью следующих команд:

Шаг 2: Создание и настройка бота в Discord

  1. Перейдите на сайт Discord Developer Portal.
  2. Нажмите кнопку «New Application» и введите имя для вашего бота.
  3. Перейдите на вкладку «Bot» и нажмите кнопку «Add Bot».
  4. Скопируйте токен бота, он потребуется для авторизации в коде Python.

Шаг 3: Создание основного кода бота

Создайте новый файл Python и импортируйте необходимые библиотеки:

Затем создайте экземпляр бота:

Добавьте событие, которое будет вызываться при готовности бота:

Добавьте команду !join , чтобы бот присоединялся к голосовому каналу:

Добавьте команду !leave , чтобы бот выходил из голосового канала:

Добавьте команду !play для воспроизведения видео с YouTube:

Добавьте команду !pause для приостановки воспроизведения:

Добавьте команду !resume для продолжения воспроизведения:

Запустите бота, передав токен, скопированный на шаге 2:

Шаг 4: Запуск бота

Запустите файл Python, и ваш музыкальный бот для Discord будет работать. Теперь вы можете использовать команды !join , !leave , !play , !pause и !resume для управления воспроизведением музыки в голосовом канале.

How do I make my discord.py bot play mp3 in voice channel?

I’m a beginner in Python and I have recently started making a discord bot for some friends and I. The idea is to type !startq and have the bot join the channel, play an mp3 file that is locally stored in the same folder that the bot.py is in also.

So far my bot joins the channel fine, but it doesn’t actually play the mp3. I’ve asked countless people in the «Unofficial Discord API Discord» and a few other programming Discords, but I haven’t gotten an answer yet.

Как получать музыку из ВКонтакте в 2022 году

При проектировании проекта, я решил разделить его на две части. Первая — получение музыки из ВК. Вторая — сам бот. И начать я решил с первой части.

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

Я решил посмотреть что сейчас отдает ВКонтакте при воспроизведении записи и полез во вкладку network, вот что я там увидел:

Нас интересует index.m3u8Нас интересует index.m3u8 Открыв его мы видим GET запрос на сгенерированный ВКонтакте urlОткрыв его мы видим GET запрос на сгенерированный ВКонтакте url А ответ этого запроса представляет из себя просто HLS формат, с сегментами и их ключами декодирования если они закодированыА ответ этого запроса представляет из себя просто HLS формат, с сегментами и их ключами декодирования если они закодированы

Теперь передо мной стояла новая задача, как получить с определенного аудио нужную ссылку на m3u8 файл и уже потом думать как его разбирать и собирать в дальнейшем в цельным mp3 файл.

В ходе раздумий был найден довольно простой вариант в виде библиотеки для питона vk_api и реализация получения такой ссылки через эту библиотеку выглядит так:

Вот мы и получили ссылку на этот файл и встал вопрос, а что делать дальше. Я попробовал запихнуть эту ссылку в ffmpeg и уже было обрадовался, ведь он скачал мой заветный аудиофайл и сразу же сделал конвертацию в mp3, однако, счастье мое длилось не долго, ведь ffmpeg хоть и скачал все сегменты, самостоятельно склеив их, но зашифрованные сегменты он не расшифровал, поэтому давайте еще раз взглянем на внутренности m3u8 файла

Мы видим, что перед зашифрованными сегментами в EXT-X-KEY указан метод шифровки AES-128 и ссылка на скачку ключа для расшифровки.

Для решения уже этой проблемы была найдена прекрасная библиотека m3u8 и pycryptodome:

И наконец конвертируем все в mp3 формат, для чего нам понадобится установленный ffmpeg на ПК.

Для меня это был довольно интересный опыт, поскольку я никогда до этого в своей жизни не работал с зашифрованными файлами и HLS протоколом, надеюсь Вам тоже было интересно читать это. Так же надеюсь я смог помочь другим людям, ведь никаких решений по скачиванию аудио с ВКонтакте на питоне в 2022 году я не нашел.

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

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