Node.js开发Telegram Bot:保存Chat ID至数据库及实现通知功能
Hey there! As someone new to building Telegram Bots with Node.js, I’ll walk you through a concrete, beginner-friendly implementation to save chat IDs to a database and send bulk notifications. Let’s dive in!
First, initialize a new Node.js project and install the two key packages we’ll need:
node-telegram-bot-api: The go-to library for interacting with Telegram’s Bot APIsqlite3: A lightweight, file-based SQL database (perfect for beginners since it doesn’t require a separate server)
Run these commands in your terminal:
npm init -y npm install node-telegram-bot-api sqlite3
Create a file (like bot.js) and add this code to set up your bot and connect to the database. Don’t forget to replace YOUR_TELEGRAM_BOT_TOKEN with the token you got from @BotFather!
const TelegramBot = require('node-telegram-bot-api'); const sqlite3 = require('sqlite3').verbose(); // Replace with your actual bot token from @BotFather const token = 'YOUR_TELEGRAM_BOT_TOKEN'; const bot = new TelegramBot(token, { polling: true }); // Polling mode is great for development // Connect to SQLite database (creates the file if it doesn't exist) const db = new sqlite3.Database('chat_ids.db', (err) => { if (err) { console.error('Database connection error:', err.message); } else { console.log('Successfully connected to the chat IDs database!'); } }); // Create a table to store chat IDs (only if it doesn't exist already) db.run(`CREATE TABLE IF NOT EXISTS chats ( id INTEGER PRIMARY KEY AUTOINCREMENT, chat_id TEXT UNIQUE NOT NULL )`);
Let’s add a /start command so users can subscribe to notifications. When they send this command, we’ll save their chat ID to the database (and avoid duplicates with INSERT OR IGNORE):
bot.onText(/\/start/, (msg) => { const chatId = msg.chat.id.toString(); // Insert the chat ID, ignore if it's already in the database db.run(`INSERT OR IGNORE INTO chats (chat_id) VALUES (?)`, [chatId], function(err) { if (err) { return console.error('Error saving chat ID:', err.message); } if (this.changes > 0) { bot.sendMessage(chatId, '🎉 You\'ve subscribed to notifications! You\'ll get updates from now on.'); } else { bot.sendMessage(chatId, 'ℹ️ You\'re already subscribed to notifications.'); } }); });
Now let’s build a function to fetch all saved chat IDs and send a message to each one. We’ll also add a /sendnotification command so you can test this easily:
// Function to send a notification to all subscribed users function sendBulkNotification(message) { db.all(`SELECT chat_id FROM chats`, (err, rows) => { if (err) { return console.error('Error fetching chat IDs:', err.message); } rows.forEach((row) => { const targetChatId = row.chat_id; bot.sendMessage(targetChatId, message) .catch((err) => { // Handle cases where the bot can't send a message (e.g., user blocked the bot) console.log(`Failed to send to ${targetChatId}: ${err.message}`); // Optional: Remove invalid chat IDs from the database to clean up // db.run(`DELETE FROM chats WHERE chat_id = ?`, [targetChatId]); }); }); }); } // Test the notification system with a command bot.onText(/\/sendnotification (.+)/, (msg, match) => { const notificationText = match[1]; // Capture the message after the command sendBulkNotification(notificationText); bot.sendMessage(msg.chat.id, '✅ Notification sent to all subscribed users!'); });
Let’s make it user-friendly by adding an /unsubscribe command so users can opt out:
bot.onText(/\/unsubscribe/, (msg) => { const chatId = msg.chat.id.toString(); db.run(`DELETE FROM chats WHERE chat_id = ?`, [chatId], function(err) { if (err) { return console.error('Error unsubscribing:', err.message); } if (this.changes > 0) { bot.sendMessage(chatId, '👋 You\'ve unsubscribed from notifications. We\'ll miss you!'); } else { bot.sendMessage(chatId, 'ℹ️ You weren\'t subscribed to notifications anyway.'); } }); });
- Polling vs Webhooks: We used polling mode here because it’s easier to set up for development. For production, switch to webhooks for better performance (you’ll need a public URL for that).
- Database Choice: SQLite is perfect for small-scale bots. If you need to scale later, you can swap it for PostgreSQL or MongoDB—just adjust the database query syntax.
- Error Handling: Always handle errors (like failed message sends) to keep your bot running smoothly.
内容的提问来源于stack exchange,提问作者totalnewb




