This repository was archived by the owner on May 1, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathconnection.js
More file actions
227 lines (180 loc) · 5.44 KB
/
Copy pathconnection.js
File metadata and controls
227 lines (180 loc) · 5.44 KB
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
/**
* Script de
* inicialização do bot.
*
* Este script é
* responsável por
* iniciar a conexão
* com o WhatsApp.
*
* Não é recomendado alterar
* este arquivo,
* a menos que você saiba
* o que está fazendo.
*
* @author Dev Gui
*/
const {
default: makeWASocket,
DisconnectReason,
useMultiFileAuthState,
fetchLatestBaileysVersion,
isJidBroadcast,
isJidStatusBroadcast,
proto,
makeInMemoryStore,
isJidNewsletter,
delay,
} = require("baileys");
const pino = require("pino");
const { BAILEYS_CREDS_DIR } = require("./config");
const { runLite } = require("./index");
const { onlyNumbers } = require("./utils/functions");
const {
textInput,
infoLog,
warningLog,
errorLog,
successLog,
tutorLog,
bannerLog,
} = require("./utils/terminal");
const { welcome } = require("./welcome");
const store = makeInMemoryStore({
logger: pino().child({ level: "silent", stream: "store" }),
});
bannerLog();
async function startConnection() {
const { state, saveCreds } = await useMultiFileAuthState(BAILEYS_CREDS_DIR);
const { version } = await fetchLatestBaileysVersion();
const socket = makeWASocket({
version,
browser: ["Safari", "MacOS", "15.0"],
logger: pino({ level: "error" }),
printQRInTerminal: false,
defaultQueryTimeoutMs: 60 * 1000,
auth: state,
shouldIgnoreJid: (jid) =>
isJidBroadcast(jid) || isJidStatusBroadcast(jid) || isJidNewsletter(jid),
keepAliveIntervalMs: 60 * 1000,
markOnlineOnConnect: true,
shouldSyncHistoryMessage: () => false,
getMessage: async (key) => {
if (!store) {
return proto.Message.fromObject({});
}
const msg = await store.loadMessage(key.remoteJid, key.id);
return msg ? msg.message : undefined;
},
});
if (!socket.authState.creds.registered) {
warningLog("Credenciais ainda não configuradas!");
let enableTutor = "s";
do {
if (!["s", "n"].includes(enableTutor)) {
errorLog("Opção inválida! Tente novamente.");
}
enableTutor = await textInput(
"Deseja ativar o tutor com explicações detalhadas para instalação no termux? (s/n): "
);
} while (!["s", "n"].includes(enableTutor));
infoLog(
'Informe o número do Bot assim como está no WhatsApp, somente números (exemplo: "5511920202020")'
);
const phoneNumber = await textInput("Informe o seu número de telefone: ");
if (!phoneNumber) {
errorLog(
'Número de telefone inválido! Tente novamente com o comando "yarn start" ou "npm start".'
);
process.exit(1);
}
if (enableTutor === "s") {
await delay(1000);
tutorLog("Estamos gerando seu código... lembre-se:\n");
await delay(5000);
tutorLog(
`1. Depois que colar o código no WhatsApp, aguarde 10 segundos e depois pare o bot com CTRL + C.
⌛ Gerando código, aguarde.. 25% concluído.\n`
);
await delay(10_000);
tutorLog(
`2. Depois de parar o bot,
abra o MT Manager ou ZArchiver na pasta:
📁 lite-bot
Abra o arquivo config.js e configure:
- Seu prefixo ( o padrão é: / )
- Número do bot
- Número do dono do bot
⌛ Gerando código, aguarde... 50% concluído.\n`,
"cyan"
);
await delay(10_000);
tutorLog(
`3. Depois, abra o termux e digite:
cd /sdcard/lite-bot
⌛ Gerando código, aguarde... 75% concluído.\n`
);
await delay(10_000);
tutorLog(
`4. Por último, inicie o bot com:
yarn start
ou
npm start
✅ Geração concluída! Enviando código...\n`,
"green"
);
await delay(5_000);
}
const code = await socket.requestPairingCode(onlyNumbers(phoneNumber));
infoLog(`Código de pareamento: ${code}`);
}
socket.ev.on("connection.update", async (update) => {
const { connection, lastDisconnect } = update;
if (connection === "close") {
const statusCode =
lastDisconnect.error?.output?.statusCode !== DisconnectReason.loggedOut;
if (statusCode === DisconnectReason.loggedOut) {
errorLog("Bot desconectado!");
} else {
switch (statusCode) {
case DisconnectReason.badSession:
warningLog("Sessão inválida!");
break;
case DisconnectReason.connectionClosed:
warningLog("Conexão fechada!");
break;
case DisconnectReason.connectionLost:
warningLog("Conexão perdida!");
break;
case DisconnectReason.connectionReplaced:
warningLog("Conexão substituída!");
break;
case DisconnectReason.multideviceMismatch:
warningLog("Dispositivo incompatível!");
break;
case DisconnectReason.forbidden:
warningLog("Conexão proibida!");
break;
case DisconnectReason.restartRequired:
infoLog('Me reinicie por favor! Digite "yarn start".');
break;
case DisconnectReason.unavailableService:
warningLog("Serviço indisponível!");
break;
}
startConnection();
}
} else if (connection === "open") {
successLog("Fui conectado com sucesso!");
}
});
socket.ev.on("creds.update", saveCreds);
socket.ev.on("messages.upsert", (data) => {
runLite({ socket, data });
});
socket.ev.on("group-participants.update", (data) => {
welcome({ socket, data });
});
return socket;
}
startConnection();