Home  /  Blog  /  Daily Hadith Discord Bot

Build a Daily Hadith Bot for Discord

Bot7 min readNovember 2026

This post shows you how to build a hadith Discord bot that fetches a random hadith from UmmahAPI and posts it to your server every morning at a set time. You will write the whole thing in Node.js using discord.js and node-cron.

What You Need Before You Start

Make sure you have these ready before writing any code:

You do not need a database. The bot just calls the API and posts the result. That is it.

Set Up the Project

Create a new folder and install the packages you need.

mkdir hadith-bot
cd hadith-bot
npm init -y
npm install discord.js node-cron dotenv

Here is what each package does:

Create a .env file in your project root:

# .env
DISCORD_TOKEN=your_discord_bot_token_here
CHANNEL_ID=your_target_channel_id_here
UMMAH_API_KEY=your_ummahapi_key_here

Tip. To get your channel ID in Discord, right-click the channel name and click "Copy Channel ID". You may need to enable Developer Mode first under User Settings > Advanced.

Fetch a Random Hadith from UmmahAPI

UmmahAPI has a /api/hadith/random endpoint that returns a random hadith from one of the 10 supported collections. Let's test it first so you can see what the response looks like.

# Test the endpoint in your terminal
curl "https://ummahapi.com/api/hadith/random"

The response looks like this:

{
  "collection": "bukhari",
  "number": 1,
  "arabic": "إِنَّمَا الأَعْمَالُ بِالنِّيَّاتِ...",
  "english": "Actions are judged by intentions..."
}

Now write a function that fetches this data in Node.js. Create a file called hadith.js:

// hadith.js
const BASE_URL = "https://ummahapi.com";

async function getRandomHadith(apiKey) {
  const url = `${BASE_URL}/api/hadith/random`;

  const headers = {};
  if (apiKey) {
    headers["x-api-key"] = apiKey;
  }

  const res = await fetch(url, { headers });
  if (!res.ok) {
    throw new Error(`API error: ${res.status}`);
  }

  return res.json();
}

module.exports = { getRandomHadith };

You can also fetch from a specific collection if you want more control. For example, to always pull from Sahih Bukhari:

// fetch from a specific collection instead of random
async function getHadithFromCollection(collection, apiKey) {
  const res = await fetch(
    `https://ummahapi.com/api/hadith/${collection}/random`,
    { headers: { "x-api-key": apiKey } }
  );
  return res.json();
}

See the full list of supported collections on the Hadith API page. The 10 collections are: bukhari, muslim, tirmidhi, abudawud, nasai, ibnmajah, malik, nawawi, qudsi, and dehlawi.

Build the Discord Bot

Now create the main file, index.js. This sets up the Discord client, logs in, and waits for the cron job to fire.

// index.js
require("dotenv").config();
const { Client, GatewayIntentBits, EmbedBuilder } = require("discord.js");
const cron = require("node-cron");
const { getRandomHadith } = require("./hadith");

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

client.once("ready", () => {
  console.log(`Logged in as ${client.user.tag}`);
  scheduleHadith();
});

function scheduleHadith() {
  // Runs every day at 07:00 AM server time
  cron.schedule("0 7 * * *", async () => {
    try {
      await postHadith();
    } catch (err) {
      console.error("Failed to post hadith:", err);
    }
  });
}

async function postHadith() {
  const channel = await client.channels.fetch(process.env.CHANNEL_ID);
  if (!channel) return;

  const hadith = await getRandomHadith(process.env.UMMAH_API_KEY);

  const embed = new EmbedBuilder()
    .setColor("#1a6b3c")
    .setTitle(`Hadith of the Day`)
    .setDescription(hadith.english)
    .addFields(
      { name: "Collection", value: hadith.collection, inline: true },
      { name: "Number", value: String(hadith.number), inline: true }
    )
    .setFooter({ text: "Powered by UmmahAPI · ummahapi.com" });

  await channel.send({ embeds: [embed] });
}

client.login(process.env.DISCORD_TOKEN);

Run it with:

node index.js

You should see the "Logged in as" message in your terminal. The bot will then post to your chosen channel at 7 AM every day.

Format the Message Nicely

The embed above works, but you can make it better. If the response includes Arabic text, add it above the English translation so users see both. Here is an updated version of the embed builder:

const embed = new EmbedBuilder()
  .setColor("#1a6b3c")
  .setTitle("Hadith of the Day")
  .setDescription(
    hadith.arabic
      ? `**Arabic**\n${hadith.arabic}\n\n**Translation**\n${hadith.english}`
      : hadith.english
  )
  .addFields(
    { name: "Collection", value: capitalize(hadith.collection), inline: true },
    { name: "Number", value: String(hadith.number), inline: true }
  )
  .setTimestamp()
  .setFooter({ text: "Powered by UmmahAPI · ummahapi.com" });

function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

Tip. Discord embeds have a 4096 character limit for the description field. Very long hadiths can exceed this. Add a simple check: if hadith.english.length > 3800, trim it and append "..." before passing it to the embed.

Add a Slash Command to Post On Demand

Scheduling is great, but sometimes you want to trigger a hadith post manually. You can add a slash command called /hadith that any server member can use. First, register the command when the bot starts:

// Add this to your ready event
client.once("ready", async () => {
  console.log(`Logged in as ${client.user.tag}`);

  await client.application.commands.create({
    name: "hadith",
    description: "Get a random hadith right now"
  });

  scheduleHadith();
});

Then listen for the interaction and respond:

client.on("interactionCreate", async (interaction) => {
  if (!interaction.isChatInputCommand()) return;
  if (interaction.commandName !== "hadith") return;

  await interaction.deferReply();

  try {
    const hadith = await getRandomHadith(process.env.UMMAH_API_KEY);

    const embed = new EmbedBuilder()
      .setColor("#1a6b3c")
      .setTitle("Random Hadith")
      .setDescription(hadith.english)
      .addFields(
        { name: "Collection", value: capitalize(hadith.collection), inline: true },
        { name: "Number", value: String(hadith.number), inline: true }
      )
      .setFooter({ text: "Powered by UmmahAPI · ummahapi.com" });

    await interaction.editReply({ embeds: [embed] });
  } catch (err) {
    await interaction.editReply("Could not fetch a hadith right now. Try again later.");
  }
});

Now any member can type /hadith in your server and get one instantly. No waiting until morning.

Run the Bot in Production

Running node index.js in a terminal works for testing, but it stops when you close the terminal. For a production setup, use pm2 to keep it running in the background.

npm install -g pm2
pm2 start index.js --name hadith-bot
pm2 save
pm2 startup

The pm2 save and pm2 startup commands make sure the bot restarts automatically if your server reboots. You can check logs any time with:

pm2 logs hadith-bot

If you prefer containers, a simple Dockerfile works fine too. The bot has no special requirements beyond Node.js and network access to reach the Discord API and UmmahAPI.

Your Final File Structure

Here is what the finished project looks like:

hadith-bot/
  index.js        # Main bot file
  hadith.js       # API fetch helper
  .env            # Secrets (never commit this)
  package.json
  node_modules/

That is the whole project. Under 100 lines of real code. You can extend it in many directions. For example, you could add a /quran command using the Quran API, or post prayer times each morning alongside the hadith using the Prayer Times API. Check the full API docs for everything that is available.

FAQ

What library do I need to build a hadith Discord bot?

You need discord.js to interact with the Discord API. For scheduling, node-cron is a simple and reliable choice. Both are available on npm and work well together in a Node.js project.

Is the UmmahAPI Hadith endpoint free to use?

Yes. UmmahAPI is free. Without a key you get 5,000 requests per 15 minutes, which is more than enough for a daily bot. Register at ummahapi.com/register for an unlimited free API key.

Which hadith collections does UmmahAPI support?

UmmahAPI supports 10 collections: bukhari, muslim, tirmidhi, abudawud, nasai, ibnmajah, malik, nawawi, qudsi, and dehlawi. You can query any single collection with GET /api/hadith/:collection, or use GET /api/hadith/random to get one from any collection at random.

How do I make the bot post at the same time every day?

Use the node-cron package. The cron expression "0 7 * * *" fires at 7:00 AM every day in whatever timezone your server is running in. If you want a specific timezone, pass it as the third argument: cron.schedule("0 7 * * *", fn, { timezone: "America/New_York" }).

Build more with UmmahAPI

UmmahAPI gives you free access to Quran, Hadith, Prayer Times, Duas, Qibla, and more, all from one simple API.

Read the docs