bot-wa / bot.js
Rasyid2567
3
dbdbfc0
Raw History Blame Contribute Delete
23.8 kB
const { Client, LocalAuth, MessageMedia } = require('whatsapp-web.js');
const qrcode = require('qrcode-terminal');
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('Bot WhatsApp Aktif!');
res.end();
}).listen(process.env.PORT || 8000);
console.log('='.repeat(50));
console.log('🤖 WA-BOT - Sticker, Smeme, Brat & Bratvid');
console.log('='.repeat(50));
// Konfigurasi
const CONFIG = {
MAX_SIZE: 8 * 1024 * 1024, // 8MB untuk gambar
MAX_VIDEO_SIZE: 8 * 1024 * 1024, // 8MB untuk video (WhatsApp limit)
STICKER_SIZE: 512,
SMEME_COMMAND: '.smeme',
STICKER_COMMAND: '.s',
WATERMARK_COMMAND: '.wm',
BRAT_COMMAND: '.brat', // Video to animated sticker
BRATVID_COMMAND: '.bratvid', // Kirim video pendek
HELP_COMMAND: '.help',
PING_COMMAND: '.ping'
};
// Client setup
const client = new Client({
authStrategy: new LocalAuth({
dataPath: './.wwebjs_auth',
clientId: 'wa-bot-ultimate'
}),
puppeteer: {
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage']
}
});
// ========== QR CODE HANDLER ==========
client.on('qr', (qr) => {
console.log('\n📱 QR CODE READY!');
console.log('='.repeat(40));
qrcode.generate(qr, { small: true });
console.log('='.repeat(40));
console.log('\n📝 CARA SCAN:');
console.log('1. WhatsApp HP > ⋯ > Linked Devices');
console.log('2. Link a Device > Scan QR');
console.log('='.repeat(50));
});
// ========== READY HANDLER ==========
client.on('ready', () => {
console.log('\n✅ BOT READY!');
console.log(`🤖 Name: ${client.info.pushname}`);
console.log(`📱 Number: ${client.info.wid.user}`);
console.log(`🕐 Connected: ${new Date().toLocaleString()}`);
console.log('\n🎮 COMMANDS:');
console.log('• .ping - Cek bot hidup');
console.log('• .help - Bantuan');
console.log('• .s - Sticker dari gambar');
console.log('• .smeme <teks atas> | <teks bawah> - Buat meme');
console.log('• .wm <nama> - Ubah nama author sticker');
console.log('• .brat - Video jadi sticker (max 8MB, <10 detik)');
console.log('• .bratvid - Kirim video pendek');
console.log('\n⏳ PROGRESS REACTIONS:');
console.log('• Sticker → ⏳ → ✅ → 🎨');
console.log('• Smeme → ⏳ → ✅ → 😂');
console.log('• Brat → ⏳ → ✅ → 🎬');
console.log('• Bratvid → ⏳ → ✅ → 📹');
console.log('='.repeat(50));
});
// ========== MESSAGE HANDLER ==========
client.on('message', async message => {
const text = message.body?.trim() || '';
try {
// ========== AUTO REACTION ==========
// Reaksi untuk sticker yang dikirim user
if (message.hasMedia && message.type === 'sticker') {
const stickerEmojis = ['😍', '👍', '😂', '🔥', '🎉', '👌', '😎', '✨'];
const randomEmoji = stickerEmojis[Math.floor(Math.random() * stickerEmojis.length)];
await message.react(randomEmoji);
console.log(`✅ Reacted to sticker with: ${randomEmoji}`);
}
// Reaksi untuk video yang dikirim user
if (message.hasMedia && message.type === 'video') {
await message.react('🎬');
console.log('✅ Reacted to video with 🎬');
}
// Reaksi untuk kata-kata tertentu
await autoReactToKeywords(message, text);
// ========== COMMANDS ==========
const quotedMsg = message.hasQuotedMsg ? await message.getQuotedMessage() : null;
// Sticker biasa (.s)
if (text.toLowerCase() === CONFIG.STICKER_COMMAND) {
await createSticker(message, 'Bot WA', 'Custom Sticker', quotedMsg);
}
// Smeme (.smeme <teks>)
else if (text.toLowerCase().startsWith(CONFIG.SMEME_COMMAND)) {
await createSmeme(message, text, quotedMsg);
}
// Watermark (.wm <nama>)
else if (text.toLowerCase().startsWith(CONFIG.WATERMARK_COMMAND)) {
await changeStickerAuthor(message, text);
}
// Brat - Video to animated sticker (.brat)
else if (text.toLowerCase() === CONFIG.BRAT_COMMAND) {
await createBratSticker(message, quotedMsg);
}
// Bratvid - Kirim video pendek (.bratvid)
else if (text.toLowerCase() === CONFIG.BRATVID_COMMAND) {
await sendBratVideo(message, quotedMsg);
}
// Ping (.ping)
else if (text.toLowerCase() === CONFIG.PING_COMMAND) {
const uptime = process.uptime();
const hours = Math.floor(uptime / 3600);
const minutes = Math.floor((uptime % 3600) / 60);
const seconds = Math.floor(uptime % 60);
const uptimeStr = `${hours}h ${minutes}m ${seconds}s`;
await message.reply(`🏓 Pong! Bot aktif!\n⏳ Uptime: ${uptimeStr}`);
await message.react('🏓');
}
// Help (.help)
else if (text.toLowerCase() === CONFIG.HELP_COMMAND) {
await sendHelp(message);
}
// Jika kirim video tanpa command
else if (message.hasMedia && message.type === 'video' && !text.includes('.')) {
await message.reply('📹 Kirim video dengan caption atau reply ke video:\n• .brat - Untuk sticker animasi\n• .bratvid - Untuk video pendek');
}
} catch (error) {
console.error('❌ Error:', error);
}
});
// ========== FUNGSI UTAMA ==========
// 1. Fungsi buat sticker biasa
async function createSticker(message, author, stickerName, quotedMsg = null) {
try {
const targetMessage = message.hasMedia ? message : (quotedMsg && quotedMsg.hasMedia ? quotedMsg : null);
if (!targetMessage || (targetMessage.type !== 'image' && targetMessage.type !== 'sticker')) {
await message.reply('❌ Kirim gambar atau reply ke gambar dengan caption .s');
return;
}
console.log('🔄 Membuat sticker...');
await message.react('⏳');
const media = await targetMessage.downloadMedia();
if (!media || !media.data) throw new Error('Gambar tidak valid');
const buffer = Buffer.from(media.data, 'base64');
const processedBuffer = await sharp(buffer)
.resize(CONFIG.STICKER_SIZE, CONFIG.STICKER_SIZE, {
fit: 'contain',
background: { r: 0, g: 0, b: 0, alpha: 0 }
})
.png()
.toBuffer();
// Step 2: Kirim sticker
await sendAsSticker(message.from, processedBuffer, author, stickerName);
// Step 3: Hapus reaction jam, kasih centang (✅)
await clearReaction(message);
await message.react('✅');
await message.reply('✅ Sticker berhasil dibuat! 🎉');
console.log('✅ Sticker created with reactions');
} catch (error) {
console.error('❌ Sticker error:', error);
// Hapus reaction jam, kasih X
await clearReaction(message);
await message.react('❌');
throw error;
}
}
// 2. Fungsi buat smeme (dengan teks atas & bawah)
async function createSmeme(message, text, quotedMsg = null) {
try {
const fullText = text.substring(CONFIG.SMEME_COMMAND.length).trim();
if (!fullText) {
await message.reply('❌ Format: .smeme <teks>\nContoh:\n• .smeme Lucu banget\n• .smeme TEKS ATAS | TEKS BAWAH');
return;
}
const targetMessage = message.hasMedia ? message : (quotedMsg && quotedMsg.hasMedia ? quotedMsg : null);
if (!targetMessage || targetMessage.type !== 'image') {
await message.reply('❌ Kirim gambar dengan caption .smeme atau reply ke gambar!');
return;
}
let topText = '';
let bottomText = '';
if (fullText.includes('|')) {
const parts = fullText.split('|').map(p => p.trim());
topText = parts[0] || '';
bottomText = parts[1] || '';
console.log(`🔄 Membuat smeme: ATAS="${topText}" BAWAH="${bottomText}"`);
// Step 1: Kasih reaction jam
await message.react('⏳');
} else {
topText = fullText;
console.log(`🔄 Membuat smeme: "${topText}"`);
// Step 1: Kasih reaction jam
await message.react('⏳');
}
const media = await targetMessage.downloadMedia();
if (!media || !media.data) throw new Error('Gambar tidak valid');
const buffer = Buffer.from(media.data, 'base64');
const memeBuffer = await addTextToImage(buffer, topText, bottomText);
const stickerName = bottomText ? `${topText} - ${bottomText}` : topText;
// Step 2: Kirim sticker
await sendAsSticker(message.from, memeBuffer, 'Smeme Bot', stickerName);
// Step 3: Hapus reaction jam, kasih centang dan senyum
await clearReaction(message);
await message.react('✅');
await message.react('😂');
const successMsg = bottomText
? `✅ Smeme "${topText} | ${bottomText}" berhasil dibuat! 😄`
: `✅ Smeme "${topText}" berhasil dibuat! 😄`;
await message.reply(successMsg);
console.log('✅ Smeme created with reactions');
} catch (error) {
console.error('❌ Smeme error:', error);
// Hapus reaction jam, kasih sedih
await clearReaction(message);
await message.react('😢');
throw error;
}
}
// 3. Fungsi ubah nama author sticker (.wm)
async function changeStickerAuthor(message, text) {
try {
const authorName = text.substring(CONFIG.WATERMARK_COMMAND.length).trim();
if (!authorName) {
await message.reply('❌ Format: .wm <nama>\nContoh: .wm Nama Kamu');
return;
}
if (!message.hasQuotedMsg) {
await message.reply('❌ Reply sticker yang mau diganti nama authornya!');
return;
}
const quotedMsg = await message.getQuotedMessage();
if (!quotedMsg.hasMedia || quotedMsg.type !== 'sticker') {
await message.reply('❌ Hanya bisa reply ke sticker!');
return;
}
console.log(`🔄 Mengubah author sticker ke: "${authorName}"`);
// Step 1: Kasih reaction jam
await message.react('⏳');
const media = await quotedMsg.downloadMedia();
if (!media || !media.data) throw new Error('Sticker tidak valid');
const buffer = Buffer.from(media.data, 'base64');
const stickerName = quotedMsg.body || 'Custom Sticker';
// Step 2: Kirim sticker baru
await sendAsSticker(message.from, buffer, authorName, stickerName);
// Step 3: Hapus reaction jam, kasih centang dan glitter
await clearReaction(message);
await message.react('✅');
await message.react('✨');
await message.reply(`✅ Sticker dengan author "${authorName}" berhasil dibuat! ✨`);
console.log('✅ Author changed with reactions');
} catch (error) {
console.error('❌ Watermark error:', error);
// Hapus reaction jam, kasih warning
await clearReaction(message);
await message.react('⚠️');
throw error;
}
}
// 4. Fungsi BRAT - Video jadi sticker (FIXED)
async function createBratSticker(message, quotedMsg = null) {
try {
const targetMessage = message.hasMedia ? message : (quotedMsg && quotedMsg.hasMedia ? quotedMsg : null);
if (!targetMessage || !targetMessage.hasMedia || !targetMessage.mimetype.includes('video')) {
await message.reply('❌ Kirim video dengan caption .brat atau reply ke video!');
return;
}
console.log('🔄 Memproses BRAT (video to sticker)...');
await message.react('⏳');
const media = await targetMessage.downloadMedia();
if (!media || !media.data) {
throw new Error('Video tidak valid');
}
// Cek ukuran
const fileSize = (media.data.length * 3) / 4;
if (fileSize > CONFIG.MAX_VIDEO_SIZE) {
throw new Error(`Video terlalu besar! Maksimal ${CONFIG.MAX_VIDEO_SIZE / 1024 / 1024}MB`);
}
console.log(`📹 Video size: ${(fileSize / 1024 / 1024).toFixed(2)}MB`);
// Step 2: Kirim video sebagai media message
// WhatsApp akan otomatis convert video pendek ke format yang sesuai
const videoMedia = new MessageMedia(media.mimetype, media.data, 'video.mp4');
// Kirim video dengan opsi sendMediaAsSticker
await client.sendMessage(message.from, videoMedia, {
sendMediaAsSticker: true,
stickerAuthor: 'Brat Bot',
stickerName: 'Video Sticker'
});
// Step 3: Hapus reaction jam, kasih centang dan film
await clearReaction(message);
await message.react('✅');
await message.react('🎬');
await message.reply('✅ Video berhasil dikonversi ke sticker! 🎬\n\nℹ️ WhatsApp akan otomatis convert video ke format sticker.');
console.log('✅ Brat sticker sent with reactions');
} catch (error) {
console.error('❌ Brat error:', error);
// Hapus reaction jam, kasih X
await clearReaction(message);
await message.react('❌');
if (error.message.includes('sticker')) {
await message.reply('❌ WhatsApp tidak bisa convert video ini ke sticker.\n💡 Coba video yang lebih pendek (<10 detik) atau lebih kecil (<8MB)');
} else {
await message.reply(`❌ Error: ${error.message}`);
}
throw error;
}
}
// 5. Fungsi BRATVID - Kirim video pendek
async function sendBratVideo(message, quotedMsg = null) {
try {
const targetMessage = message.hasMedia ? message : (quotedMsg && quotedMsg.hasMedia ? quotedMsg : null);
if (!targetMessage || !targetMessage.hasMedia || !targetMessage.mimetype.includes('video')) {
await message.reply('❌ Kirim video dengan caption .bratvid atau reply ke video!');
return;
}
console.log('🔄 Memproses BRATVID (kirim video)...');
await message.react('⏳');
const media = await targetMessage.downloadMedia();
if (!media || !media.data) {
throw new Error('Video tidak valid');
}
// Cek ukuran
const fileSize = (media.data.length * 3) / 4;
if (fileSize > CONFIG.MAX_VIDEO_SIZE) {
throw new Error(`Video terlalu besar! Maksimal ${CONFIG.MAX_VIDEO_SIZE / 1024 / 1024}MB`);
}
console.log(`📹 Video size: ${(fileSize / 1024 / 1024).toFixed(2)}MB`);
// Step 2: Kirim ulang video
const videoMedia = new MessageMedia(media.mimetype, media.data, 'video.mp4');
await client.sendMessage(message.from, videoMedia, {
caption: '📹 Video dari BRATVID'
});
// Step 3: Hapus reaction jam, kasih centang dan kamera
await clearReaction(message);
await message.react('✅');
await message.react('📹');
await message.reply('✅ Video berhasil dikirim! 📹');
console.log('✅ Bratvid sent with reactions');
} catch (error) {
console.error('❌ Bratvid error:', error);
// Hapus reaction jam, kasih X
await clearReaction(message);
await message.react('❌');
throw error;
}
}
// ========== HELPER FUNCTIONS ==========
// Fungsi untuk auto react berdasarkan kata kunci
async function autoReactToKeywords(message, text) {
const lowerText = text.toLowerCase();
// Mapping kata kunci ke emoji
const reactionMap = [
// Salam
{ keywords: ['hai', 'hi', 'hello', 'halo', 'p', 'assalamualaikum'], emoji: '👋' },
{ keywords: ['terima kasih', 'makasih', 'thanks', 'thank you'], emoji: '🙏' },
{ keywords: ['sama-sama', 'sama sama', 'youre welcome'], emoji: '😊' },
// Positif
{ keywords: ['ok', 'oke', 'okay', 'siap', 'roger', 'baik'], emoji: '👍' },
{ keywords: ['mantap', 'keren', 'bagus', 'hebat', 'wow'], emoji: '🔥' },
{ keywords: ['lucu', 'funny', 'haha', 'wkwk', 'ngakak'], emoji: '😂' },
{ keywords: ['love', 'sayang', 'cinta'], emoji: '❤️' },
// Command bot berhasil
{ keywords: ['berhasil', 'sukses', 'done', 'selesai'], emoji: '✅' },
{ keywords: ['gagal', 'error', 'failed'], emoji: '❌' },
// Sticker related
{ keywords: ['sticker', 'stiker', 'stikernya', 'hasilnya'], emoji: '🎨' },
{ keywords: ['meme', 'smeme', 'memes'], emoji: '🤡' },
{ keywords: ['brat', 'video sticker', 'animasi'], emoji: '🎬' },
{ keywords: ['bratvid', 'video pendek'], emoji: '📹' },
// Bot command
{ keywords: ['bot', 'bang bot', 'bro bot'], emoji: '🤖' },
{ keywords: ['ping', 'test'], emoji: '🏓' },
{ keywords: ['help', 'bantuan'], emoji: 'ℹ️' },
];
// Cek setiap mapping
for (const map of reactionMap) {
for (const keyword of map.keywords) {
if (lowerText.includes(keyword)) {
try {
await message.react(map.emoji);
console.log(`✅ Auto reacted with ${map.emoji} for keyword: ${keyword}`);
return true;
} catch (error) {
console.log(`❌ Failed to react: ${error.message}`);
}
}
}
}
return false;
}
// Fungsi untuk clear reaction
async function clearReaction(message) {
try {
// WhatsApp Web JS tidak punya clearReaction langsung
// Kita coba hapus dengan mengirim empty reaction atau timpa
try {
// Coba hapus reaction kita sendiri
await message.react(''); // Reaction kosong mungkin bisa hapus
} catch (e) {
// Jika tidak bisa, reaction baru akan timpa yang lama
return true;
}
return true;
} catch (error) {
console.log('⚠️ Cannot clear reaction:', error.message);
return false;
}
}
// Fungsi untuk menambah teks ke gambar (smeme)
async function addTextToImage(imageBuffer, topText, bottomText = '') {
try {
const imageWidth = 480;
const imageHeight = 380;
const resizedImage = await sharp(imageBuffer)
.resize(imageWidth, imageHeight, {
fit: 'contain',
background: { r: 0, g: 0, b: 0, alpha: 0 }
})
.png()
.toBuffer();
const padding = 16;
const textHeight = 56;
let svgElements = '';
if (topText) {
svgElements += `
<rect x="0" y="0" width="512" height="${textHeight}" fill="rgba(0,0,0,0.7)"/>
<text x="256" y="${textHeight / 2 + 8}"
font-family="Arial, sans-serif"
font-size="20"
font-weight="bold"
fill="white"
text-anchor="middle"
alignment-baseline="middle">
${escapeHtml(topText)}
</text>
`;
}
const imageY = topText ? textHeight + padding : padding;
svgElements += `
<image x="${padding}" y="${imageY}" width="${512 - 2 * padding}" height="${512 - imageY - (bottomText ? textHeight + padding : padding)}"
href="data:image/png;base64,${resizedImage.toString('base64')}"/>
`;
if (bottomText) {
const bottomY = 512 - textHeight;
svgElements += `
<rect x="0" y="${bottomY}" width="512" height="${textHeight}" fill="rgba(0,0,0,0.7)"/>
<text x="256" y="${bottomY + textHeight / 2 + 8}"
font-family="Arial, sans-serif"
font-size="20"
font-weight="bold"
fill="white"
text-anchor="middle"
alignment-baseline="middle">
${escapeHtml(bottomText)}
</text>
`;
}
const svgText = `
<svg width="512" height="512">
${svgElements}
</svg>
`;
const finalImage = await sharp(Buffer.from(svgText))
.png()
.toBuffer();
return finalImage;
} catch (error) {
console.error('❌ Add text error:', error);
throw new Error('Gagal menambahkan teks ke gambar');
}
}
// Fungsi escape HTML
function escapeHtml(text) {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
}
// Fungsi untuk kirim sticker
async function sendAsSticker(chatId, buffer, author, stickerName) {
const stickerBase64 = buffer.toString('base64');
const stickerMedia = new MessageMedia('image/png', stickerBase64, 'sticker.png');
await client.sendMessage(chatId, stickerMedia, {
sendMediaAsSticker: true,
stickerAuthor: author,
stickerName: stickerName.substring(0, 100)
});
}
// Fungsi bantuan
async function sendHelp(message) {
const helpText = `
🤖 *WA-BOT COMMANDS* 🤖
*🎨 STICKER:*
• \`.s\` - Buat sticker (Caption/Reply gambar)
• \`.wm <nama>\` - Ubah author (Reply sticker)
*🤡 SMEME (MEME STICKER):*
• \`.smeme <teks>\` - Teks atas (Caption/Reply gambar)
• \`.smeme t1 | t2\` - Teks atas & bawah
*🎬 BRAT (VIDEO TO STICKER):*
• \`.brat\` - Video ke sticker (Caption/Reply video)
• ⚠️ Max 8MB, <10 detik
*📹 BRATVID (SEND VIDEO):*
• \`.bratvid\` - Kirim video pendek
• Max 8MB
*🔄 PROGRESS INDICATOR:*
• ⏳ - Sedang diproses
• ✅ - Berhasil
• 🎨 - Sticker selesai
• 😂 - Smeme selesai
• 🎬 - Brat selesai
• 📹 - Bratvid selesai
• ✨ - Watermark selesai
• ❌ - Gagal
*💡 TIPS BRAT:*
1. Video harus pendek (<10 detik)
2. Ukuran kecil (<8MB)
3. WhatsApp auto convert ke format sticker
4. Jika gagal, coba video lain
*🎭 AUTO REACTION:*
• Sticker dari user → Random emoji
• Video → 🎬
• Kata "makasih" → 🙏
• Kata "mantap" → 🔥
• Kata "lucu" → 😂
*🛠️ LAINNYA:*
• \`.ping\` - Cek bot hidup → 🏓
• \`.help\` - Tampilkan bantuan ini → ℹ️
`;
await message.reply(helpText);
await message.react('ℹ️');
console.log('✅ Help sent with reaction');
}
// ========== ERROR HANDLERS ==========
client.on('auth_failure', (msg) => {
console.log('❌ AUTH FAILED:', msg);
});
client.on('disconnected', (reason) => {
console.log('🔌 Disconnected:', reason);
console.log('🔄 Reconnecting in 10s...');
setTimeout(() => client.initialize(), 10000);
});
// ========== START BOT ==========
client.initialize();
// Handle exit
process.on('SIGINT', async () => {
console.log('\n🛑 Stopping bot...');
await client.destroy();
console.log('✅ Bot stopped');
process.exit(0);
});
// ========== SERVER FOR HOSTING ==========
const PORT = process.env.PORT || 8000;
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Bot is running!\n');
}).listen(PORT, () => {
console.log(`🚀 Server listening on port ${PORT}`);
});