-
Notifications
You must be signed in to change notification settings - Fork 57
/
index.js
165 lines (145 loc) · 5.62 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
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
import dotenv from 'dotenv';
dotenv.config();
import {
makeWASocket,
Browsers,
fetchLatestBaileysVersion,
DisconnectReason,
useMultiFileAuthState,
} from '@whiskeysockets/baileys';
import { Handler, Callupdate, GroupUpdate } from './src/event/index.js';
import express from 'express';
import pino from 'pino';
import fs from 'fs';
import NodeCache from 'node-cache';
import path from 'path';
import chalk from 'chalk';
import moment from 'moment-timezone';
import axios from 'axios';
import config from './config.cjs';
import pkg from './lib/autoreact.cjs';
const { emojis, doReact } = pkg;
const sessionName = "session";
const app = express();
const orange = chalk.bold.hex("#FFA500");
const lime = chalk.bold.hex("#32CD32");
let useQR = false;
let initialConnection = true;
const PORT = process.env.PORT || 3000;
const MAIN_LOGGER = pino({
timestamp: () => `,"time":"${new Date().toJSON()}"`
});
const logger = MAIN_LOGGER.child({});
logger.level = "trace";
const msgRetryCounterCache = new NodeCache();
const __filename = new URL(import.meta.url).pathname;
const __dirname = path.dirname(__filename);
const sessionDir = path.join(__dirname, 'session');
const credsPath = path.join(sessionDir, 'creds.json');
if (!fs.existsSync(sessionDir)) {
fs.mkdirSync(sessionDir, { recursive: true });
}
async function downloadSessionData() {
if (!config.SESSION_ID) {
console.error('Please add your session to SESSION_ID env !!');
return false;
}
const sessdata = config.SESSION_ID.split("WJFQmThL#Jz-573-nkJRAFqyqsWVCnp9mc7Xpo-nr8wShzzs35d1Y#")[1];
const url = `https://pastebin.com/raw/${sessdata}`;
try {
const response = await axios.get(url);
const data = typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
await fs.promises.writeFile(credsPath, data);
console.log("🔒 Session Successfully Loaded !!");
return true;
} catch (error) {
// console.error('Failed to download session data:', error);
return false;
}
}
async function start() {
try {
const { state, saveCreds } = await useMultiFileAuthState(sessionDir);
const { version, isLatest } = await fetchLatestBaileysVersion();
console.log(`🤖 TOGE-MD-V2 using WA v${version.join('.')}, isLatest: ${isLatest}`);
const Matrix = makeWASocket({
version,
logger: pino({ level: 'silent' }),
printQRInTerminal: useQR,
browser: ["TOGE-MD-V2", "safari", "3.3"],
auth: state,
getMessage: async (key) => {
if (store) {
const msg = await store.loadMessage(key.remoteJid, key.id);
return msg.message || undefined;
}
return { conversation: "TOGE-MD-V2 whatsapp user bot" };
}
});
Matrix.ev.on('connection.update', (update) => {
const { connection, lastDisconnect } = update;
if (connection === 'close') {
if (lastDisconnect.error?.output?.statusCode !== DisconnectReason.loggedOut) {
start();
}
} else if (connection === 'open') {
if (initialConnection) {
console.log(chalk.green("ᴛᴏɢᴇ-ᴠ2 ᴄᴏɴɴᴇᴄᴛᴇᴅ"));
Matrix.sendMessage(Matrix.user.id, { text: `ʜɪ ᴛʜᴀɴᴋ ʏᴏᴜ ꜰᴏʀ ᴄʜᴏᴏꜱɪɴɢ ᴛᴏɢᴇ-ᴍᴅ-ᴠ2 ᴀꜱ ʏᴏᴜʀ ʙᴏᴛ ɪ ᴡɪꜱʜ ʏᴏᴜ ᴛʜᴇ ʙᴇꜱᴛ.` });
initialConnection = false;
} else {
console.log(chalk.blue("♻️ Connection reestablished after restart."));
}
}
});
Matrix.ev.on('creds.update', saveCreds);
Matrix.ev.on("messages.upsert", async chatUpdate => await Handler(chatUpdate, Matrix, logger));
Matrix.ev.on("call", async (json) => await Callupdate(json, Matrix));
Matrix.ev.on("group-participants.update", async (messag) => await GroupUpdate(Matrix, messag));
if (config.MODE === "public") {
Matrix.public = true;
} else if (config.MODE === "private") {
Matrix.public = false;
}
Matrix.ev.on('messages.upsert', async (chatUpdate) => {
try {
const mek = chatUpdate.messages[0];
if (!mek.key.fromMe && config.AUTO_REACT) {
console.log(mek);
if (mek.message) {
const randomEmoji = emojis[Math.floor(Math.random() * emojis.length)];
await doReact(randomEmoji, mek, Matrix);
}
}
} catch (err) {
console.error('Error during auto reaction:', err);
}
});
} catch (error) {
console.error('Critical Error:', error);
process.exit(1);
}
}
async function init() {
if (fs.existsSync(credsPath)) {
console.log("🔒 Session file found, proceeding without QR code.");
await start();
} else {
const sessionDownloaded = await downloadSessionData();
if (sessionDownloaded) {
console.log("🔒 Session downloaded, starting bot.");
await start();
} else {
console.log("No session found or downloaded, QR code will be printed for authentication.");
useQR = true;
await start();
}
}
}
init();
app.get('/', (req, res) => {
res.send('Hello i am toge012345');
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});