In this tutorial, I’ll Walk you through the entire process of creating a Discord TTS Bot, complete with configuration and scripting, by the end of this article, you’ll have a functional bot ready to speak your text in a voice channel!
NOTE: We will be using the npm.js Discord library package (specifically discord.js
) for this tutorial, not the Python-based Discord libraries. If you’re looking for a Python solution, this guide may not be applicable.🌟
Here are the steps we will be doing to create a Discord TTS Bot
- Step 1: Creating your Application on Discord Developer Portal
- Step 2: Prepare your Environment
- Step 3: Writing the Code
- Step 4: Running the Bot and Testing
So without further a do let’s get into it
Step 1: Creating Your Application on Discord Developer Portal
Before writing a single line of code, you need to create a bot on the Discord Developer Portal. Follow these steps:
- Visit the Developer Portal:
Go to Discord Developer Portal - Create a New Application:
Click the New Application button at the top right, give it a name (e.g., “Discord TTS Bot”), and hit Create, then Setup Icon and description in General Information Section - Set Up the Bot:
- Navigate to the Bot tab on the left sidebar
- If you are just building it for fun and really don’t have to get into specification then just simply turn on all the intents in the Intent Section (if your bot somehow becomes massive then it will matter but for a simple TTS bot it really doesn’t matter).
- In the Permission Section check the permissions that you want your bot to have, if you are building it for fun just simply click administrator, it will be easier that way.
- Copy Your Token:
On the Token Section copy the Token if it is present, if not then simply reset it, then it will appear, copy it and save it somewhere safe we need it in our code to communicate with our Bot.
Important: Store this safely (we’ll use it later). Don’t share it publicly. - Set Up Bot Permissions:
- Go to the OAuth2 tab in the left sidebar.
- Under Scopes, check bot.
- Under Bot Permissions, select the required permissions (e.g., “Connect”, “Speak”, and “Send Messages”) or just simply click Administrator for all.
- Copy the generated URL and open it in your browser to invite the bot to your server, it will be present under the Bot Permissions Section in the near end of the page.
Now your Discord TTS bot is configured and ready to connect with Discord with little bit of code!
Step 2: Prepare Your Environment
To build and run your bot, you need the right tools in place. Here’s how to set up your environment:
- Install Node.js:
Download and install Node.js from the official site. Node.js allows you to execute JavaScript code outside a browser. - Create a New Project:
- Create a folder for your bot project (e.g.,
TTSBot
). - Open a terminal inside the folder and run
npm init -y
This will generate apackage.json
file, which helps manage dependencies.
- Create a folder for your bot project (e.g.,
- Install Dependencies:
Install the necessary libraries by running the following commandnpm install discord.js @discordjs/voice say dotenv
discord.js
: For interacting with Discord.@discordjs/voice
: For handling voice functionality.say
: For converting text to speech.dotenv
: For securely storing your bot’s token in an.env
file.
- Set Up a
.env
File:
Create a.env
file in your project folder and add your botDISCORD_BOT_TOKEN=COPIED BOT TOKEN
it will be something like thisDISCORD_BOT_TOKEN=xxxxxxxxxxxxxxxMzEwOA.Grs2dV.vr137SV45_CW5IOG2xxxxxxxxxxxxxxxxxxxxxxxx
here x also represents some random numbers and characters.
Now your environment is ready to support the bot development.
Step 3: Writing the Code
Here’s the magic part writing the bot’s script! Follow these steps:
Create the Bot Script:
In your project folder, create a new file named index.js
and write the following code:
const { Client, GatewayIntentBits } = require('discord.js');
const {
joinVoiceChannel,
createAudioPlayer,
createAudioResource,
AudioPlayerStatus,
} = require('@discordjs/voice');
const say = require('say');
const fs = require('fs');
const path = require('path');
require('dotenv').config();
const TEMP_AUDIO_FILE = path.join(__dirname, 'temp-audio.wav');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildVoiceStates,
],
});
let voiceConnection = null;
client.once('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('messageCreate', async (message) => {
if (message.author.bot) return;
const args = message.content.split(' ');
const command = args.shift()?.toLowerCase();
if (command === '!join') {
if (!message.member.voice.channel) {
message.reply('You need to be in a voice channel to use this command.');
return;
}
voiceConnection = joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
});
message.reply('Joined the voice channel and ready to speak!');
} else if (command === '!leave') {
if (voiceConnection) {
voiceConnection.destroy();
voiceConnection = null;
message.reply('Left the voice channel.');
} else {
message.reply('I am not in a voice channel.');
}
} else if (command === '!say') {
const text = args.join(' ');
if (!text) {
message.reply('Please provide some text to speak!');
return;
}
say.export(text, null, 1.0, TEMP_AUDIO_FILE, (err) => {
if (err) {
console.error(err);
message.reply('Failed to generate audio.');
return;
}
const player = createAudioPlayer();
const resource = createAudioResource(TEMP_AUDIO_FILE);
if (!voiceConnection) {
message.reply('Bot is not in a voice channel.');
return;
}
player.play(resource);
voiceConnection.subscribe(player);
player.on(AudioPlayerStatus.Idle, () => {
fs.unlinkSync(TEMP_AUDIO_FILE);
});
message.reply('Speaking in the voice channel!');
});
}
});
client.login(process.env.DISCORD_BOT_TOKEN);
Understand the Commands:
!join
: Makes the bot join the user’s current voice channel.!say
: Converts the text provided after!say
into speech and plays it in the voice channel.!leave
: Disconnects the bot from the voice channel.
Step 4: Running the Discord TTS Bot and Testing
Now that the bot code is ready, let’s bring it to life 🍭🍭🍭:
- Run the Bot:
Open your terminal, navigate to your project folder, and typenode index.js
, If everything is correct you will see your bot is online on discord. - Test in Discord:
- Type
!join
in a text channel while you’re in a voice channel. The bot should join. - Type
!say Hello, everyone!
and listen to your bot speaking. - Use
!leave
to disconnect the bot from the channel
- Type
How It Works in Action
- A user types a command in a Discord text channel (e.g.,
!join
or!say Hello!
). - The bot processes the command and takes action:
- Joins a voice channel (
!join
). - Converts text into speech, generates an audio file, and plays it (
!say
). - Leaves the voice channel (
!leave
).
- Joins a voice channel (
- Temporary files are cleaned up after use to keep your server resources optimized.
You can add as much logic as you want.
Modifying your TTS
To change the voice of the bot or speed you can alter the parameters in the say.export() command with the name of the speaker you want to use and the rate of speed.
say.export(text, NAMEOFTHESPEAKER , SPEED VALUE , TEMP_AUDIO_FILE, (err) => { ....... });
To get the list of the Name of the Speakers you can use.
say.getInstalledVoices(callback)
Conclusion
By following these steps, you’ve successfully created a functional Discord TTS Bot 🎉🎉 With commands like !say
, you can now make your bot speak in a voice channel, making your server both fun and functional. Customize the bot further to fit your unique needs.
Thanks for reading🌟🌟🌟, if you have any questions or concerns kindly leave them down below. If you want to know how to modify your own LLMS then visit How to Customize Your own Ollama Model or if you are into PHP then Techniques to Prevent SQL Injections in PHP: A Comprehensive Guide or Build Your Own Generic CRUD API in PHP
Again thanks for reading 💖💖💖💖