Skip to content

Commit

Permalink
add support web api
Browse files Browse the repository at this point in the history
  • Loading branch information
Kry9toN committed Jan 24, 2021
1 parent b435748 commit 0a27fe3
Show file tree
Hide file tree
Showing 7 changed files with 281 additions and 7 deletions.
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,16 @@
"chalk": "^4.1.0",
"child_process": "^1.0.2",
"discord.js": "^12.5.1",
"ejs": "^3.1.5",
"express": "^4.17.1",
"fluent-ffmpeg": "^2.1.2",
"moment-timezone": "^0.5.32",
"node-fetch": "^2.6.1",
"node-os-utils": "^1.3.2",
"pg": "^8.5.1",
"release-it": "^14.2.2",
"remove.bg": "^1.3.0",
"socket.io": "^3.1.0",
"source-map-loader": "^2.0.0",
"spinnies": "^0.5.1",
"typescript": "^4.1.3",
Expand Down
6 changes: 3 additions & 3 deletions src/command/id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ module.exports = {
execute (client, chat, pesan) {
const uid = client.sender
if (client.isGroup) {
const gid = client.groupId
client.reply(`*ID* kamu : ${uid}\nGroup *ID* : ${gid}`)
const gid = client.groupId
client.reply(`*ID* kamu : ${uid}\nGroup *ID* : ${gid}`)
} else {
client.reply(`*ID* kamu : ${uid}`)
client.reply(`*ID* kamu : ${uid}`)
}
}
}
14 changes: 10 additions & 4 deletions src/krypton.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export {}
const {
WAConnection, MessageType
} = require('@adiwajshing/baileys')
Expand All @@ -11,8 +12,14 @@ const moment = require('moment-timezone')
const { welcome, goodbye } = require('./utils/greeting')
const time = moment.tz('Asia/Jakarta').format('DD/MM HH:mm:ss')
const { databaseView, databaseInput } = require('./utils/db')
const { web } = require('./utils/web')

async function krypton () {
const client = new WAConnection()
client.cmd = new Collection()
client.runtimeDb = new Collection()
const cooldowns = new Collection()

/***
* Initial Database
**/
Expand Down Expand Up @@ -43,10 +50,6 @@ async function krypton () {
databaseInput('CREATE TABLE IF NOT EXISTS afks( uid VARCHAR(30) PRIMARY KEY NOT NULL, afk VARCHAR(10) NOT NULL, reason CHAR(225) NOT NULL, timestart VARCHAR(100) NOT NULL )')
.catch(err => console.log(err))

const client = new WAConnection()
client.cmd = new Collection()
client.runtimeDb = new Collection()
const cooldowns = new Collection()
client.logger.level = 'warn'
await client.on('qr', () => {
console.log(color('[', 'white'), color('!', 'red'), color(']', 'white'), color(' Scan the QR code above'))
Expand Down Expand Up @@ -77,6 +80,9 @@ async function krypton () {
await client.connect({ timeoutMs: 30 * 1000 })
fs.writeFileSync('./sessions/krypton-sessions.json', JSON.stringify(client.base64EncodedAuthInfo(), null, '\t'))

// Web api proses
web(client)

await client.on('group-participants-update', async (greeting) => {
try {
const num = greeting.participants[0]
Expand Down
68 changes: 68 additions & 0 deletions src/utils/web.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
export {}
// REQUIRE NPM PACKAGES
const {
MessageType
} = require('@adiwajshing/baileys')
const http = require('http')
const express = require('express')
const app = express()
const httpServer = http.createServer(app)
const osUtils = require('node-os-utils')
const os = require('os')
const io = require('socket.io')(httpServer)
const { color } = require('./color')

const web = async (client) => {
const apiKey = process.env.WEB_API
// View Engine and static public folder
app.set('view engine', 'ejs')
app.use(express.static('./views'))

// Root Route
app.get('/', (req, res) => {
res.render('index.ejs')
})

app.get('/send/:id/:text/:api', (req, res) => {
const { id, text, api } = req.params
if (api !== apiKey) return res.json({ info: 'Api Key salah', status: 502 })
client.sendMessage(id, text, MessageType.text)
.then(() => {
res.json({ info: 'Berhasil mengirim', status: 200 })
}).catch((err) => res.json({ info: 'Gagal mengirim', status: 502 }))
})

// CPU USAGE
const cpu = osUtils.cpu

// USER and OS
const username = os.userInfo([{ encoding: 'buffer' }]).username
const osInfo = os.type()

// SOCKET IO
io.on('connection', socket => {
console.log(color(`[INFO] ${socket.id} Server socket connected`, 'green'))
// USE SET INTERVAL TO CHECK RAM USAGE EVERY SECOND
setInterval(async () => {
// RAM USED tot - free
const ramUsed = Math.round(os.totalmem()) - Math.round(os.freemem())
// RAM percentage
const ram = (ramUsed * 100 / Math.round(os.totalmem())).toFixed(0)
// Uptime and Chat
const chat = await client.chats.all().length
const uptime = Math.round(process.uptime()).toFixed(0)
// CPU USAGE PERCENTAGE
cpu.usage().then(cpu => socket.emit('ram-usage', { ram, cpu, username, osInfo, chat, uptime }))
}, 1000)
})

// Run the server
const PORT = 3000
httpServer.listen(PORT, () => {
console.log(color('[INFO] Web api Server on port: ', 'green') + color(`${PORT}`, 'yellow'))
})
}

module.exports = {
web
}
82 changes: 82 additions & 0 deletions views/css/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
@import url('https://fonts.googleapis.com/css2?family=Oswald&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

body {
font-family: 'Oswald', sans-serif;
color: #808080;
}

h1 {
font-size: 4rem;
padding: 10px;
margin: 10px auto;
}

.content {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
}

.uptime-label,
.bot,
.server,
.chat,
.user,
.os {
font-size: 1.1rem;
height: 30px;
}

label {
margin: 5px auto;
}
.innerBar-ram,
.innerBar-cpu {
background: linear-gradient(to right, #3fffa2 0%, #ffdb3a 50%, #e5405e 100%);
height: 24px;
width: 0%;
}
.outerContainer-ram,
.outerContainer-cpu {
width: 400px;
height: 24px;
border-radius: 5px;
overflow: hidden;
background: lightgray;
}

footer {
position: fixed;
bottom: 10px;
text-align: center;
padding: 10px;
left: 50%;
transform: translate(-50%);
}

.home {
text-decoration: none;
position: sticky;
top: 10px;
left: 50%;
transform: translate(-50%);
}

.home .home-svg {
width: 20px;
display: inline-block;
}

@media (max-width: 768px) {
h1 {
font-size: 3rem;
}
}
44 changes: 44 additions & 0 deletions views/index.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Monitoring Bot</title>
<link rel="stylesheet" href="./css/style.css">
<link rel="icon" type="image/svg" href="./imgs/resources.svg">
</head>

<body>
<a href="/catalog" class="home"><img class="home-svg" src="./imgs/home.svg" alt=""></a>
<div class="content">
<h1>KryPtoN Bot Resources</h1>
<div class="user">Hello</div>
<label class="server">Server</label>
<div class="os">OS Type</div>
<!-- CPU -->
<label class="cpu-label" for="cpu">CPU 0%</label>
<div class="outerContainer-cpu">
<div class="innerBar-cpu"></div>
</div>
<!-- RAM -->
<label class="ram-label" for="ram">RAM 0%</label>
<div class="outerContainer-ram">
<div class="innerBar-ram"></div>
</div>
<label class="bot">BOT</label>
<!-- CHAT -->
<div class="chat">Total CHAT</div>
<!-- ULTIME -->
<label class="uptime-label">Uptime</label>
<div class="uptime"></div>
</div>

<footer>KryPtoN 😎 ©2021</footer>
<!-- SOCKET IO -->
<script src="/socket.io/socket.io.js" defer></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="./js/main.js" defer></script>
</body>

</html>
70 changes: 70 additions & 0 deletions views/js/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// SOCKET IO
const socket = io();
// SELECT ELEMENTS
const labelRam = document.querySelector('.ram-label');
const labelCpu = document.querySelector('.cpu-label');
const user = document.querySelector('.user');
const os = document.querySelector('.os');
const chatTotal = document.querySelector('.chat');
const onTime = document.querySelector('.uptime');

// ON CONNECT EVENT
socket.on('connect', () => {
console.log('Connected');
});
// ON RAM USAGE EVENT
socket.on('ram-usage', ({ ram, cpu, username, osInfo, chat, uptime }) => {
// SHOW OS USER INFO
user.innerHTML = `<span>Hello ${username}</span>`;
os.innerHTML = `<span>OS type: ${osInfo === 'Windows_NT' ? 'Microsoft Windows' : osInfo}</span>`
// Set ram label
labelRam.innerHTML = `<span>RAM ${ram} % </span>`;
// Set Ram bar
$('.innerBar-ram').animate({ width: `${ram}%` }, 2000);
// Set cpu label
labelCpu.innerHTML = `<span>CPU ${cpu} % </span>`;
// Set cpu bar
$('.innerBar-cpu').animate({ width: `${cpu}%` }, 2000);
// Check
if (cpu > 90) {
notify(cpu)
}
chatTotal.innerHTML = `<span>Total CHAT: ${chat}</span>`

function botUpTime(seconds){
function pad(s){
return (s < 10 ? '0' : '') + s;
}
var hours = Math.floor(seconds / (60*60));
var minutes = Math.floor(seconds % (60*60) / 60);
var seconds = Math.floor(seconds % 60);

//return pad(hours) + ':' + pad(minutes) + ':' + pad(seconds)
return onTime.innerHTML = `<span>${pad(hours)}Jam ${pad(minutes)}Menit ${pad(seconds)}Detik</span>`
}

botUpTime(uptime)

});

// NOTIFICATION FUNCTION
let notify = (info) => {
// If granted
if (Notification.permission === 'granted') {
new Notification('Title', {
body: `CPU over ${info} %`
});
}
// If denied
if (Notification.permission !== 'denied') {
Notification.requestPermission()
.then((permission) => {
if (permission === 'granted') {
new Notification('Title', {
body: `CPU over ${info} %`
});
};
});
};

};

0 comments on commit 0a27fe3

Please sign in to comment.