نمونه پروژههای کاربردی در نود جیاس (Node.js)¶
توسعه رباتهای کدمیت در محیط جاوااسکریپت و تایپاسکریپت بسیار سریع و سرراست است. در این بخش از fetch بومی نود نسخه ۱۸+ یا پکیج axios استفاده میکنیم.
۱. ربات نود جیاس با Fetch بومی (Node.js 18+)¶
بدون نیاز به نصب هیچ پکیج اضافی:
// 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("ربات نود جیاس کدمیت راهاندازی شد...");
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: "سلام به ربات جاوااسکریپت در کدمیت خوش آمدید!",
reply_markup: {
inline_keyboard: [
[{ text: "وبسایت کدمیت", url: "https://codemeet.chat" }]
]
}
});
} else {
await apiRequest("sendMessage", {
chat_id,
text: `دریافت شد: ${text}`
});
}
}
}
} catch (err) {
console.error("خطا در شبکه یا اجرا:", err);
await new Promise(r => setTimeout(r, 3000));
}
}
}
startBot();
برای اجرای اسکریپت:
۲. سرور وبهوک با Express.js¶
// 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("وبهوک دریافتی:", 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: `پاسخ از سرور وبهوک: ${text}`
})
});
}
res.status(200).json({ ok: true });
});
app.listen(3000, () => {
console.log("وبهوک سرور روی پورت 3000 آماده است.");
});