-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
138 lines (114 loc) · 5.03 KB
/
index.js
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
// index.js
require('dotenv').config();
const { default: makeWASocket, DisconnectReason, useMultiFileAuthState, downloadContentFromMessage } = require('baileys');
const { Boom } = require('@hapi/boom');
const { GoogleGenerativeAI } = require('@google/generative-ai');
const qrcode = require('qrcode-terminal');
const fs = require('fs').promises;
const { logInfo, logSuccess, logWarning, logError } = require('./logger');
// Initialize Gemini AI with API key from .env
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
// Initialize chat history
let chatHistory = [];
async function connectToWhatsApp() {
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys');
const sock = makeWASocket({
auth: state,
printQRInTerminal: true
});
sock.ev.on('connection.update', (update) => {
const { connection, lastDisconnect } = update;
if (connection === 'close') {
const shouldReconnect = (lastDisconnect.error instanceof Boom &&
lastDisconnect.error.output.statusCode !== DisconnectReason.loggedOut);
logWarning('Connection closed due to ' + lastDisconnect.error);
logInfo('Reconnecting: ' + (shouldReconnect ? 'Yes' : 'No'));
if (shouldReconnect) {
// Retry the connection after a short delay
setTimeout(() => {
connectToWhatsApp();
}, 5000);
} else {
logError('Connection closed due to unknown error: ' + lastDisconnect.error);
}
} else if (connection === 'error') {
logError('Connection error: ' + update.error);
}
});
sock.ev.on('creds.update', saveCreds);
sock.ev.on('messages.upsert', async ({ messages }) => {
const m = messages[0];
if (!m.message) return;
let messageContent = '';
let hasImage = false;
let imageBuffer = null;
// Check for text in various message types
if (m.message.conversation) {
messageContent = m.message.conversation;
} else if (m.message.extendedTextMessage) {
messageContent = m.message.extendedTextMessage.text;
} else if (m.message.imageMessage) {
messageContent = m.message.imageMessage.caption || '';
hasImage = true;
}
logInfo('Message received: ' + messageContent);
// Process message even if it doesn't start with '!' when there's an image
if (messageContent.startsWith('!') || hasImage) {
const command = messageContent.startsWith('!') ? messageContent.slice(1).trim().toLowerCase() : messageContent.trim().toLowerCase();
if (command === 'reset') {
chatHistory = [];
await sock.sendMessage(m.key.remoteJid, { text: 'Chat history has been reset.' });
return;
}
try {
logInfo('Processing query: ' + command);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
if (hasImage) {
imageBuffer = await downloadImage(m.message.imageMessage);
logInfo('Image downloaded successfully');
}
let result;
if (imageBuffer) {
const imagePart = {
inlineData: {
data: imageBuffer.toString('base64'),
mimeType: 'image/jpeg'
}
};
result = await model.generateContent([imagePart, { text: command }]);
} else {
result = await model.generateContent([...chatHistory, { text: command }]);
}
const response = result.response;
const text = response.text();
// Update chat history
chatHistory.push({ text: command });
chatHistory.push({ text: text });
// Keep only the last 10 messages in the history
if (chatHistory.length > 10) {
chatHistory = chatHistory.slice(-10);
}
logSuccess('Generated response: ' + text);
await sock.sendMessage(m.key.remoteJid, { text });
} catch (error) {
logError('Error generating response: ' + error);
await sock.sendMessage(m.key.remoteJid, { text: 'Sorry, I encountered an error while processing your request.' });
}
}
});
}
async function downloadImage(imageMessage) {
try {
const stream = await downloadContentFromMessage(imageMessage, 'image');
let buffer = Buffer.from([]);
for await (const chunk of stream) {
buffer = Buffer.concat([buffer, chunk]);
}
logInfo('Image downloaded, size: ' + buffer.length + ' bytes');
return buffer;
} catch (error) {
logError('Error downloading image: ' + error);
return null;
}
}
connectToWhatsApp();