-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
224 lines (192 loc) · 7.78 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
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
import { Boom } from '@hapi/boom'
import Baileys, {
DisconnectReason,
delay,
Browsers,
useMultiFileAuthState
} from '@whiskeysockets/baileys'
import cors from 'cors'
import express from 'express'
import fs from 'fs'
import { readFile } from 'fs/promises'
import { Pastebin, PrivacyLevel, ExpirationTime } from "pastedeno";
import path, { dirname } from 'path'
import pino from 'pino'
import { fileURLToPath } from 'url'
const app = express()
app.use((req, res, next) => {
res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate')
res.setHeader('Pragma', 'no-cache')
res.setHeader('Expires', '0')
next()
})
app.use(cors())
const pastebin = new Pastebin({
api_dev_key: "06S06TKqc-rMUHoHsrYxA_bwWp9Oo12y",
});
let PORT = process.env.PORT || 8000
const __filename = fileURLToPath(
import.meta.url)
const __dirname = dirname(__filename)
function createRandomId() {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
let id = ''
for (let i = 0; i < 10; i++) {
id += characters.charAt(Math.floor(Math.random() * characters.length))
}
return id
}
let sessionFolder = `./auth/${createRandomId()}`
if (fs.existsSync(sessionFolder)) {
try {
fs.rmdirSync(sessionFolder, { recursive: true })
console.log('Deleted the "SESSION" folder.')
} catch (err) {
console.error('Error deleting the "SESSION" folder:', err)
}
}
let clearState = () => {
fs.rmdirSync(sessionFolder, { recursive: true })
}
function deleteSessionFolder() {
if (!fs.existsSync(sessionFolder)) {
console.log('The "SESSION" folder does not exist.')
return
}
try {
fs.rmdirSync(sessionFolder, { recursive: true })
console.log('Deleted the "SESSION" folder.')
} catch (err) {
console.error('Error deleting the "SESSION" folder:', err)
}
}
app.get('/', async(req, res) => {
res.sendFile(path.join(__dirname, 'index.html'))
})
app.get('/qr', async(req, res) => {
res.sendFile(path.join(__dirname, 'qr.html'))
})
app.get('/code', async(req, res) => {
res.sendFile(path.join(__dirname, 'pair.html'))
})
app.get('/pair', async(req, res) => {
let phone = req.query.phone
if (!phone) return res.json({ error: 'Please Provide Phone Number' })
try {
const code = await startnigg(phone)
res.json({ code: code })
} catch (error) {
console.error('Error in WhatsApp authentication:', error)
res.status(500).json({ error: 'Internal Server Error' })
}
})
async function startnigg(phone) {
const authDir = path.join(__dirname, 'auth');
if (!fs.existsSync(authDir)) {
fs.mkdirSync(authDir);
}
return new Promise(async(resolve, reject) => {
try {
if (!fs.existsSync(sessionFolder)) {
await fs.mkdirSync(sessionFolder)
}
const { state, saveCreds } = await useMultiFileAuthState(sessionFolder)
const negga = Baileys.makeWASocket({
version: [2, 3000, 1015901307],
printQRInTerminal: false,
logger: pino({
level: 'silent',
}),
browser: Browsers.ubuntu("Chrome"),
auth: state,
})
if (!negga.authState.creds.registered) {
let phoneNumber = phone ? phone.replace(/[^0-9]/g, '') : ''
if (phoneNumber.length < 11) {
return reject(new Error('Please Enter Your Number With Country Code !!'))
}
setTimeout(async() => {
try {
let code = await negga.requestPairingCode(phoneNumber)
console.log(`Your Pairing Code : ${code}`)
resolve(code)
} catch (requestPairingCodeError) {
const errorMessage = 'Error requesting pairing code from WhatsApp'
console.error(errorMessage, requestPairingCodeError)
return reject(new Error(errorMessage))
}
}, 3000)
}
negga.ev.on('creds.update', saveCreds)
negga.ev.on('connection.update', async update => {
const { connection, lastDisconnect } = update
if (connection === 'open') {
await delay(10000)
let data1 = await readFile(`${sessionFolder}/creds.json`)
const output = await pastebin.createPaste({
text: data1.toString(),
title: "Tracertech",
format: "javascript",
privacy: PrivacyLevel.UNLISTED,
expiration: ExpirationTime.ONE_MONTH
});
const sessi = 'Session~' + output.split('https://pastebin.com/')[1]
console.log(sessi)
await delay(2000)
let guru = await negga.sendMessage(negga.user.id, { text: sessi })
await delay(2000)
await negga.sendMessage(
negga.user.id, {
text: '\nsᴇssɪᴏɴ sᴄᴀɴ sᴜᴄᴄᴇss\n',
}, { quoted: guru }
)
console.log('Connected to WhatsApp Servers')
try {
deleteSessionFolder()
} catch (error) {
console.error('Error deleting session folder:', error)
}
process.send('reset')
}
if (connection === 'close') {
let reason = new Boom(lastDisconnect ? .error) ? .output.statusCode
console.log('Connection Closed:', reason)
if (reason === DisconnectReason.connectionClosed) {
console.log('[Connection closed, reconnecting....!]')
process.send('reset')
} else if (reason === DisconnectReason.connectionLost) {
console.log('[Connection Lost from Server, reconnecting....!]')
process.send('reset')
} else if (reason === DisconnectReason.loggedOut) {
clearState()
console.log('[Device Logged Out, Please Try to Login Again....!]')
process.send('reset')
} else if (reason === DisconnectReason.restartRequired) {
console.log('[Server Restarting....!]')
startnigg()
} else if (reason === DisconnectReason.timedOut) {
console.log('[Connection Timed Out, Trying to Reconnect....!]')
process.send('reset')
} else if (reason === DisconnectReason.badSession) {
console.log('[BadSession exists, Trying to Reconnect....!]')
clearState()
process.send('reset')
} else if (reason === DisconnectReason.connectionReplaced) {
console.log(`[Connection Replaced, Trying to Reconnect....!]`)
process.send('reset')
} else {
console.log('[Server Disconnected: Maybe Your WhatsApp Account got Fucked....!]')
process.send('reset')
}
}
})
negga.ev.on('messages.upsert', () => {})
} catch (error) {
console.error('An Error Occurred:', error)
throw new Error('An Error Occurred')
}
})
}
app.listen(PORT, () => {
console.log(`API Running on PORT:${PORT}`)
})