Skip to content

Node.js & JavaScript Bot Examples

Building CodeMeet bots in JavaScript / TypeScript is straightforward using native fetch (Node.js 18+) or web servers like Express.js.


1. Native Fetch Long Polling Bot (Node.js 18+)

No external npm dependencies required:

// bot.js
const TOKEN = "YOUR_BOT_TOKEN_HERE";
const API = `https://botapi.codemeet.chat/bot${TOKEN}`;

async function apiRequest(method, payload = null, queryParams = {}) {
  let url = `${API}/${method}`;
  const query = new URLSearchParams(queryParams).toString();
  if (query) url += `?${query}`;

  const options = {
    method: payload ? "POST" : "GET",
    headers: { "Content-Type": "application/json" }
  };
  if (payload) options.body = JSON.stringify(payload);

  const res = await fetch(url, options);
  return await res.json();
}

async function startBot() {
  console.log("CodeMeet Node.js Bot started...");
  let offset = null;

  while (true) {
    try {
      const updates = await apiRequest("getUpdates", null, {
        timeout: 20,
        ...(offset && { offset })
      });

      if (!updates.ok) {
        await new Promise(r => setTimeout(r, 1000));
        continue;
      }

      for (const update of updates.result || []) {
        offset = update.update_id + 1;

        if (update.message) {
          const chat_id = update.message.chat.id;
          const text = update.message.text || "";

          if (text === "/start") {
            await apiRequest("sendMessage", {
              chat_id,
              text: "Hello, welcome to my JavaScript bot on CodeMeet!",
              reply_markup: {
                inline_keyboard: [
                  [{ text: "CodeMeet Website", url: "https://codemeet.chat" }]
                ]
              }
            });
          } else {
            await apiRequest("sendMessage", {
              chat_id,
              text: `Echo: ${text}`
            });
          }
        }
      }
    } catch (err) {
      console.error("Network or parsing error:", err);
      await new Promise(r => setTimeout(r, 3000));
    }
  }
}

startBot();

Run with:

node bot.js


2. Express.js Webhook Server

npm install express
// server.js
const express = require("express");
const app = express();

app.use(express.json());

const TOKEN = "YOUR_BOT_TOKEN_HERE";
const API = `https://botapi.codemeet.chat/bot${TOKEN}`;

app.post("/webhook", async (req, res) => {
  const update = req.body;
  console.log("Received update:", update);

  if (update.message) {
    const chat_id = update.message.chat.id;
    const text = update.message.text;

    await fetch(`${API}/sendMessage`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        chat_id,
        text: `Webhook response: ${text}`
      })
    });
  }

  res.status(200).json({ ok: true });
});

app.listen(3000, () => {
  console.log("Webhook receiver listening on port 3000.");
});