Skip to content

Conversation

@riganrambu758-hash
Copy link

// bot.js
// Simple WhatsApp bot using Baileys
const { default: makeWASocket, useMultiFileAuthState, DisconnectReason, fetchLatestBaileysVersion } = require('@whiskeysockets/baileys') const qrcode = require('qrcode-terminal')
const fs = require('fs')

async function start() {
// simpan session di folder "session"
const { state, saveCreds } = await useMultiFileAuthState('session')

// dapatkan versi baileys (optional) untuk kompatibilitas
let { version, isLatest } = await fetchLatestBaileysVersion().catch(() => ({ version: [4, 0, 0], isLatest: false }))

const sock = makeWASocket({
auth: state,
printQRInTerminal: false, // kita handle QR sendiri
version
})

// print QR ke terminal ketika muncul
sock.ev.on('connection.update', (update) => {
const { connection, qr, lastDisconnect } = update
if (qr) {
console.log('QR CODE TERSEDIA — scan dengan WhatsApp di device lain')
qrcode.generate(qr, { small: true })
}
if (connection === 'open') {
console.log('✅ Bot WhatsApp berhasil konek!')
}
if (connection === 'close') {
const reason = (lastDisconnect?.error)?.output?.statusCode || lastDisconnect?.error?.toString()
console.log('⚠️ Koneksi tertutup:', reason)
// reconnect logic simple:
if (lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut) {
console.log('Mencoba reconnect dalam 5 detik...')
setTimeout(start, 5000)
} else {
console.log('Session ter-logout. Hapus folder session untuk login ulang.')
}
}
})

// simpan credentials saat ada update
sock.ev.on('creds.update', saveCreds)

// event pesan masuk
sock.ev.on('messages.upsert', async (m) => {
try {
const upsert = m
if (!upsert.messages) return
const msg = upsert.messages[0]
if (!msg.message || msg.key.fromMe) return

  const from = msg.key.remoteJid
  const messageText = msg.message.conversation || msg.message?.extendedTextMessage?.text || ''

  console.log(`[Pesan] dari ${from}: ${messageText}`)

  // simple command handling
  const text = messageText?.toString().trim().toLowerCase()

  if (text === 'halo' || text === 'hi' || text === 'hai') {
    await sock.sendMessage(from, { text: 'Halo 👋, saya bot! Ketik "menu" untuk opsi.' })
  } else if (text === 'menu') {
    await sock.sendMessage(from, {
      text: '📌 Menu Bot:\n1. halo\n2. menu\n3. info\n4. ping'
    })
  } else if (text === 'info') {
    await sock.sendMessage(from, { text: '🤖 Bot sederhana menggunakan Baileys (Termux).' })
  } else if (text === 'ping') {
    const time = new Date().toLocaleString()
    await sock.sendMessage(from, { text: `Pong! waktu server: ${time}` })
  } else {
    // fallback auto-reply
    await sock.sendMessage(from, { text: 'Maaf, aku tidak mengerti. Ketik "menu".' })
  }
} catch (e) {
  console.error('Error handling message', e)
}

})
}

start().catch(err => console.error('Start failed:', err))

// bot.js
// Simple WhatsApp bot using Baileys
const { default: makeWASocket, useMultiFileAuthState, DisconnectReason, fetchLatestBaileysVersion } = require('@whiskeysockets/baileys')
const qrcode = require('qrcode-terminal')
const fs = require('fs')

async function start() {
  // simpan session di folder "session"
  const { state, saveCreds } = await useMultiFileAuthState('session')

  // dapatkan versi baileys (optional) untuk kompatibilitas
  let { version, isLatest } = await fetchLatestBaileysVersion().catch(() => ({ version: [4, 0, 0], isLatest: false }))

  const sock = makeWASocket({
    auth: state,
    printQRInTerminal: false, // kita handle QR sendiri
    version
  })

  // print QR ke terminal ketika muncul
  sock.ev.on('connection.update', (update) => {
    const { connection, qr, lastDisconnect } = update
    if (qr) {
      console.log('QR CODE TERSEDIA — scan dengan WhatsApp di device lain')
      qrcode.generate(qr, { small: true })
    }
    if (connection === 'open') {
      console.log('✅ Bot WhatsApp berhasil konek!')
    }
    if (connection === 'close') {
      const reason = (lastDisconnect?.error)?.output?.statusCode || lastDisconnect?.error?.toString()
      console.log('⚠️ Koneksi tertutup:', reason)
      // reconnect logic simple:
      if (lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut) {
        console.log('Mencoba reconnect dalam 5 detik...')
        setTimeout(start, 5000)
      } else {
        console.log('Session ter-logout. Hapus folder session untuk login ulang.')
      }
    }
  })

  // simpan credentials saat ada update
  sock.ev.on('creds.update', saveCreds)

  // event pesan masuk
  sock.ev.on('messages.upsert', async (m) => {
    try {
      const upsert = m
      if (!upsert.messages) return
      const msg = upsert.messages[0]
      if (!msg.message || msg.key.fromMe) return

      const from = msg.key.remoteJid
      const messageText = msg.message.conversation || msg.message?.extendedTextMessage?.text || ''

      console.log(`[Pesan] dari ${from}: ${messageText}`)

      // simple command handling
      const text = messageText?.toString().trim().toLowerCase()

      if (text === 'halo' || text === 'hi' || text === 'hai') {
        await sock.sendMessage(from, { text: 'Halo 👋, saya bot! Ketik "menu" untuk opsi.' })
      } else if (text === 'menu') {
        await sock.sendMessage(from, {
          text: '📌 Menu Bot:\n1. halo\n2. menu\n3. info\n4. ping'
        })
      } else if (text === 'info') {
        await sock.sendMessage(from, { text: '🤖 Bot sederhana menggunakan Baileys (Termux).' })
      } else if (text === 'ping') {
        const time = new Date().toLocaleString()
        await sock.sendMessage(from, { text: `Pong! waktu server: ${time}` })
      } else {
        // fallback auto-reply
        await sock.sendMessage(from, { text: 'Maaf, aku tidak mengerti. Ketik "menu".' })
      }
    } catch (e) {
      console.error('Error handling message', e)
    }
  })
}

start().catch(err => console.error('Start failed:', err))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant