Managing a Telegram group with 3,000 members isn't just about growing numbers—it's about fostering a safe, respectful community. After encountering repeated instances of hate speech, I developed a Node.js-based moderation bot that automatically identifies and restricts users posting racial slurs. In this article, I'll walk you through the entire development process, from conception to deployment.
Manual moderation of a large Telegram group presents several challenges:
First, we set up the basic bot structure with proper error handling:
const TelegramBot = require('node-telegram-bot-api'); const express = require('express'); const bodyParser = require('body-parser'); const dotenv = require('dotenv'); const logging = require('console'); dotenv.config(); const BOT_TOKEN = process.env.BOT_TOKEN; const bot = new TelegramBot(BOT_TOKEN, { polling: true });
The bot implements a multi-layer monitoring system:
bot.on('message', async (msg) => { if (!msg.chat || !msg.from) return; // Message processing logic });
function checkForRacialSlurs(message) { if (!message) return false; return RACIAL_SLURS.some(slur => message.toLowerCase().includes(slur) ); }
async function restrictUser(chatId, userId) { try { await bot.restrictChatMember(chatId, userId, { permissions: { can_send_messages: false, can_send_media_messages: false, can_send_polls: false, can_send_other_messages: false, can_add_web_page_previews: false, can_change_info: false, can_invite_users: false, can_pin_messages: false, }, }); return true; } catch (error) { logging.error('Restriction failed:', error); return false; } }
The bot includes a staff layout system for easy access to moderator information:
const STAFF_LAYOUT = ` <b>GROUP STAFF</b> ? <b>Founder</b> └ @Sixademiks ⚜️ <b>Verified Vendors</b> ├ @Vendor1 (City1) └ @Vendor2 (City2) `;
New users receive a formatted welcome message with HTML parsing:
bot.onText(/\/start/, async (msg) => { try { const welcomeMessage = ` <b>Welcome to the DirtyNewz Bot!</b> Please read the <b>pinned messages</b> for the group rules...`; await bot.sendMessage(msg.chat.id, welcomeMessage, { parse_mode: 'HTML' }); } catch (error) { logging.error("Error in /start:", error); } });
Comprehensive logging helps track bot performance and user violations:
logging.log('User was restricted due to violation'); logging.error('Error during restriction:', error);
After deploying the bot in our 5,000-member group, we observed:
Initially, we hit Telegram's rate limits during high-traffic periods. Solution:
const rateLimiter = { messageCount: 0, lastReset: Date.now(), check: function() { if (Date.now() - this.lastReset > 1000) { this.messageCount = 0; this.lastReset = Date.now(); } return this.messageCount++ < 30; } };
Robust error handling prevents bot crashes:
process.on('unhandledRejection', (reason, promise) => { logging.error('Unhandled Rejection at:', promise, 'reason:', reason); }); bot.on('polling_error', (error) => { logging.error('Polling error:', error); }); <h3> 3. Message Processing </h3> <p>Efficient message processing to handle high volume:<br> </p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">const TelegramBot = require('node-telegram-bot-api'); const express = require('express'); const bodyParser = require('body-parser'); const dotenv = require('dotenv'); const logging = require('console'); dotenv.config(); const BOT_TOKEN = process.env.BOT_TOKEN; const bot = new TelegramBot(BOT_TOKEN, { polling: true });
The bot is deployed on a Linux server using PM2 for process management:
bot.on('message', async (msg) => { if (!msg.chat || !msg.from) return; // Message processing logic });
Regular monitoring is crucial:
function checkForRacialSlurs(message) { if (!message) return false; return RACIAL_SLURS.some(slur => message.toLowerCase().includes(slur) ); }
async function restrictUser(chatId, userId) { try { await bot.restrictChatMember(chatId, userId, { permissions: { can_send_messages: false, can_send_media_messages: false, can_send_polls: false, can_send_other_messages: false, can_add_web_page_previews: false, can_change_info: false, can_invite_users: false, can_pin_messages: false, }, }); return true; } catch (error) { logging.error('Restriction failed:', error); return false; } }
const STAFF_LAYOUT = ` <b>GROUP STAFF</b> ? <b>Founder</b> └ @Sixademiks ⚜️ <b>Verified Vendors</b> ├ @Vendor1 (City1) └ @Vendor2 (City2) `;
bot.onText(/\/start/, async (msg) => { try { const welcomeMessage = ` <b>Welcome to the DirtyNewz Bot!</b> Please read the <b>pinned messages</b> for the group rules...`; await bot.sendMessage(msg.chat.id, welcomeMessage, { parse_mode: 'HTML' }); } catch (error) { logging.error("Error in /start:", error); } });
Building a moderation bot for a large Telegram group taught valuable lessons about scalability, error handling, and community management. The bot has significantly improved our group's environment while reducing moderator workload.
Remember that effective moderation is about finding the right balance between automated systems and human oversight. While this bot handles the first line of defense, it's designed to complement, not replace, human moderators.
Feel free to reach out with questions or check out the complete code on my GitHub!
The above is the detailed content of Building a Scalable Anti-Hate Speech Moderation Bot for Telegram: A Deep Dive. For more information, please follow other related articles on the PHP Chinese website!