An improved version of MusicBot.py, a multipurpose Discord bot. Now with Application commands, multi-guild, multi-website support and an extended moderation module alongside other new features!
main branch:
stable branch:
- Key features
- Quick start guide
- Full Setup Guide
- Create a Discord Application
- Set up a Bot
- Code setup
- Requirements
- Preparing the project directory
- Automatic environment setup
- Manual environment setup
- Usage
- Extra configuration
- Extending the Bot
- Troubleshooting
- Licensing
- Full application commands support for a more user-friendly interface.
- Multi-guild support.
- Improved playlist capabilities, with multi-playlist support and full control over them.
- Improved help command, with command-specific entries.
- Enhanced role-based command access system.
- Enhanced command functionality, with 40+ music commands and 15+ moderation commands.
- Multi-website support, with YouTube (search, video or playlist*), Newgrounds, SoundCloud (song, search or sets*) and Bandcamp (song or albums*).
- Guild and voice channel auto-cleanup functionality.
- Sharding support.
- Extendable with custom modules.
- Easily self-hostable.
*Support may depend on command.
-
Go through the full guide if you're inexperienced with setting up Discord bots.
Otherwise, here are the core commands for basic setup on UNIX-like systems with
git:git clone https://github.com/japaneseTemmie/MusicBot.py-2.0 cd MusicBot.py-2.0 echo "TOKEN=your_bot_token" > .env python3 start.py
- If you already have a bot, this section can be skipped. Ensure the needed permissions and intents are enabled and visit Troubleshooting section if your bot is in more than 2500 guilds.
- Visit the Discord Developer Portal, log in, and create a new app. You may customize it if you wish.
-
Navigate to the
Botsection.(Optional) Modify the name, avatar and banner to your liking.
-
Scroll down to
Privileged Gateway Intentsand enable everything. Save the changes. -
Scroll up to
Tokenand click onReset Tokento get your bot a new token, then copy it to your clipboard and paste it in a file for later use.Make sure to not share it with anyone. Treat it like a password.
-
Go to the
InstallationSection, uncheckUser installin theInstallation Contextsbox. -
In the
Default install settingsbox, includebotin theScopesentry and add the following permissions in thePermissionsentry (note that permissions can be disabled if related modules won't be used):Permission Category Permissions Server Management Manage Server, Manage Roles, Manage Channels, Manage Threads and Manage Messages Moderation Kick Members, Ban Members and Moderate Members Messaging Send Messages, Send Messages in Threads and Read Message History Voice Connect, Speak, Move Members, Mute Members Other Embed Links, Mention Everyone -
Save the changes. Copy the link provided in the
Install linkbox. Open it in a browser window and add your bot to your server.
-
UNIX-like/Windows OS. Code should work cross-platform, but works best on Linux (BSD/macOS not tested, but likely to work).
-
Make sure
Python 3.10+andFFmpegare installed on your system.-
On a GNU/Linux distribution, they may already be installed.
If not, make sure to install them from your distribution's repositories:
sudo apt install python3 ffmpeg(Debian, Debian-based distro (Ubuntu, Linux Mint, ZorinOS))sudo dnf install python3 ffmpeg(Fedora, Fedora-based distro (Bazzite, Nobara))sudo pacman -S python3 ffmpeg(Arch, Arch-based distro (CachyOS, Manjaro))... or compile them from source.
-
For Windows/macOS, you can find official download links & installation guides:
-
-
Test
PythonandFFmpeg-
Python:
python3 -V(UNIX-like)python -V(Windows)Expected output:
Python {VERSION} -
FFmpeg:
ffmpeg -version(UNIX-like/Windows)Expected output:
ffmpeg version {VERSION} ...
Project was tested on
Python 3.12.3andFFmpeg 6.1.Up to date versions should work fine.
-
-
Hardware requirements:
-
Minimum (personal use / few guilds):
-
A 100Mbps Download / 10Mbps Upload internet connection (Ethernet preferred for lower latency).
-
A 4 core CPU running at ~3GHz.
-
4 or 8 gigabytes of RAM.
-
15GB of free storage.
-
-
Recommended (many guilds):
-
1Gbps+ Download / 700Mbps+ Upload internet connection through Ethernet.
-
A desktop high-end or entry level server-grade CPU with 8+ performance cores running at 4GHz+.
-
32 or more gigabytes of RAM.
-
100GB+ of free solid state storage.
-
NOTE: These are only generic requirements. Hardware should scale as per guild count and usage.
Additional notes:
-
Very slow or unstable connections will cause the bot to respond to commands with huge delays, causing bugs that will otherwise not happen.
-
The bot caches role and playlist files extensively for faster lookup and lower disk activity at the expense of using more RAM.
-
CPU is used for
yt-dlpextraction and parsing, Discord API event and audio processing (ffmpeg). -
Network is used for
yt-dlpextraction and Discord API calls. -
Storage is used for storing guild and config / logging data.
-
-
Unpack the source code to a directory of your choice. (Or,
git cloneit.) -
Open a terminal in that directory.
-
On Windows:
CMDis recommended.PowerShellhas a very different syntax and won't work with these commands. -
On UNIX-like OS:
Bash/Zshis preferred.Fishmight break some commands.
-
-
Create a
.envfile with the following contents by running:echo "TOKEN={your_discord_bot_token}" > .env(UNIX-like)echo TOKEN={your_discord_bot_token} > .env(Windows) -
Replace
{your_discord_bot_token}with your bot's token.Example file output:
TOKEN=1a2b3c4d5e6f7g
-
Prepare and run automatically using the helper script:
python3 start.py(UNIX-like)python start.py(Windows)What it does:
Automatically determines if a Python venv is installed, creates one if not, installs dependencies and runs the main script. Essentially, it spares you the manual setup commands.
- Once it outputs '
Ready', it will start listening for events and commands.
- Once it outputs '
If the automatic setup doesn't work, it may be worth manually setting it up:
-
Create a Python virtual environment (venv):
python3 -m venv ./.venv/(UNIX-like)python -m venv .\.venv\(Windows)What it does:
Invokes the Python interpreter with the venv module, passing the current path as the installation directory.
-
If successful, activate the venv:
source ./.venv/bin/activate(UNIX-like).\.venv\Scripts\activate.bat(Windows)What it does:
Runs the activation script for the venv.
-
Install the required dependencies for the project:
pip install -r requirements.txt(UNIX-like/Windows)What it does:
Runs the pip package manager, passing the contents of this file as the packages to install.
-
Finally, if successful, run the main entry point:
python3 main.py(UNIX-like)python main.py(Windows)What it does:
Invokes the Python interpreter with the main.py file.
- Once it outputs '
Ready', it will start listening for events and commands.
- Once it outputs '
To start listening to your favourite music:
- Join a voice channel.
- Use the /join command to invite the bot to join your voice channel.
- Use /add or /playnow to add / play your tracks!
Help for every command can be found using the /help command.
During the first run, the bot will create a config.json file in its own directory. It contains configuration data.
To enable or modify the activity the bot displays in its profile,
you can modify the enable_activity, activity_name, activity_type, activity_state (for listening and playing activity types only) and status_type
values to set your own custom activity.
Documentation for every configuration key can be found here. Modify values at your own risk.
Notes
- Changing any value will require a restart to take effect. See Troubleshooting to see how to properly restart.
- Config keys are automatically recreated at startup if missing.
Example activity config:
{
"enable_activity": true,
"activity_name": "Amazing music",
"activity_type": "listening",
"activity_state": null,
"status_type": "online"
}To add your own modules, simply create a new .py file in the modules directory. For access to config and runtime settings data as constants, import the settings and init.constants modules.
Write your class as a commands.Cog subclass, which takes only a client parameter of type Bot or (|) ShardedBot (from module bot) in its
constructor, this allows custom classes to interact with the Bot subclasses of commands.Bot or commands.AutoShardedBot.
Best practices:
- Check out the example module and follow the discord.py documentation for help with the Discord API.
- Check locks before running I/O file or VoiceClient operations (
channel.connect()/vc.play()/vc.stop()/vc.pause()etc.). You can use thecheck_vc_lock()orcheck_file_lock()async functions fromhelpers.guildhelpers. - Do not call
sleep()or anything that blocks the main thread. Useasyncio.sleep()instead if working within an async context. - Do not do file I/O directly, instead, send the
write_file()oropen_file()function (fromhelpers.iohelpers) to an asyncio thread and await its result. Or, write your own async I/O functions. File I/O blocks the main thread. - Custom helpers should be kept in a new module in
./helpers. - Avoid interacting with core modules, as they were not written with an API-like system in mind.
- To log errors or messages to stdout, use
log(). Instead, to log to thediscord.logfile (if logging is explicitly enabled through theCAN_LOGconstant found insettings.py), uselog_to_discord_log()(frominit.logutils). - Do not use the
TOKENconstant anywhere unless there's a very good reason to. (like running the bot itself) - If custom Cogs need other non-default permissions, make sure to enable them in your application's Installation section and update role permissions for your bot.
Then, add a new key in config.json named enable_{class_name} to allow enabling/disabling the module, and set its value to true, or else the bot won't load your Cog.
Start the bot. It will attempt to auto-discover your module and load the appropriate class(es).
Note: The bot will load any class that inherits from commands.Cog, independently of the name, adding 'Cog' at the end of your class name keeps it consistent with the default modules.
-
If the bot state ends up broken, restarting might help.
To restart the bot:
-
Gracefully terminate the process with CTRL + C, this is the preferred way and allows the bot to properly clean up before exiting.
-
Then, run:
python3 start.py(UNIX-like)python start.py(Windows)if the current terminal is not in the venv. Otherwise:
python3 main.py(UNIX-like)python main.py(Windows)Note: The script
start.pycan be used to launch the bot even after first time configuration.
-
-
If the bot fails to play tracks, ensure the libraries (specifically,
yt_dlp) are up to date.Open a terminal in the project directory and run:
python3 updatelibs.py(UNIX-like)python updatelibs.py(Windows)Then, try again.
-
If you have an existing bot that's in over 2500 guilds, ensure the
use_shardingkey is set totrueinconfig.json'Sharding' allows multiple instances of this bot to manage multiple guilds and is required by Discord after a bot reaches 2500 guilds.
This project is licensed under MIT. See LICENSE for more information.