Files
wapp/test/index.js
2025-12-06 18:58:29 +01:00

82 lines
2.3 KiB
JavaScript

const { Client, LocalAuth } = require('whatsapp-web.js')
const qrcode = require('qrcode-terminal')
// Initialize client with session persistence
const client = new Client({
authStrategy: new LocalAuth(), // Saves session so you don't need to scan QR every time
puppeteer : {
headless: true,
args : ['--no-sandbox', '--disable-setuid-sandbox']
}
})
// Generate QR in terminal
client.on('qr', (qr) => {
console.log('\n📱 Scan this QR code with WhatsApp:')
qrcode.generate(qr, { small: true })
})
// When client is ready
/*client.on('ready', () => {
console.log('\n✅ Client is ready!')
console.log('Listening for messages...')
console.log('Use Ctrl+C to exit\n')
})*/
client.on('ready', async () => {
console.log('\n✅ Client is ready!')
// Auto-reply to the last person who messaged you
let lastContact = null
var currentTimeAndDateTodayAsDutchh = new Date().toLocaleString('nl-NL', { timeZone: 'Europe/Amsterdam' })
await sendMessage('31639266516@c.us', currentTimeAndDateTodayAsDutchh + 'Yoo toppertje 🎉!')
client.on('message', (message) => {
console.log(`📥 [${ message.from }] ${ message.body }`)
lastContact = message.from.split('@')[0] // Extract number
// Send after 10 seconds
setTimeout(async () => {
if (lastContact) {
console.log(`\nSending test to ${ lastContact }...`)
await sendMessage(lastContact, 'Yooo toppertje🎉!')
} else
console.log('No last contact found')
}, 2000)
})
})
// Listen for incoming messages
client.on('message', (message) => {
console.log(`📥 [${ message.from }] ${ message.body || '(media message)' }`)
// Auto-reply example
if (message.body.toLowerCase() === 'ping') {
message.reply('🏓 Pong!')
console.log(' Replied with "Pong!"')
}
})
// Function to send messages
const sendMessage = async (number, text) => {
try {
const chatId = number.includes('@c.us') ? number : `${ number }@c.us`
await client.sendMessage(chatId, text)
console.log(`✅ Sent to ${ number }: "${ text }"`)
return true
} catch (error) {
console.error(`❌ Error sending to ${ number }:`, error.message)
return false
}
}
// Export for external use
module.exports = { client, sendMessage }
// Initialize client
client.initialize()
// Graceful shutdown
process.on('SIGINT', async () => {
console.log('\n🛑 Shutting down...')
await client.destroy()
process.exit(0)
})