Article Image

API

How to Create a Leaderboard Bot Using the Discord API

8/6/2024

Learn how to create a leaderboard bot using the Discord API with this comprehensive guide. Enhance your Discord server by integrating a customized bot to track and display user activity.

Discord bots are powerful tools that can automate tasks, manage communities, and add fun features to your server. One popular use case is a leaderboard bot, which tracks and ranks users based on their activity or achievements. This article will guide you through creating a leaderboard bot using the Discord API, ensuring that your server becomes more interactive and engaging.

Understanding the Discord API

The Discord API allows developers to interact with Discord servers, users, and channels programmatically. It provides endpoints for various functionalities, such as sending messages, managing roles, and tracking user activity. To create a leaderboard bot, you’ll need to understand how to use these endpoints effectively.

Setting Up Your Development Environment

Install Node.js and npm

Ensure you have Node.js and npm installed on your computer. You can download them from the Node.js website.

Create a new project directory

Open your terminal and create a new directory for your bot project.

              mkdir leaderboard-bot cd leaderboard-bot  

Initialize the project

Run npm init to create a package.json file.

  npm init -y  

Install Discord.js

Discord.js is a powerful library for interacting with the Discord API.

  npm install discord.js  

Creating a Discord Bot Account

Visit the Discord Developer Portal

Go to the Discord Developer Portal.

Create a new application

Click on "New Application," give it a name, and save it.

Create a bot user

In the "Bot" section, click "Add Bot." This will create a bot user and generate a token. Keep this token safe; it’s used to authenticate your bot.

Invite your bot to a server

Under the "OAuth2" section, generate an invite link with the appropriate permissions and invite the bot to your server.

Writing the Bot Code

Now that your environment is set up, it’s time to write the bot code. Create an index.js file in your project directory and open it in your text editor.

Initializing the Bot

Start by requiring the necessary modules and initializing the bot:

          const { Client, Intents } = require('discord.js'); const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });  client.once('ready', () => { console.log('Leaderboard Bot is online!'); });  client.login('YOUR_BOT_TOKEN');  

Replace 'YOUR_BOT_TOKEN' with the token you obtained from the Discord Developer Portal.

Tracking User Activity

To create a leaderboard, you need to track user activity. For simplicity, let’s track the number of messages each user sends.

          const userActivity = {};  client.on('messageCreate', message => { if (message.author.bot) return;  if (!userActivity[message.author.id]) {     userActivity[message.author.id] = { username: message.author.username, messages: 0 }; }  userActivity[message.author.id].messages += 1; });  

Creating the Leaderboard Command

Next, create a command that displays the leaderboard. When a user types !leaderboard, the bot will send a message with the top users.

          client.on('messageCreate', message => { if (message.content === '!leaderboard') { const sortedUsers = Object.values(userActivity).sort((a, b) => b.messages - a.messages); let leaderboard = 'Leaderboard:\n';      sortedUsers.slice(0, 10).forEach((user, index) => {         leaderboard += `${index + 1}. ${user.username} - ${user.messages} messages\n`;     });      message.channel.send(leaderboard); } });  

Adding More Features

You can extend the bot with more features, such as tracking different types of activity or resetting the leaderboard periodically.

Tracking Other Activities

To make the leaderboard more comprehensive, you can track other activities like voice chat participation or reactions.

Voice Chat Participation

              client.on('voiceStateUpdate', (oldState, newState) => { if (newState.channelId && !oldState.channelId) { if (!userActivity[newState.id]) { userActivity[newState.id] = { username: newState.member.user.username, messages: 0, voice: 0 }; }      userActivity[newState.id].voice += 1; } });  

Reactions

  client.on('messageReactionAdd', (reaction, user) => { if (user.bot) return;  if (!userActivity[user.id]) {     userActivity[user.id] = { username: user.username, messages: 0, reactions: 0 }; }  userActivity[user.id].reactions += 1; });  

Resetting the Leaderboard

You can reset the leaderboard periodically to keep the competition fresh. For example, reset it every week.

          const schedule = require('node-schedule');  const resetLeaderboard = schedule.scheduleJob('0 0 * * 0', () => { for (const userId in userActivity) { userActivity[userId].messages = 0; userActivity[userId].reactions = 0; userActivity[userId].voice = 0; } });  

Adding a Database

For a more robust solution, use a database to store user activity. This ensures data persistence even if the bot restarts.

Using SQLite

Install SQLite3

                  npm install sqlite3  

Setup the Database

  const sqlite3 = require('sqlite3').verbose(); const db = new sqlite3.Database('./leaderboard.db');  db.serialize(() => { db.run('CREATE TABLE IF NOT EXISTS user_activity (id TEXT PRIMARY KEY, username TEXT, messages INTEGER, reactions INTEGER, voice INTEGER)'); });  client.on('messageCreate', message => { if (message.author.bot) return;  db.get('SELECT * FROM user_activity WHERE id = ?', [message.author.id], (err, row) => {     if (err) {         console.error(err.message);     } else {         if (row) {             db.run('UPDATE user_activity SET messages = ? WHERE id = ?', [row.messages + 1, message.author.id]);         } else {             db.run('INSERT INTO user_activity (id, username, messages, reactions, voice) VALUES (?, ?, ?, ?, ?)', [message.author.id, message.author.username, 1, 0, 0]);         }     } }); });  

FAQs

How do I get my bot token?

Your bot token is available in the Discord Developer Portal. Navigate to your application, select the "Bot" tab, and you’ll find the token.

Can I track other activities besides messages?

Yes, you can track various activities like reactions, voice chat participation, and more by using the appropriate events from the Discord.js library.

How do I make my bot more secure?

Ensure you never share your bot token and use environment variables to store sensitive data. Regularly update your dependencies to avoid security vulnerabilities.

Can I host my bot for free?

Yes, you can host your bot for free on platforms like Heroku or Glitch, although they have limitations. For more reliable hosting, consider using paid services.

What if my bot goes offline?

If your bot goes offline, ensure your code handles reconnections gracefully. Use a database to persist user activity data to prevent loss during downtime.

How do I invite the bot to multiple servers?

Use OAuth2 to generate invite links for each server. Ensure your bot is designed to handle multiple servers by using guild-specific configurations.

Conclusion

Creating a leaderboard bot using the Discord API is a rewarding project that can greatly enhance your Discord server's engagement. By tracking various user activities and presenting them in a competitive format, you encourage participation and interaction. With the foundational knowledge provided in this guide, you can extend and customize your bot to suit your server's unique needs. Happy coding!