Examples
Complete, runnable examples to get you started quickly. All examples are available in the Example/ directory.
Simple Polling Bot
A full-featured bot that polls all chats for new messages, handles text commands, and detects/downloads media files.
File: Example/simple-bot.js
const { ArattixBot, Bot } = require('arattix');
const fs = require('fs');
const path = require('path');
const POLL_INTERVAL = 3000;
const PREFIX = '/';
const DOWNLOAD_DIR = path.join(__dirname, '..', 'downloads');
if (!fs.existsSync(DOWNLOAD_DIR)) {
fs.mkdirSync(DOWNLOAD_DIR, { recursive: true });
}
const lastSeen = {};
// ─── Command Handlers ────────────────────────────────────
const commands = {
ping: async (msg, bot, chatId) => {
await bot.sender.sendMessage('🏓 Pong!', {
chatId, dname: 'Arattix Bot'
});
},
help: async (msg, bot, chatId) => {
await bot.sender.sendMessage(
'📋 *Available Commands*\n' +
'/ping - Check if bot is alive\n' +
'/help - Show this help\n' +
'/echo <text> - Echo back your text\n' +
'/info - Show chat info\n' +
'\n📎 Send any media and the bot will detect it!',
{ chatId, dname: 'Arattix Bot' }
);
},
echo: async (msg, bot, chatId) => {
const text = msg.content?.text?.slice(6).trim();
if (text) {
await bot.sender.sendMessage(`🔊 ${text}`, {
chatId, dname: 'Arattix Bot'
});
}
},
info: async (msg, bot, chatId, chatTitle) => {
await bot.sender.sendMessage(
`ℹ️ Chat: ${chatTitle}\n` +
`ID: ${chatId}\n` +
`Your name: ${msg.sender?.name}\n` +
`Your ID: ${msg.sender?.id}`,
{ chatId, dname: 'Arattix Bot' }
);
},
};
// ─── Main ─────────────────────────────────────────────────
async function main() {
console.log('🤖 Arattix Bot starting...\n');
const arattix = new ArattixBot({ isShowQr: true });
const bot = await arattix.loginWithQr();
console.log('✅ Logged in!\n');
await bot.setupCsrf();
// Get all chats
const chatData = await bot.fetchChatsRaw({ limit: 30 });
const chatList = chatData.data?.chats || [];
console.log(`📋 Monitoring ${chatList.length} chats`);
// Initialize message tracking
for (const chat of chatList) {
try {
const msgs = await bot.fetchMessages(chat.chatid, { limit: 1 });
if (msgs.length > 0) {
lastSeen[chat.chatid] = msgs[msgs.length - 1].id;
}
} catch (err) {
// Skip chats that fail
}
}
console.log('⏳ Bot is now listening...\n');
// Poll loop
setInterval(async () => {
for (const chat of chatList) {
try {
const msgs = await bot.fetchMessages(chat.chatid, { limit: 5 });
for (const msg of msgs) {
if (lastSeen[chat.chatid] && msg.id <= lastSeen[chat.chatid]) continue;
// Handle text commands
const text = msg.content?.text;
if (text && text.startsWith(PREFIX)) {
const cmd = text.slice(PREFIX.length).split(' ')[0].toLowerCase();
if (commands[cmd]) {
await commands[cmd](msg, bot, chat.chatid, chat.title);
}
}
// Handle media
if (Bot.isMediaMessage(msg)) {
const info = Bot.getMediaInfo(msg);
console.log(`📁 Media in ${chat.title}: ${info.fileName}`);
await bot.sender.sendMessage(
`📁 Received: ${info.fileName} (${info.mimeType})`,
{ chatId: chat.chatid, dname: 'Arattix Bot' }
);
}
}
if (msgs.length > 0) {
lastSeen[chat.chatid] = msgs[msgs.length - 1].id;
}
} catch (err) {
// Silently handle errors per chat
}
}
}, POLL_INTERVAL);
}
main().catch(console.error);
Minimal Echo Bot
The simplest possible bot — replies to every message with its content.
const { ArattixBot } = require('arattix');
async function main() {
const bot = await new ArattixBot().loginWithQr();
await bot.setupCsrf();
const chats = await bot.fetchChatsRaw({ limit: 5 });
const chatList = chats.data?.chats || [];
const lastSeen = {};
// Initialize
for (const c of chatList) {
const msgs = await bot.fetchMessages(c.chatid, { limit: 1 });
if (msgs.length) lastSeen[c.chatid] = msgs.at(-1).id;
}
// Poll
setInterval(async () => {
for (const c of chatList) {
const msgs = await bot.fetchMessages(c.chatid, { limit: 5 });
for (const m of msgs) {
if (lastSeen[c.chatid] && m.id <= lastSeen[c.chatid]) continue;
if (m.content?.text) {
await bot.sender.sendMessage(
`Echo: ${m.content.text}`,
{ chatId: c.chatid, dname: 'Echo Bot' }
);
}
}
if (msgs.length) lastSeen[c.chatid] = msgs.at(-1).id;
}
}, 3000);
}
main();
Media Forwarder
Downloads any image received in one chat and forwards it to another chat.
const { ArattixBot, Bot, MediaInfo } = require('arattix');
const SOURCE_CHAT = 'chat_id_to_monitor';
const TARGET_CHAT = 'chat_id_to_forward_to';
async function main() {
const bot = await new ArattixBot().loginWithQr();
await bot.setupCsrf();
let lastId = null;
// Initialize
const msgs = await bot.fetchMessages(SOURCE_CHAT, { limit: 1 });
if (msgs.length) lastId = msgs.at(-1).id;
console.log('📡 Monitoring for media...');
setInterval(async () => {
const msgs = await bot.fetchMessages(SOURCE_CHAT, { limit: 10 });
for (const msg of msgs) {
if (lastId && msg.id <= lastId) continue;
const media = MediaInfo.from(msg);
if (media && media.isImage) {
console.log(`🖼️ Found image: ${media.fileName}`);
// Download
const { data } = await bot.downloadMedia(
media.fileId, SOURCE_CHAT
);
// Forward
await bot.sender.sendBuffer(data, media.fileName, {
chatId: TARGET_CHAT,
caption: `Forwarded from source chat`
});
console.log('✅ Forwarded!');
}
}
if (msgs.length) lastId = msgs.at(-1).id;
}, 3000);
}
main();
List All Chats
A simple script to list all your chats with details.
const { ArattixBot } = require('arattix');
async function main() {
const bot = await new ArattixBot().loginWithQr();
await bot.setupCsrf();
const chats = await bot.fetchChats({ limit: 50 });
console.log('Your Chats:\n');
let i = 1;
for (const [id, chat] of Object.entries(chats)) {
console.log(`${i}. ${chat.title}`);
console.log(` ID: ${id}`);
console.log(` Owner: ${chat.owner.getDname()}`);
console.log(` Participants: ${chat.participants.length}`);
console.log();
i++;
}
}
main();
Docker Deployment
Deploy any of the above bots using Docker for production environments.
Create your bot file
// my-production-bot.js
const { ArattixBot } = require('arattix');
async function main() {
console.log('🐳 Starting containerized Arattix bot...');
const arattix = new ArattixBot({
isShowQr: true,
// Use environment variables for configuration
proxy: process.env.HTTP_PROXY || null
});
const bot = await arattix.loginWithQr();
await bot.setupCsrf();
const chats = await bot.fetchChatsRaw({ limit: 10 });
console.log(`📋 Monitoring ${chats.data?.chats?.length || 0} chats`);
// Your bot logic here...
// Example: Simple echo functionality
const lastSeen = {};
setInterval(async () => {
for (const chat of chats.data?.chats || []) {
try {
const msgs = await bot.fetchMessages(chat.chatid, { limit: 5 });
for (const msg of msgs) {
if (lastSeen[chat.chatid] && msg.id <= lastSeen[chat.chatid]) continue;
if (msg.content?.text?.startsWith('/hello')) {
await bot.sender.sendMessage('🐳 Hello from Docker!', {
chatId: chat.chatid,
dname: 'Docker Bot'
});
}
}
if (msgs.length) lastSeen[chat.chatid] = msgs.at(-1).id;
} catch (err) {
console.error(`Error in chat ${chat.chatid}:`, err.message);
}
}
}, 5000);
}
main().catch(console.error);
Deploy with Docker
# Build the image
docker build -t my-arattix-bot .
# Run with persistence
docker run -d \
--name arattix-production \
-v $(pwd)/cookies.json:/app/cookies.json \
-v $(pwd)/downloads:/app/downloads \
-v $(pwd)/my-production-bot.js:/app/my-production-bot.js \
-e NODE_ENV=production \
my-arattix-bot node my-production-bot.js
# Check logs
docker logs -f arattix-production
Using Docker Compose
# docker-compose.override.yml
services:
arattix-bot:
volumes:
- ./my-production-bot.js:/app/my-production-bot.js
command: node my-production-bot.js
environment:
- NODE_ENV=production
- BOT_NAME=MyProductionBot
Production Tips
• Always use volume mounts for
• Set restart policies with
• Monitor logs with
• Use healthchecks to ensure your bot is responsive
cookies.json persistence• Set restart policies with
--restart unless-stopped• Monitor logs with
docker logs• Use healthchecks to ensure your bot is responsive