Files
wauto/index.ts
T
2026-11-21 01:47:48 +07:00

247 lines
7.3 KiB
TypeScript

import makeWASocket, {
useMultiFileAuthState,
DisconnectReason,
fetchLatestBaileysVersion,
downloadContentFromMessage,
extractMessageContent,
WASocket,
WAMessage,
proto,
} from '@whiskeysockets/baileys'
import qrcode from 'qrcode-terminal'
import pino from 'pino'
import sharp from 'sharp'
const PREFIX = '!'
// false = react to everyone (and yourself). true = only react to messages YOU send.
const SELF_ONLY = false
type Handler = (sock: WASocket, msg: WAMessage, args: string[]) => Promise<void>
interface TargetMedia {
media: any
type: 'image' | 'video' | 'sticker'
key?: proto.IMessageKey
}
function getTargetMedia(msg: WAMessage): TargetMedia | null {
const m = extractMessageContent(msg.message)
if (!m) return null
// 1. Direct media in the message
if (m.imageMessage) {
return { media: m.imageMessage, type: 'image', key: msg.key }
}
if (m.stickerMessage) {
return { media: m.stickerMessage, type: 'sticker', key: msg.key }
}
if (m.videoMessage && (m.videoMessage.seconds ?? 0) <= 10) {
return { media: m.videoMessage, type: 'video', key: msg.key }
}
if (m.documentMessage && m.documentMessage.mimetype?.startsWith('image/')) {
return { media: m.documentMessage, type: 'image', key: msg.key }
}
// 2. Quoted media (replying to an image/sticker/video/image-document)
const ctx =
m.extendedTextMessage?.contextInfo ||
(m as any).imageMessage?.contextInfo ||
(m as any).videoMessage?.contextInfo
if (ctx?.quotedMessage) {
const quoted = extractMessageContent(ctx.quotedMessage)
if (quoted) {
const quotedKey: proto.IMessageKey = {
remoteJid: msg.key.remoteJid,
id: ctx.stanzaId ?? undefined,
participant: ctx.participant ?? undefined,
fromMe: ctx.participant ? false : msg.key.fromMe,
}
if (quoted.imageMessage) {
return { media: quoted.imageMessage, type: 'image', key: quotedKey }
}
if (quoted.stickerMessage) {
return { media: quoted.stickerMessage, type: 'sticker', key: quotedKey }
}
if (quoted.videoMessage && (quoted.videoMessage.seconds ?? 0) <= 10) {
return { media: quoted.videoMessage, type: 'video', key: quotedKey }
}
if (quoted.documentMessage && quoted.documentMessage.mimetype?.startsWith('image/')) {
return { media: quoted.documentMessage, type: 'image', key: quotedKey }
}
}
}
return null
}
async function downloadMedia(
media: any,
type: 'image' | 'video' | 'sticker',
key?: proto.IMessageKey,
sock?: WASocket,
): Promise<Buffer> {
const fetchStream = async (m: any) => {
const stream = await downloadContentFromMessage(
{
mediaKey: m.mediaKey,
directPath: m.directPath,
url: m.url,
},
type,
)
const chunks: Buffer[] = []
for await (const chunk of stream) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
}
return Buffer.concat(chunks)
}
try {
return await fetchStream(media)
} catch (err: any) {
// If the media link expired, try requesting a reupload if socket and key are available
if (sock && key && (err?.status === 404 || err?.status === 410)) {
try {
const reuploaded = await sock.updateMediaMessage({
key,
message: { [`${type}Message`]: media },
} as any)
const content = extractMessageContent(reuploaded.message) as any
const newMedia = content?.[`${type}Message`]
if (newMedia) {
return await fetchStream(newMedia)
}
} catch {
// Fall back to original error
}
}
throw err
}
}
const commands: Record<string, Handler> = {
ping: async (sock, msg) => {
await sock.sendMessage(msg.key.remoteJid!, { text: 'pong 🏓' }, { quoted: msg })
},
time: async (sock, msg) => {
const now = new Date().toLocaleString('id-ID', { timeZone: 'Asia/Jakarta' })
await sock.sendMessage(msg.key.remoteJid!, { text: `🕒 ${now} WIB` }, { quoted: msg })
},
echo: async (sock, msg, args) => {
await sock.sendMessage(msg.key.remoteJid!, { text: args.join(' ') || '(empty)' }, { quoted: msg })
},
sticker: async (sock, msg) => {
const jid = msg.key.remoteJid!
const target = getTargetMedia(msg)
if (!target) {
await sock.sendMessage(
jid,
{ text: 'Send an image with caption !sticker, or reply to an image/sticker with !sticker' },
{ quoted: msg },
)
return
}
const buffer = await downloadMedia(target.media, target.type, target.key, sock)
let webp: Buffer
try {
webp = await sharp(buffer, { animated: true })
.resize(512, 512, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } })
.webp({ quality: 80 })
.toBuffer()
} catch {
webp = await sharp(buffer)
.resize(512, 512, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } })
.webp({ quality: 80 })
.toBuffer()
}
await sock.sendMessage(jid, { sticker: webp }, { quoted: msg })
},
help: async (sock, msg) => {
const list = Object.keys(commands).map((c) => PREFIX + c).join('\n')
await sock.sendMessage(msg.key.remoteJid!, { text: `Commands:\n${list}` }, { quoted: msg })
},
}
// Aliases for sticker
commands.stiker = commands.sticker
commands.s = commands.sticker
function getText(msg: WAMessage): string {
const m = extractMessageContent(msg.message)
return (
m?.conversation ||
m?.extendedTextMessage?.text ||
m?.imageMessage?.caption ||
m?.videoMessage?.caption ||
m?.documentMessage?.caption ||
''
)
}
async function start() {
const { state, saveCreds } = await useMultiFileAuthState('auth')
const { version } = await fetchLatestBaileysVersion()
const sock = makeWASocket({
version,
auth: state,
logger: pino({ level: 'silent' }),
markOnlineOnConnect: false,
})
sock.ev.on('creds.update', saveCreds)
sock.ev.on('connection.update', ({ connection, lastDisconnect, qr }) => {
if (qr) {
console.log('Scan this QR: WhatsApp > Linked devices > Link a device')
qrcode.generate(qr, { small: true })
}
if (connection === 'open') console.log('✅ Connected')
if (connection === 'close') {
const code = (lastDisconnect?.error as any)?.output?.statusCode
if (code === DisconnectReason.loggedOut) {
console.log('Logged out. Delete the "auth" folder and run again.')
} else {
console.log('Connection closed, reconnecting...')
start()
}
}
})
sock.ev.on('messages.upsert', async ({ messages, type }) => {
if (type !== 'notify') return
for (const msg of messages) {
if (!msg.message || !msg.key.remoteJid) continue
if (SELF_ONLY && !msg.key.fromMe) continue
const text = getText(msg).trim()
if (!text.startsWith(PREFIX)) continue
const [name, ...args] = text.slice(PREFIX.length).split(/\s+/)
const handler = commands[name.toLowerCase()]
if (!handler) continue
try {
await handler(sock, msg, args)
} catch (err) {
console.error(`Error in !${name}:`, err)
try {
await sock.sendMessage(
msg.key.remoteJid!,
{ text: `⚠️ Error in !${name}: ${(err as Error)?.message || 'Something went wrong'}` },
{ quoted: msg },
)
} catch {}
}
}
})
}
start()