File size: 6,840 Bytes
2981fab
 
 
2f9aca7
166bee6
2981fab
45cd9df
2f9aca7
deef0c2
0f8176d
2981fab
deef0c2
0bc72e7
cb00eaf
deef0c2
0f8176d
38f4661
2981fab
2f9aca7
 
0f8176d
deef0c2
0bc72e7
deef0c2
 
0f8176d
 
 
 
 
 
 
 
9e63409
0f8176d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e63409
deef0c2
166bee6
9e63409
 
 
 
 
0f8176d
 
 
 
 
 
9e63409
 
 
 
 
0f8176d
 
 
 
 
 
 
 
166bee6
cb00eaf
0f8176d
deef0c2
 
cb00eaf
0f8176d
 
deef0c2
45cd9df
 
 
 
 
deef0c2
45cd9df
deef0c2
45cd9df
cb00eaf
0f8176d
9e63409
 
 
0f8176d
38f4661
9e63409
 
0f8176d
9e63409
0f8176d
 
 
9e63409
 
 
 
45cd9df
 
 
 
 
deef0c2
0f8176d
 
deef0c2
45cd9df
2981fab
45cd9df
deef0c2
45cd9df
0f8176d
 
 
166bee6
0f8176d
 
 
 
 
45cd9df
9e63409
0f8176d
 
 
 
 
 
 
 
 
 
 
 
9e63409
 
2981fab
45cd9df
2981fab
45cd9df
 
 
 
2f9aca7
45cd9df
 
2981fab
45cd9df
2f9aca7
45cd9df
deef0c2
2f9aca7
deef0c2
 
 
 
 
 
0f8176d
deef0c2
 
 
 
 
0f8176d
deef0c2
45cd9df
deef0c2
0f8176d
 
 
 
45cd9df
 
2981fab
 
deef0c2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
const { 
    default: makeWASocket, 
    DisconnectReason, 
    useMultiFileAuthState,
    fetchLatestBaileysVersion 
} = require('@whiskeysockets/baileys');
const QRCode = require('qrcode-terminal');
const qrcode = require('qrcode');
const axios = require('axios');
const crypto = require('crypto');  // TAMBAHIN INI
const fs = require('fs');
const express = require('express');
const pino = require('pino');

const app = express();
const PORT = process.env.PORT || 7860;
const HF_TOKEN = process.env.HF_TOKEN || 'hf_LMbsGCSfszThllrjJzi';

let sock = null;
let qrCodeData = null;
let pairingCode = null;
let status = 'connecting';

// Web UI
app.get('/', async (req, res) => {
    // Kalau connected
    if (status === 'connected') {
        res.send(`<h1>βœ… Bot Connected!</h1><p>Siap menerima pesan WhatsApp</p>`);
        return;
    }
    
    // Kalau ada pairing code
    if (pairingCode) {
        res.send(`
            <div style="text-align:center;font-family:Arial;padding:20px;">
                <h1>πŸ”’ Pairing Code</h1>
                <div style="font-size:3em;letter-spacing:10px;background:#333;color:#0f0;padding:20px;border-radius:10px;margin:20px 0;">
                    ${pairingCode}
                </div>
                <p>Cara pakai:</p>
                <ol style="text-align:left;display:inline-block;">
                    <li>Buka WhatsApp</li>
                    <li>Menu β†’ Linked Devices</li>
                    <li>Link with phone number</li>
                    <li>Masukin kode di atas</li>
                </ol>
                <p>Atau tunggu QR code di bawah...</p>
                <script>setTimeout(()=>location.reload(),5000)</script>
            </div>
        `);
        return;
    }
    
    // Kalau ada QR
    if (qrCodeData) {
        const qr = await qrcode.toDataURL(qrCodeData);
        res.send(`
            <div style="text-align:center;font-family:Arial;padding:20px;">
                <h1>πŸ“· Scan QR Code</h1>
                <img src="${qr}" width="300" style="margin:20px 0;">
                <p>WhatsApp β†’ Menu β†’ Linked Devices β†’ Scan</p>
                <script>setTimeout(()=>location.reload(),5000)</script>
            </div>
        `);
        return;
    }
    
    // Loading
    res.send(`
        <div style="text-align:center;font-family:Arial;padding:20px;">
            <h1>⏳ Status: ${status}</h1>
            <p>Menyiapkan koneksi...</p>
            <p>Refresh dalam 5 detik</p>
            <script>setTimeout(()=>location.reload(),3000)</script>
        </div>
    `);
});

app.listen(PORT, () => console.log(`🌐 Web: http://localhost:${PORT}`));

// Bot
async function startBot() {
    console.log('πŸš€ Starting bot...');
    
    const { state, saveCreds } = await useMultiFileAuthState('./auth');
    const { version } = await fetchLatestBaileysVersion();

    sock = makeWASocket({
        version,
        logger: pino({ level: 'silent' }),
        printQRInTerminal: true,
        auth: state,
        browser: ['Ubuntu', 'Chrome', '20.0.04'],
    });

    // Pairing code (dengan error handling)
    if (!state.creds.registered) {
        setTimeout(async () => {
            try {
                // Coba pairing code
                const code = await sock.requestPairingCode('6282117207534'); // GANTI NOMOR!
                pairingCode = code;
                console.log('\nπŸ”’ PAIRING CODE:', code);
                console.log('πŸ‘‰ Masukin ke WhatsApp β†’ Linked Devices β†’ Link with phone number\n');
            } catch (e) {
                console.log('⚠️ Pairing code gagal, pake QR aja');
                console.log('πŸ‘‰ Tunggu QR code muncul...\n');
                // QR akan muncul otomatis di event connection.update
            }
        }, 3000);
    }

    sock.ev.on('connection.update', async (update) => {
        const { connection, lastDisconnect, qr } = update;
        
        if (qr) {
            qrCodeData = qr;
            status = 'qr_ready';
            console.log('\nπŸ”₯ QR CODE READY');
            console.log('πŸ‘‰ Scan pakai WhatsApp\n');
            QRCode.generate(qr, { small: true });
        }

        if (connection === 'open') {
            status = 'connected';
            qrCodeData = null;
            pairingCode = null;
            console.log('\nβœ… CONNECTED!');
            console.log('πŸ“± Bot siap dipake\n');
            
            try {
                await sock.sendMessage(sock.user.id, { 
                    text: 'πŸ€– *Bot Aktif!*\n\nKetik !help untuk bantuan' 
                });
            } catch (e) {}
        }
        else if (connection === 'close') {
            const statusCode = lastDisconnect?.error?.output?.statusCode;
            const shouldReconnect = statusCode !== DisconnectReason.loggedOut;
            
            console.log('\n❌ Disconnected:', statusCode);
            status = 'disconnected';
            qrCodeData = null;
            pairingCode = null;
            
            if (shouldReconnect) {
                console.log('πŸ”„ Reconnecting in 5s...\n');
                setTimeout(startBot, 5000);
            }
        }
    });

    sock.ev.on('creds.update', saveCreds);

    sock.ev.on('messages.upsert', async ({ messages, type }) => {
        if (type !== 'notify') return;
        const msg = messages[0];
        if (!msg.message || msg.key.fromMe) return;

        const sender = msg.key.remoteJid;
        const text = msg.message.conversation || msg.message.extendedTextMessage?.text || '';

        if (!text.startsWith('!')) return;

        const cmd = text.slice(1).split(' ')[0].toLowerCase();
        const args = text.slice(1).split(' ').slice(1).join(' ');

        if (cmd === 'ai' && args) {
            await sock.sendMessage(sender, { text: '⏳ AI mikir...' });
            try {
                const res = await axios.post(
                    '/static-proxy?url=https%3A%2F%2Fapi-inference.huggingface.co%2Fmodels%2Fmistralai%2FMistral-7B-Instruct-v0.2%26%23x27%3B%3C%2Fspan%3E%2C
                    { inputs: `<s>[INST] ${args} [/INST]`, parameters: { max_new_tokens: 500 } },
                    { headers: { 'Authorization': `Bearer ${HF_TOKEN}` }, timeout: 30000 }
                );
                let reply = res.data[0]?.generated_text || 'Gagal';
                reply = reply.replace(/<s>\[INST\].*?\[\/INST\]\s*/, '');
                await sock.sendMessage(sender, { text: reply.substring(0, 1000) });
            } catch (e) {
                await sock.sendMessage(sender, { text: '❌ AI sibuk, coba lagi' });
            }
        }
        else if (cmd === 'help') {
            await sock.sendMessage(sender, { text: '!ai [tanya] - Tanya AI\n!status - Cek status' });
        }
        else if (cmd === 'status') {
            await sock.sendMessage(sender, { text: `Status: ${status}` });
        }
    });
}

startBot();