код музыкального бота на python для дискорда
Python Discord Bot: Play Music and Send Gifs
Last updated on April 17, 2021
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.
Part 1: Importing all the libraries
First, create a virtual environment and install the requirements:
Then import all the needed libraries 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:
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, number of users, 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.
About the author
Erik van Baaren
Erik is the owner of Python Land and the author of many of the articles and tutorials on this website. He’s been working as a professional software developer for 25 years, and he holds a Master of Science degree in computer science. His favorite language of choice: Python!
Код музыкального бота на python для дискорда
Created by Robert USF Computer Science.
This is a personal project of mine to create an easy to use and reliable discord music bot. I hope you can find use in it as well! Check out our other project written in Node.js: https://github.com/RobertAndion/DiscordMusicBotNode
You must have java 11 (or java 13) for lavalink. The bot is written in and requires Python3 You must install python-dotenv, discord.py, lavalink.py and psutil, links are listed below.
(psutil does not need to be installed if cpu functions are not needed, see more below.)
Lava link is not my creation and can be found at: https://github.com/Frederikam/Lavalink/releases (It can also be found in other Git branches. Any should be fine) The lavalink.jar, MUST BE DOWNLOADED AND PLACED IN DIRECTORY
If you want to change the lavalink password you must change it in the application.yml and in both music.py and playlist.py on the commented lines where ‘changeme123’ is located.
Docker start command:
After this you can exit the container and rename it using
and then use the container id in the following command:
Now the automatic start file will boot up the container and automatically run the bot inside, if the instructions below are followed.
Automatic Docker Startup
Then choose nano if you are unfamiliar with linux editors, or pick your favorite editor. Add the following line to the bottom of the file it opens
Now upon the main server restarting it will start up the docker container and run the bot inside.
Full installation instructions:
How to install packages
First ensure that you have python3 installed on your system, to do so enter python3 into a terminal and you should be greeted by the python command line interface, to exit type quit() Now that you have made sure you have python3 install pip.
Now that you have pip installed you can reference the links above on how to install each package with pip commands. For example to install lavalink it is as simple as:
(Some will only need pip while other OS will need pip3 to be specified.)
The sections below will cover starting the bot with the Reboot command enabled or running it without. I personally use Reboot often as many of the issues you may run across only need a quick reboot to get working again.
Reboot command configuration
In order to use the new Reboot command you need to run the bot using tmux. Installing tmux is simple
Running the bot with reboot capabilities:
In order to start the bot run
This will set up tmux with the proper session names in order to use the scripts provided. This is a helpful new feature thats saves the time of having to log into the bot and reboot it manually. Many issues are quickly solved with a reboot.
Running the bot without reboot command capabilities:
run the lavalink server using the command:
Then run the bot in a separate terminal using:
Both terminals must remain running for the bot to be live, consider using tmux.
Before many commands will work, an initial «play» command will need to be made. Once this is done once it will not need to be redone for the entirety of the bots run time. This is not something to be fixed. The player object doesn’t exist until at least one play related command has been issued in a session. Most commands have error handling for this now, run a play or playl command before trying to pause or unpause etc. (makes logical sense anyways.)
Preparing to use the bot:
In order for music commands you must make a «Dj», «Administrator» or «DJ» role in discord and assign it to those you want to be able to play songs. (Future releases will have variable role names you can set in the code)
Admin functions will either need kick ban permissions for some commands or an «Admin» or «Administrator» role. Everything is essentially role based to keep unwanted users from flooding the bot.
Anything in <> is an argument required by the function. Anything in () are alternate command shortcuts/names
This command, if you are a server admin, will send you a private message with a short summary of how to use the bot. It has no other function.
This command will reboot both Lavalink and the bot directly from discord. This command is tied to the owners discord ID so only the server owner may reboot. Please read more about how to set it up above. Note: This function should be used before trying clearcache to fix bot errors. To not use this function remove line 4, and 40-44 in bot.py
This command will only work for the bot owner and will private message them a zip file of all playlists. This is especially useful for Docker containers where the only thing you would need out before making a new version are the playlists.
If the person using the command is in a voice channel and the bot has access to that channel it will connect and play the song listed. This is also the command to continue adding songs to the queue, it covers both functions. The bot will auto disconnect when the end of the queue is reached.
If the bot is playing a song it will skip to the next song as long as the person is in the same voice channel as the bot. If there are no songs after the bot will automatically disconnect. The argument can be used to say how many songs to skip.
This will clear all songs including now playing and the queue. This is the best way to disconnect the bot, because it flushes everything first. Disconnect is still a command but will be removed in the future.
Removed completely now, will be removed on next readme update/release.
This command will disconnect the bot, however it is bad practice in most cases. It will not stop the playing of songs or clear the queue. clear is the preferred command. This has now been removed. It is still present in the code but commented out. Not recomended
This command is a useful one to pause the bot. The command has now been update. It will now unpause automatically after 7 minutes of being paused. This can be changed manually under the pause command. change the sleep(number of seconds here) to any amount of time. Other commands can still be used including unpause during this «wait» period.
This will unpause a currently paused bot. (Should come after a pause command) This will automatically happen after 7 minutes afte a pause command by default.
This will list all songs to be played next in pages of 10 with the currently playing song at the top of page 1 labeled as NP. The current page and total pages are displayed at the bottom, like so, Page: 5/6 means you are on page 5 out of a total of 6 pages. No argument assumes page one, negative or 0 goes to page 1 and a page larger than the total goes to the last page.
This no longer uses the given shuffle function from lavalink. It is a custom function that shuffles in a finalized form, viewable in the queue command.
Currently removed So far I have not needed this with the new API so it has been removed.(Dangerous anyways) Warning This is to be used as a last resort ONLY. Better to reboot the bot. This will clear the player cache from your server. Do not do this for minor issues, try restarting the bot (and/or Lavalink) first, or kicking it and reinviting it. This command can currupt data, the bot MUST be disconnected before using this. Furthermore for the safety of this command it is restricted to those with administrator permissions only.
This will list the specific songs contained inside the specified playlist. Nothing needs to be playing to use this command. If you have more than 20 songs in a playlist, they will now send in pages of 20 to avoid «invisible» playlists if they are too big. (No need to be in a voice channel to use this command)
This will list all of the users playlists whether or not the user is in a voice channel. The playlists will now show up in pages of 10, if you have more than 10 playlists provide the page number you wish to go to after lpl (page total listed on the bottom similar to the queue command.)
This will delete the entire playlist given with no confirmation and no reclamation. Be certain before you delete as it is permanant.
This function takes two paramaters, seperated by spaces. The first is the song number and the second is the name of the playlist to delete the song from.
This function will create a playlist of the given name. The first song will be the song currently playing from the bot. If nothing is playing the command will fail not work.
Adds the currently playing song to the given playlist. Case sensitive. If the playlist does not exist or no song is playing this will fail not work.
This will play the entire playlist name given. Case sensitive. It will take some time to load all songs, it will print a message when it is completely done.
This function will rename an existing playlist. The names must be seperated by a comma and no spaces before or after the comma.
This function will add the entire queue to a given playlist. It does not add the currently playing song, this way if you make a playlist just for the queue, it will not add the currently playing song twice.
These require either «Administrator» or «Admin» commands for more advanced commands while intuitive ones like ban and kick only require those permissions.
This will kick the named user out of the server. It requires the ban and kick permissions.
This will ban the named user from the server. It requires the ban and kick permissions.
Used to assign a role to a user on text command. Once this is done that role will be locked to bot control. The first argument is the @user and he second is the name of the roll. Requires «Admin» or «Administrator» role.
This will move the given user into the channel name listed. Requires the «Administrator» or «Admin» role.
This will disconnect the named user from voice channels. Requires the «Administrator» or «Admin» role.
The Administration functions can be removed if undesired by deleting Admin.py from the directory and removing line 29 from bot.py
‘client.load_extension(‘Admin’)’ This is the command that loads in the Cog.
In order to use the welcome functions you must enable «Privileged Gateway Intents» on the discord developer page under the Bot section. Enable the «SERVER MEMBERS INTENT» this will allow the function to welcome new members.
These are automated functions that will activate on a new member joining. They will be greeted in your «general» chat and given the role «Example» automatically. These should be changed to your unique needs, and the role should be created and customized in your server first. If you do not want automatic roles the two lines to remove are marked in the welcome.py file. There are also comments there that direct you how to changed the channel the announcement will be placed in. There is also the option to change the printed message.
NOTE: The role will follow any server you add it to and fail. If you plan to have the bot in more than one server add the following instead of the current two lines for the role.
This will make it so the role function only applies to your server. You can put the greeting under this protection as well, however most servers have a general chat. The name of the user and of the server are dynamicaly coded.
(FUTURE: In the future the if statement above will not be needed. Server specific files will be created and managed through the bot to control this.)
The welcome functions can be removed by deleting line 30 in bot.py and deleting welcome.py. ‘client.load_extension(‘welcome’)’ This is the command that loads in the Cog. You must also delete line 8 and 9 from bot.py to remove discord intents if you do not want to use welcome functions.
All the functions in fileRead are used by commands and require no command to use (Helper functions).
NOTE: cpu.py is a new option and will require extra work to get working.
If this functionality is undesired you can remove line 34 from bot.py and delete cpu.py. You will also not need the psutil package
This will show current cpu information such as % usage, load and temperature. The temperature will take some adjustment to get working. First change line 29 in cpu.py to:
This will print a full JSON package of the available sensors then select the proper one as I did for one server in the actual code.
This provides more permanant information such as thread count, RAM, and currently available RAM. (Should be cross system compatible.)
Todo/Possible adds in the future: Add the option to customize the message and role given through discord commands. Future update coming. Add a delete from queue function that removes a specific song from the queue based on position. Update: The custom function for shuffling has been done.
About
Discord Music Bot. Play, Playlist, Welcome and Administrative commands.
Создание Discord-бота на Python. Часть 1
Версия Python: 3.8.2
Версия discord.py: 1.3.3
Приветствую, хабровчане и другие пользователи интернета. Сегодня я начну цикл статей, посвящённых созданию Discord-бота с помощью библиотеки discord.py. Мы рассмотрим создание как и примитивного бота, как и «продвинутого» бота с модулями. В этой статье мы сделаем стандартную команду и ещё одну небольшую команду. Начнём!
Создание бота и получение токена
Для того, чтобы добавить бота на сервер нужно создать свое приложение и во вкладке General Information скопировать Client ID.
Здесь заменяем CLID на ранее скопированный Client ID.
Во вкладке Bot создаём бота и копируем токен.
Написание кода
Устанавливаем саму библиотеку.
Создаём файл config.py (так удобнее), и создаём там словарь.
Создаём main-файл, название может быть любое.
Импортируем библиотеки и наш файл конфига:
Создаём «тело» бота, название может быть любое:
Начинаем писать основной код.
В конце запускаем бота с помощью:
Должно получится так:
Бонусный туториал!
Сделаем вывод случайных картинок с лисами
Для этого импортируем еще пару библиотек:
Приступим к написанию команды.
Должно получится так:
Конец
На этом 1 часть закончена. Скоро будет опубликована 2 часть.
Код музыкального бота на python для дискорда
Thanks for 25k Views with 500 subs!
Discord.js v13 will break this bot so do not use this with it. We have been started working on v5 which will be out in some days/months with new features and much more are on the way.
NOTE: Lavalink is needed for music functionality. You need to have a working Lavalink server to make the bot work.
A Tutorial has been uploaded on YouTube, Watch it by clicking on the image down below
If you have major coding issues with this bot, please join and ask for help.
Note: If you are hosting your bot in heroku, Please consider upgrading your dyno for running dashboard & bot simultaneously because in free dyno it’ll run out of memory(as there are two workers). If you want to run only the bot, turn off the web dyno.
Contributions are always welcomed 😀 Make sure to follow Contributing.md
Note: Contributions are not accepted in the master branch. If you like to contribute check out v5 branch
Made with ❤️ and JavaScript!
About
An advanced discord music bot, supports Spotify, Soundcloud, YouTube with Shuffling, Volume Control and Web Dashboard with Slash Commands support!
Discord бот на Python
В данной статье мы создадим Discord бот, используя при этом только Python.
Краткая информация о Discord для тех, кто еще о нем не знает
Discord — это, фактически, универсальная платформа голосового и текстового общения для геймеров.
Игроки, стримеры, студенты и разработчики используют Discord, чтобы обсуждать игры, отвечать на вопросы, общаться в чате во время игры в хорошем качестве, в том числе с членами своей команды. В нем даже есть игровой магазин с критическими отзывами и возможностью подписки. По сути, это центр игровых сообществ.
Хотя есть много вещей, которые вы можете создать с помощью API Discord, в этом руководстве мы остановимся на создании бота на Python.
Необходимые приготовления
Чтобы создать Discord бот, вам понадобится:
Что такое боты?
Бот (сокращение от «робот») — это программа, которая выполняет автоматические, повторяющиеся и заранее определенные задачи. Боты обычно имитируют человеческое поведение или подменяют его. Поскольку все их действия автоматизированы, они работают намного быстрее, чем обычные пользователи.
Боты очень часто используются для ответов на типовые вопросы, возникающие в различных сообществах. Они действуют как своего рода представители человека для выполнения различных функций. Основной особенностью такого бота является то, что он устраняет необходимость вручную отвечать каждому участнику и полностью автоматизирует данный процесс.
Для чего нужны чат-боты
Автоматизация ответов на основные вопросы
В любой области деятельности всегда есть вопросы, которые пользователи задают чаще всего. И на эти вопросы каждый раз надо давать одни и те же ответы. Лучшее решение в таком случае — чат-бот.
Ускорение рабочих процессов
Чат-боты, в отличии от людей, никогда не устают. Все люди могут работать только ограниченный период времени, в то время как у ботов таких ограничений нет. Использование чат-ботов в бизнесе хорошо дополняет работу людей, повышает производительность труда и сокращает человеческий труд.
Экономия денег и времени
При правильном использовании дружелюбного чат-бота привлечение клиентов происходит с минимальными затратами и максимальной эффективностью.
Марк Лутц «Изучаем Python»
Скачивайте книгу у нас в телеграм
Пишем код для чат-бота
Сперва убедитесь, что на вашем компьютере установлен Python. Если его еще нет, то загрузите его с официального сайта.
Среду программирования можно использовать любую, какая вам больше нравится. Например, PyCharm, VS Code или Sublime.
Теперь выберите опцию New application (новое приложение) в правом верхнем углу страницы и дайте вашему новому приложению имя. Как видите, можно даже добавить изображение к аватару вашего бота. Мы можем сделать это позже. Сейчас пойдем в раздел Bot (на странице слева) и выберем опцию Add bot (добавить бота).
Затем откройте ссылку под секцией scope в новом окне и выберите сервер, на котором вы желаете видеть ваш бот.
Для этого введем следующую команду:
Основная задача нашего тестового бота будет состоять в том, чтобы давать ответ всем пользователям на их сообщение «Hello». Но вы, конечно, можете его настроить в соответствии с вашими потребностями.
Для начала импортируем необходимые библиотеки:
Создадим переменную Client :
Напишем следующий код для определения статуса бота:
Это сообщение будет отображаться всякий раз, когда вы размещаете своего бота в сети. Вы также можете проверить статус бота из самого Discord.
Это сообщение подтверждает, что наш бот готов к использованию на сервере.
Теперь, когда бот готов к работе, мы можем ответить пользователям на их приветствие hello :
Для запуска бота нам понадобится токен. Он находится в разделе Bot на сайте Discord. Мы заходили туда при создании бота.
Теперь настало время запустить нашего бота!
Откройте CMD и наберите следующую команду:
Если так не выходит, то наберите вот это:
Точно таким же образом пишем бот для приветствия новых участников:
Возможные проблемы при создании бота
Все может быть не так просто, как это кажется на первый взгляд. Вы обязательно должны помнить о проблемах, с которыми можете столкнуться при создании бота. Некоторые из них мы перечислили ниже:
Заключение
Мы рассмотрели, как создать Discord бот на Python. Разумеется, это был простейший бот. Но вы, конечно же, можете написать свой собственный код и добавить множество различных функций, например OCR.