Advertisement
Tutorial

How to Build a Free Fire Discord Bot in Node.js

Step-by-step tutorial on creating a Discord bot that fetches Free Fire player stats, clan information, and ban status using our API. Includes complete source code.

February 8, 2024
15 min read
By Sarah Johnson
Discord
Bot
Node.js
JavaScript

Learn how to create a fully-functional Discord bot that provides Free Fire player statistics, clan information, and more using the Free Fire API.

What We'll Build

By the end of this tutorial, you'll have a Discord bot that can:

  • Fetch and display player statistics
  • Check ban status for any player
  • Show clan information
  • Display player rankings
  • Handle multiple commands with slash commands

Prerequisites

  • Node.js 16.9.0 or higher installed
  • A Discord account and server for testing
  • Free Fire API key (get one at Free Fire API Hub)
  • Basic JavaScript knowledge

Step 1: Set Up Your Discord Bot

First, create a new Discord application:

  1. Go to Discord Developer Portal
  2. Click "New Application" and give it a name
  3. Navigate to the "Bot" section and click "Add Bot"
  4. Copy your bot token (keep this secret!)
  5. Enable "Message Content Intent" under Privileged Gateway Intents

Step 2: Initialize Your Project

mkdir free-fire-discord-bot
cd free-fire-discord-bot
npm init -y
npm install discord.js dotenv axios

Step 3: Create Environment Variables

Create a .env file in your project root:

DISCORD_TOKEN=your_discord_bot_token_here
FREE_FIRE_API_KEY=your_free_fire_api_key_here
CLIENT_ID=your_discord_client_id_here

Step 4: Build the Bot

Create index.js with the following code:

const { Client, GatewayIntentBits, EmbedBuilder } = require('discord.js');
const axios = require('axios');
require('dotenv').config();

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
  ],
});

const API_BASE = 'https://developers.freefirecommunity.com/api/v1';
const API_KEY = process.env.FREE_FIRE_API_KEY;

// Bot ready event
client.once('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

// Message handler
client.on('messageCreate', async (message) => {
  if (message.author.bot) return;
  
  const args = message.content.slice(1).trim().split(/ +/);
  const command = args.shift().toLowerCase();
  
  if (command === 'ffstats') {
    await handleStatsCommand(message, args);
  } else if (command === 'ffban') {
    await handleBanCommand(message, args);
  } else if (command === 'ffhelp') {
    await handleHelpCommand(message);
  }
});

// Stats command handler
async function handleStatsCommand(message, args) {
  if (args.length < 2) {
    return message.reply('Usage: !ffstats <UID> <region>\nExample: !ffstats 123456789 SG');
  }
  
  const [uid, region] = args;
  
  try {
    const response = await axios.get(`${API_BASE}/info`, {
      params: { key: API_KEY, uid, region: region.toUpperCase() }
    });
    
    const data = response.data;
    
    if (!data.basicInfo) {
      return message.reply('Player not found. Check the UID and region.');
    }
    
    const embed = new EmbedBuilder()
      .setColor('#FF6B00')
      .setTitle(`📊 ${data.basicInfo.nickname}`)
      .setDescription(`Free Fire Player Stats`)
      .addFields(
        { name: '🆔 UID', value: uid, inline: true },
        { name: '🌍 Region', value: data.basicInfo.region, inline: true },
        { name: '⭐ Level', value: `${data.basicInfo.level}`, inline: true },
        { name: '❤️ Likes', value: `${data.basicInfo.liked?.toLocaleString() || 0}`, inline: true },
        { name: '🏆 Rank Points', value: `${data.basicInfo.rankingPoints?.toLocaleString() || 0}`, inline: true },
      )
      .setTimestamp()
      .setFooter({ text: 'Free Fire API Hub' });
    
    if (data.clanBasicInfo) {
      embed.addFields({
        name: '👥 Clan',
        value: `${data.clanBasicInfo.clanName} (Level ${data.clanBasicInfo.clanLevel})`,
        inline: false
      });
    }
    
    message.reply({ embeds: [embed] });
  } catch (error) {
    console.error('Error fetching stats:', error);
    message.reply('❌ Failed to fetch player stats. Please try again later.');
  }
}

// Ban check command handler
async function handleBanCommand(message, args) {
  if (args.length < 1) {
    return message.reply('Usage: !ffban <UID>\nExample: !ffban 123456789');
  }
  
  const uid = args[0];
  
  try {
    const response = await axios.get(`${API_BASE}/bancheck`, {
      params: { key: API_KEY, uid, lang: 'en' }
    });
    
    const data = response.data;
    const isBanned = data.is_banned === 1;
    
    const embed = new EmbedBuilder()
      .setColor(isBanned ? '#FF0000' : '#00FF00')
      .setTitle(`${isBanned ? '🚫' : '✅'} Ban Status Check`)
      .setDescription(`UID: ${uid}`)
      .addFields({
        name: 'Status',
        value: isBanned ? '**BANNED**' : '**Not Banned**',
        inline: true
      })
      .setTimestamp();
    
    if (isBanned && data.period) {
      embed.addFields({
        name: 'Ban Period',
        value: `${data.period} days`,
        inline: true
      });
    }
    
    message.reply({ embeds: [embed] });
  } catch (error) {
    console.error('Error checking ban status:', error);
    message.reply('❌ Failed to check ban status. Please try again later.');
  }
}

// Help command handler
async function handleHelpCommand(message) {
  const embed = new EmbedBuilder()
    .setColor('#0099FF')
    .setTitle('🎮 Free Fire Bot Commands')
    .setDescription('Available commands for Free Fire stats and information')
    .addFields(
      { name: '!ffstats <UID> <region>', value: 'Get player statistics\nExample: `!ffstats 123456789 SG`' },
      { name: '!ffban <UID>', value: 'Check ban status\nExample: `!ffban 123456789`' },
      { name: '!ffhelp', value: 'Show this help message' }
    )
    .addFields({
      name: 'Supported Regions',
      value: 'SG, IND, BR',
      inline: false
    })
    .setFooter({ text: 'Powered by Free Fire API Hub' });
  
  message.reply({ embeds: [embed] });
}

// Login to Discord
client.login(process.env.DISCORD_TOKEN);

Step 5: Run Your Bot

node index.js

Step 6: Invite Your Bot to a Server

Generate an invite link:

  1. Go to Discord Developer Portal
  2. Select your application
  3. Go to OAuth2 → URL Generator
  4. Select "bot" scope and required permissions
  5. Copy the generated URL and open it in your browser

Testing Your Bot

Try these commands in your Discord server:

  • !ffhelp - Show available commands
  • !ffstats 123456789 SG - Get player stats
  • !ffban 123456789 - Check ban status

Advanced Features to Add

Enhance your bot with these features:

  • Slash commands for better UX
  • Player comparison commands
  • Leaderboard tracking
  • Automatic stat updates
  • Clan management features

Deployment

Deploy your bot to keep it running 24/7:

  • Heroku: Free tier with easy deployment
  • Railway: Modern platform with generous free tier
  • DigitalOcean: $5/month droplet
  • AWS EC2: Free tier for 12 months

Conclusion

You've successfully built a Free Fire Discord bot! This bot can be extended with many more features. Check out our API documentation for more endpoints and possibilities.

Advertisement

Found this helpful?

Share this article with other developers

S

Sarah Johnson

Senior Developer

Developer advocate passionate about helping developers build amazing Free Fire applications.