-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
5 changed files
with
2,145 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
# Express-pairing-code | ||
Baileys Session Gen Using Express | ||
|
||
|
||
session.guruapi.tech is using this repo , so don't disturb me by asking if i use any other repo for session | ||
|
||
 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
import * as baileys from 'baileys'; | ||
import fs from 'fs-extra'; | ||
import pino from 'pino'; | ||
import cors from 'cors'; | ||
import express from 'express'; | ||
import { Boom } from '@hapi/boom'; | ||
import { dirname, join } from 'path'; | ||
import { fileURLToPath } from 'url'; | ||
|
||
const app = express(); | ||
|
||
app.set('json spaces', 2); | ||
|
||
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()); | ||
|
||
let PORT = process.env.PORT || 8000; | ||
let message = ` | ||
\`\`\` | ||
Xstro Multi Device Pairing Success | ||
Use the Accesskey Above for Xstro Bot | ||
Please Don't Share to UnAuthorized Users | ||
I won't ask you for your Session | ||
\`\`\` | ||
`; | ||
const __filename = fileURLToPath(import.meta.url); | ||
const __dirname = dirname(__filename); | ||
|
||
app.use(express.static(join(__dirname, 'client', 'build'))); | ||
|
||
let sessionFolder = `auth`; | ||
if (fs.existsSync(sessionFolder)) { | ||
try { | ||
fs.removeSync(sessionFolder); | ||
} catch (err) {} | ||
} | ||
|
||
let clearState = () => { | ||
fs.removeSync(sessionFolder); | ||
}; | ||
|
||
const uploadFolder = join(__dirname, 'upload'); | ||
if (!fs.existsSync(uploadFolder)) fs.mkdirSync(uploadFolder); | ||
|
||
function generateAccessKey() { | ||
const formatNumber = num => num.toString().padStart(2, '0'); | ||
|
||
const r1 = formatNumber(Math.floor(Math.random() * 100)); | ||
const r2 = formatNumber(Math.floor(Math.random() * 100)); | ||
const r3 = formatNumber(Math.floor(Math.random() * 100)); | ||
|
||
return `XSTRO_${r1}_${r2}_${r3}`; | ||
} | ||
|
||
app.get('/pair', async (req, res) => { | ||
let phone = req.query.phone; | ||
if (!phone) return res.json({ error: 'Provide Valid Phone Number' }); | ||
const code = await getPairingCode(phone); | ||
res.json({ code: code }); | ||
}); | ||
|
||
app.get('/session/:key', async (req, res) => { | ||
const accessKey = req.params.key; | ||
const folderPath = join(uploadFolder, accessKey); | ||
|
||
if (!fs.existsSync(folderPath)) return res.status(404).json({ error: 'Folder not found' }); | ||
|
||
const files = await Promise.all( | ||
( | ||
await fs.readdir(folderPath) | ||
).map(async file => { | ||
return { | ||
name: file, | ||
url: `${req.protocol}://${req.get('host')}/uploads/${accessKey}/${file}`, | ||
}; | ||
}), | ||
); | ||
|
||
res.json({ | ||
accessKey: accessKey, | ||
files: files, | ||
}); | ||
}); | ||
|
||
async function getPairingCode(phone) { | ||
return new Promise(async (resolve, reject) => { | ||
try { | ||
if (!fs.existsSync(sessionFolder)) fs.mkdirSync(sessionFolder); | ||
|
||
const { state, saveCreds } = await baileys.useMultiFileAuthState(sessionFolder); | ||
const { version } = await baileys.fetchLatestBaileysVersion(); | ||
|
||
const conn = baileys.makeWASocket({ | ||
version: version, | ||
printQRInTerminal: false, | ||
logger: pino({ | ||
level: 'silent', | ||
}), | ||
browser: baileys.Browsers.macOS('Safari'), | ||
auth: state, | ||
}); | ||
|
||
if (!conn.authState.creds.registered) { | ||
let phoneNumber = phone ? phone.replace(/[^0-9]/g, '') : ''; | ||
if (phoneNumber.length < 11) return reject(new Error('Enter Valid Phone Number')); | ||
|
||
setTimeout(async () => { | ||
let code = await conn.requestPairingCode(phoneNumber); | ||
resolve(code); | ||
}, 3000); | ||
} | ||
|
||
conn.ev.on('creds.update', saveCreds); | ||
|
||
conn.ev.on('connection.update', async update => { | ||
const { connection, lastDisconnect } = update; | ||
|
||
if (connection === 'open') { | ||
await baileys.delay(10000); | ||
const accessKey = generateAccessKey(); | ||
const newSessionPath = join(uploadFolder, accessKey); | ||
const msg = await conn.sendMessage(conn.user.id, { text: accessKey }); | ||
await conn.sendMessage(conn.user.id, { text: message }, { quoted: msg }); | ||
await baileys.delay(2000); | ||
try { | ||
await fs.remove(newSessionPath); | ||
await fs.move(sessionFolder, newSessionPath, { | ||
overwrite: true, | ||
force: true, | ||
}); | ||
process.send('reset'); | ||
} catch (error) {} | ||
} | ||
|
||
if (connection === 'close') { | ||
const reason = new Boom(lastDisconnect?.error)?.output.statusCode; | ||
const resetReasons = [baileys.DisconnectReason.connectionClosed, baileys.DisconnectReason.connectionLost, baileys.DisconnectReason.timedOut, baileys.DisconnectReason.connectionReplaced]; | ||
const resetWithClearStateReasons = [baileys.DisconnectReason.loggedOut, baileys.DisconnectReason.badSession]; | ||
if (resetReasons.includes(reason)) { | ||
process.send('reset'); | ||
} else if (resetWithClearStateReasons.includes(reason)) { | ||
clearState(); | ||
process.send('reset'); | ||
} else if (reason === baileys.DisconnectReason.restartRequired) { | ||
getPairingCode(); | ||
} else { | ||
process.send('reset'); | ||
} | ||
} | ||
}); | ||
|
||
conn.ev.on('messages.upsert', () => {}); | ||
} catch (error) { | ||
throw new Error('An Error Occurred'); | ||
} | ||
}); | ||
} | ||
|
||
app.listen(PORT, () => { | ||
console.log('PORT:\nhttp://localhost:' + PORT + ''); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
{ | ||
"name": "baileys-pair", | ||
"version": "1.0.0", | ||
"description": "baileys session", | ||
"main": "server.js", | ||
"type": "module", | ||
"engines": { | ||
"node": "20.18.1" | ||
}, | ||
"scripts": { | ||
"start": "node server.js" | ||
}, | ||
"author": "AstroX11", | ||
"license": "MIT", | ||
"dependencies": { | ||
"baileys": "6.7.9", | ||
"cfonts": "^3.2.0", | ||
"chalk": "^5.3.0", | ||
"cluster": "^0.7.7", | ||
"cors": "^2.8.5", | ||
"dotenv": "^16.4.5", | ||
"express": "^4.18.2", | ||
"fs-extra": "^11.2.0", | ||
"path": "^0.12.7", | ||
"pino": "^8.15.1", | ||
"yargs": "^17.6.0" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,77 @@ | ||
console.log('Server Started...'); | ||
|
||
import { join, dirname } from 'path'; | ||
import { fileURLToPath } from 'url'; | ||
import { setupMaster, fork } from 'cluster'; | ||
import { watchFile, unwatchFile } from 'fs'; | ||
import cfonts from 'cfonts'; | ||
import { createInterface } from 'readline'; | ||
import yargs from 'yargs'; | ||
|
||
const __dirname = dirname(fileURLToPath(import.meta.url)); | ||
const { say } = cfonts; | ||
const rl = createInterface(process.stdin, process.stdout); | ||
|
||
say('Negga', { | ||
font: 'pallet', | ||
align: 'center', | ||
gradient: ['red', 'magenta'], | ||
}); | ||
say(`pair`, { | ||
font: 'console', | ||
align: 'center', | ||
gradient: ['cyan', 'magenta'], | ||
}); | ||
|
||
var isRunning = false; | ||
/** | ||
* Start a js file | ||
* @param {String} file | ||
*/ | ||
function start(file) { | ||
if (isRunning) return; | ||
isRunning = true; | ||
let args = [join(__dirname, file), ...process.argv.slice(2)]; | ||
say([process.argv[0], ...args].join(' '), { | ||
font: 'console', | ||
align: 'center', | ||
gradient: ['red', 'magenta'], | ||
}); | ||
setupMaster({ | ||
exec: args[0], | ||
args: args.slice(1), | ||
}); | ||
let p = fork(); | ||
p.on('message', data => { | ||
console.log('[RECEIVED]', data); | ||
switch (data) { | ||
case 'reset': | ||
p.process.kill(); | ||
isRunning = false; | ||
start.apply(this, arguments); | ||
break; | ||
case 'uptime': | ||
p.send(process.uptime()); | ||
break; | ||
} | ||
}); | ||
|
||
p.on('exit', (_, code) => { | ||
isRunning = false; | ||
console.error('An Error occured:', code); | ||
if (code === 0) return; | ||
watchFile(args[0], () => { | ||
unwatchFile(args[0]); | ||
start(file); | ||
}); | ||
}); | ||
|
||
let opts = new Object(yargs(process.argv.slice(2)).exitProcess(false).parse()); | ||
if (!opts['test']) | ||
if (!rl.listenerCount()) | ||
rl.on('line', line => { | ||
p.emit('message', line.trim()); | ||
}); | ||
} | ||
|
||
start('index.js'); |
Oops, something went wrong.