From 0b139e3db822e2d298d4a0d9b25c263f9c4b1a42 Mon Sep 17 00:00:00 2001 From: Kry9toN Date: Sat, 23 Jan 2021 13:22:12 +0700 Subject: [PATCH] migrate to typescript --- .gitignore | 1 + package.json | 27 +- command/add.js => src/command/add.ts | 44 +- .../clearall.js => src/command/clearall.ts | 28 +- command/demote.js => src/command/demote.ts | 46 +- .../fakereply.js => src/command/fakereply.ts | 3 +- command/gmium.js => src/command/gmium.ts | 11 +- command/help.js => src/command/help.ts | 40 +- command/hidetag.js => src/command/hidetag.ts | 40 +- command/kick.js => src/command/kick.ts | 46 +- command/notes.js => src/command/notes.ts | 1 + command/nulis.js => src/command/nulis.ts | 37 +- command/nulis2.js => src/command/nulis2.ts | 33 +- command/ping.js => src/command/ping.ts | 25 +- command/promote.js => src/command/promote.ts | 46 +- command/slap.js => src/command/slap.ts | 48 +- command/sticker.js => src/command/sticker.ts | 23 +- krypton.js => src/krypton.ts | 480 +++++++++--------- utils/color.js => src/utils/color.ts | 29 +- utils/db.js => src/utils/db.ts | 1 + utils/fetcher.js => src/utils/fetcher.ts | 16 +- utils/functions.js => src/utils/functions.ts | 195 +++---- utils/greeting.js => src/utils/greeting.ts | 1 + start.js | 10 + tsconfig.json | 16 + 25 files changed, 652 insertions(+), 595 deletions(-) rename command/add.js => src/command/add.ts (81%) rename command/clearall.js => src/command/clearall.ts (76%) rename command/demote.js => src/command/demote.ts (87%) rename command/fakereply.js => src/command/fakereply.ts (87%) rename command/gmium.js => src/command/gmium.ts (89%) rename command/help.js => src/command/help.ts (97%) rename command/hidetag.js => src/command/hidetag.ts (97%) rename command/kick.js => src/command/kick.ts (86%) rename command/notes.js => src/command/notes.ts (99%) rename command/nulis.js => src/command/nulis.ts (97%) rename command/nulis2.js => src/command/nulis2.ts (97%) rename command/ping.js => src/command/ping.ts (97%) rename command/promote.js => src/command/promote.ts (87%) rename command/slap.js => src/command/slap.ts (92%) rename command/sticker.js => src/command/sticker.ts (89%) rename krypton.js => src/krypton.ts (98%) rename utils/color.js => src/utils/color.ts (95%) rename utils/db.js => src/utils/db.ts (98%) rename utils/fetcher.js => src/utils/fetcher.ts (80%) rename utils/functions.js => src/utils/functions.ts (87%) rename utils/greeting.js => src/utils/greeting.ts (99%) create mode 100644 start.js create mode 100644 tsconfig.json diff --git a/.gitignore b/.gitignore index a1b0581..e4fc59d 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,4 @@ lib/instaStory.js lib/jiwa.js package-lock.json .env +dist \ No newline at end of file diff --git a/package.json b/package.json index 0556ae2..82307d1 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,8 @@ "description": "KryPtoN Whatsapp Bot", "main": "krypton.js", "scripts": { - "start": "node krypton.js", + "start": "node start", + "compile": "tsc --build tsconfig.json", "changelog": "auto-changelog -p && git add CHANGELOG.md", "release": "read -p 'GITHUB_TOKEN: ' GITHUB_TOKEN && export GITHUB_TOKEN=$GITHUB_TOKEN && release-it" }, @@ -25,6 +26,9 @@ "release": true } }, + "eslintConfig": { + "ignorePatterns": "build/*/**" + }, "auto-changelog": { "commitLimit": false }, @@ -35,23 +39,28 @@ "license": "SEE LICENSE IN LICENSE.md", "dependencies": { "@adiwajshing/baileys": "^3.4.1", - "spinnies": "^0.5.1", - "chalk": "^4.1.0", - "discord.js": "^12.5.1", "auto-changelog": "^2.2.1", - "moment-timezone": "^0.5.32", "axios": "^0.21.1", - "wa-canvas": "git+https://github.com/Kry9toN/wa-canvas.git", - "release-it": "^14.2.2", "cfonts": "^2.9.1", + "chalk": "^4.1.0", + "child_process": "^1.0.2", + "discord.js": "^12.5.1", + "fluent-ffmpeg": "^2.1.2", + "moment-timezone": "^0.5.32", "node-fetch": "^2.6.1", "pg": "^8.5.1", - "child_process": "^1.0.2", - "fluent-ffmpeg": "^2.1.2" + "release-it": "^14.2.2", + "remove.bg": "^1.3.0", + "source-map-loader": "^2.0.0", + "spinnies": "^0.5.1", + "typescript": "^4.1.3", + "wa-canvas": "git+https://github.com/Kry9toN/wa-canvas.git" }, "devDependencies": { "babel-eslint": "^10.1.0", "eslint": "^7.14.0", + "ts-loader": "^8.0.14", + "ts-node": "^9.1.1", "eslint-config-standard": "^16.0.2", "eslint-plugin-import": "^2.22.1", "eslint-plugin-node": "^11.1.0", diff --git a/command/add.js b/src/command/add.ts similarity index 81% rename from command/add.js rename to src/command/add.ts index 02870f2..1501463 100644 --- a/command/add.js +++ b/src/command/add.ts @@ -1,22 +1,22 @@ -const { color } = require('../utils/color') - -module.exports = { - name: 'add', - aliases: ['ad'], - description: 'Untuk menambahkan orang ke group dengan nomor\nPenggunaan: !add 6285xxxx', - // eslint-disable-next-line no-shadow-restricted-names - execute (client, undefined, pesan, args) { - if (!client.isGroup) return client.reply(pesan.error.group) - if (!client.isGroupAdmins) return client.reply(pesan.hanya.admin) - if (!client.isBotGroupAdmins) return client.reply(pesan.hanya.botAdmin) - if (args.length < 1) return client.reply('Siapa yang mau lu add ?, demit ?') - if (args[0].startsWith('08')) return client.reply('Jaman sudah canggih!!, masa masih pakai 0 awalannya') - try { - num = `${args[0].replace(/ /g, '')}@s.whatsapp.net` - client.groupAdd(client.from, [num]) - } catch (e) { - console.log('Error : %s', color(e, 'red')) - client.reply('Gagal menambahkan target, mungkin karena di private') - } - } -} +export {} +const { color } = require('../utils/color') + +module.exports = { + name: 'add', + aliases: ['ad'], + description: 'Untuk menambahkan orang ke group dengan nomor\nPenggunaan: !add 6285xxxx', + execute (client: any, chat: any, pesan: any, args:any) { + if (!client.isGroup) return client.reply(pesan.error.group) + if (!client.isGroupAdmins) return client.reply(pesan.hanya.admin) + if (!client.isBotGroupAdmins) return client.reply(pesan.hanya.botAdmin) + if (args.length < 1) return client.reply('Siapa yang mau lu add ?, demit ?') + if (args[0].startsWith('08')) return client.reply('Jaman sudah canggih!!, masa masih pakai 0 awalannya') + try { + const num = `${args[0].replace(/ /g, '')}@s.whatsapp.net` + client.groupAdd(client.from, [num]) + } catch (e) { + console.log('Error : %s', color(e, 'red')) + client.reply('Gagal menambahkan target, mungkin karena di private') + } + } +} diff --git a/command/clearall.js b/src/command/clearall.ts similarity index 76% rename from command/clearall.js rename to src/command/clearall.ts index 35b20ec..08bf39c 100644 --- a/command/clearall.js +++ b/src/command/clearall.ts @@ -1,14 +1,14 @@ -module.exports = { - name: 'clearall', - aliases: ['ca'], - description: 'Untuk benghapus semua chat _only owner_', - execute (client, chat, pesan) { - if (!isOwner) return reply('Kamu siapa?') - chatAll = client.chats.all() - client.setMaxListeners(25) - for (const chat of chatAll) { - client.deleteChat(chat.jid) - } - client.reply('Berhasil menghapus semua chat') - } -} +module.exports = { + name: 'clearall', + aliases: ['ca'], + description: 'Untuk benghapus semua chat _only owner_', + execute (client, chat, pesan) { + if (!client.isOwner) return client.reply('Kamu siapa?') + const chatAll = client.chats.all() + client.setMaxListeners(25) + for (const chat of chatAll) { + client.deleteChat(chat.jid) + } + client.reply('Berhasil menghapus semua chat') + } +} diff --git a/command/demote.js b/src/command/demote.ts similarity index 87% rename from command/demote.js rename to src/command/demote.ts index c59a0bb..249a56e 100644 --- a/command/demote.js +++ b/src/command/demote.ts @@ -1,23 +1,23 @@ -module.exports = { - name: 'demote', - aliases: ['dm'], - description: 'Untuk manghapus admin anggota group\nPenggunaan: !demote _tag_', - execute (client, chat, pesan) { - if (!client.isGroup) return client.reply(pesan.error.group) - if (!client.isGroupAdmins) return client.reply(pesan.hanya.admin) - if (!client.isBotGroupAdmins) return client.reply(pesan.hanya.botAdmin) - if (chat.message.extendedTextMessage === undefined || chat.message.extendedTextMessage === null) return client.reply('Tag target yang ingin di demote!') - mentioned = chat.message.extendedTextMessage.contextInfo.mentionedJid - if (mentioned.length > 1) { - teks = 'Perintah di terima, demote :\n' - for (const _ of mentioned) { - teks += `@${_.split('@')[0]}\n` - } - client.mentions(teks, mentioned, true) - client.groupDemoteAdmin(client.from, mentioned) - } else { - client.mentions(`Perintah di terima, menghapus admin : @${mentioned[0].split('@')[0]} di group`, mentioned, true) - client.groupDemoteAdmin(client.from, mentioned) - } - } -} +module.exports = { + name: 'demote', + aliases: ['dm'], + description: 'Untuk manghapus admin anggota group\nPenggunaan: !demote _tag_', + execute (client, chat, pesan) { + if (!client.isGroup) return client.reply(pesan.error.group) + if (!client.isGroupAdmins) return client.reply(pesan.hanya.admin) + if (!client.isBotGroupAdmins) return client.reply(pesan.hanya.botAdmin) + if (chat.message.extendedTextMessage === undefined || chat.message.extendedTextMessage === null) return client.reply('Tag target yang ingin di demote!') + const mentioned = chat.message.extendedTextMessage.contextInfo.mentionedJid + if (mentioned.length > 1) { + let teks = 'Perintah di terima, demote :\n' + for (const _ of mentioned) { + teks += `@${_.split('@')[0]}\n` + } + client.mentions(teks, mentioned, true) + client.groupDemoteAdmin(client.from, mentioned) + } else { + client.mentions(`Perintah di terima, menghapus admin : @${mentioned[0].split('@')[0]} di group`, mentioned, true) + client.groupDemoteAdmin(client.from, mentioned) + } + } +} diff --git a/command/fakereply.js b/src/command/fakereply.ts similarity index 87% rename from command/fakereply.js rename to src/command/fakereply.ts index 97c791c..ee53105 100644 --- a/command/fakereply.js +++ b/src/command/fakereply.ts @@ -1,3 +1,4 @@ +export {} const { MessageType } = require('@adiwajshing/baileys') module.exports = { @@ -9,7 +10,7 @@ module.exports = { const arg = client.body.slice(9) const targets = arg.split('|')[1] const bot = arg.split('|')[2] - mentioned = chat.message.extendedTextMessage.contextInfo.mentionedJid + const mentioned = chat.message.extendedTextMessage.contextInfo.mentionedJid client.sendMessage(client.from, `${bot}`, MessageType.text, { quoted: { key: { fromMe: false, participant: `${mentioned}`, ...(client.from ? { remoteJid: client.from } : {}) }, message: { conversation: `${targets}` } } }) } } diff --git a/command/gmium.js b/src/command/gmium.ts similarity index 89% rename from command/gmium.js rename to src/command/gmium.ts index 11b2e49..ae9e2d3 100644 --- a/command/gmium.js +++ b/src/command/gmium.ts @@ -1,3 +1,4 @@ +export {} const { databaseView, databaseInput } = require('../utils/db') module.exports = { @@ -8,10 +9,10 @@ module.exports = { if (!client.isOwner && !client.isSudo) return client.reply(pesan.hanya.owner) const gid = args[2] if (args[0] === 'add') { + const mentioned = chat.message.extendedTextMessage.contextInfo.mentionedJid + const sign = mentioned[0] if (args[1] === 'unlimited') { if (chat.message.extendedTextMessage === undefined || chat.message.extendedTextMessage === null) return client.reply('Tag yang bersangkutan!') - mentioned = chat.message.extendedTextMessage.contextInfo.mentionedJid - const sign = mentioned[0] databaseInput(`INSERT INTO gmium(gid, lifetime, signature) VALUES('${gid}', 'unlimited', '${sign}')`) .then(() => { client.reply(pesan.berhasil) @@ -40,15 +41,17 @@ module.exports = { await databaseView('SELECT * FROM gmium') .then((result) => { let text = '📝 Daftar *Premium* di bot ini\n' + const mentioned = [] if (result.length > 0) { for (let i = 0; i < result.length; i++) { const gid = result[i].gid const waktu = result[i].waktu - const sign = result[i].signature.replace('@s.whatsapp.net', '') + const sign = result[i].signature + mentioned.push(sign) const life = result[i].lifetime text += `${i}. *GID*: ${gid}\n` text += ` ├> *Lifetime*: ${life}\n` - text += ` ├> *Bersangkutan*: @${sign}\n` + text += ` ├> *Bersangkutan*: @${sign.replace('@s.whatsapp.net', '')}\n` text += ` └> *Mulai*: ${waktu}\n` } client.mentions(`${text}`, mentioned, true) diff --git a/command/help.js b/src/command/help.ts similarity index 97% rename from command/help.js rename to src/command/help.ts index 49fe74a..35cb223 100644 --- a/command/help.js +++ b/src/command/help.ts @@ -1,20 +1,20 @@ -module.exports = { - name: 'help', - aliases: ['h'], - description: 'Menampilkan semua perintah dan deskripsi', - execute (client, chat, pesan, args) { - const commands = client.cmd.array() - if (args.length == 0) { - let text = 'Daftar perintah di bot ini\n\nPrefix: !\n' - commands.forEach((cmd) => { - text += `- *${cmd.name}* ${cmd.aliases ? `(${cmd.aliases})` : ''}\n` - }) - text += '\nMasih bingung? ketik *!help * akan menampilkan penggunaan perintah tersebut' - return client.reply(text) - } else { - if (!client.cmd.has(args[0])) return client.reply('Perintah yang anda maksut tidak ada bro') - const text = client.cmd.get(args[0]).description - return client.reply(text) - } - } -} +module.exports = { + name: 'help', + aliases: ['h'], + description: 'Menampilkan semua perintah dan deskripsi', + execute (client, chat, pesan, args) { + const commands = client.cmd.array() + if (args.length == 0) { + let text = 'Daftar perintah di bot ini\n\nPrefix: !\n' + commands.forEach((cmd) => { + text += `- *${cmd.name}* ${cmd.aliases ? `(${cmd.aliases})` : ''}\n` + }) + text += '\nMasih bingung? ketik *!help * akan menampilkan penggunaan perintah tersebut' + return client.reply(text) + } else { + if (!client.cmd.has(args[0])) return client.reply('Perintah yang anda maksut tidak ada bro') + const text = client.cmd.get(args[0]).description + return client.reply(text) + } + } +} diff --git a/command/hidetag.js b/src/command/hidetag.ts similarity index 97% rename from command/hidetag.js rename to src/command/hidetag.ts index 8fbf834..584f4c5 100644 --- a/command/hidetag.js +++ b/src/command/hidetag.ts @@ -1,20 +1,20 @@ -module.exports = { - name: 'hidetag', - aliases: ['ht'], - description: 'Untuk mengetag semua orang tanpa @\nPenggunaan !hidetag _text_', - execute (client, chat, pesan) { - if (!client.isGroup) return client.reply(pesan.error.group) - if (!client.isGroupAdmins) return client.reply(pesan.hanya.admin) - const value = client.body.slice(9) - const memberList = [] - for (const member of client.groupMembers) { - memberList.push(member.jid) - } - const options = { - text: value, - contextInfo: { mentionedJid: memberList }, - quoted: chat - } - client.sendMess(client.from, options) - } -} +module.exports = { + name: 'hidetag', + aliases: ['ht'], + description: 'Untuk mengetag semua orang tanpa @\nPenggunaan !hidetag _text_', + execute (client, chat, pesan) { + if (!client.isGroup) return client.reply(pesan.error.group) + if (!client.isGroupAdmins) return client.reply(pesan.hanya.admin) + const value = client.body.slice(9) + const memberList = [] + for (const member of client.groupMembers) { + memberList.push(member.jid) + } + const options = { + text: value, + contextInfo: { mentionedJid: memberList }, + quoted: chat + } + client.sendMess(client.from, options) + } +} diff --git a/command/kick.js b/src/command/kick.ts similarity index 86% rename from command/kick.js rename to src/command/kick.ts index 6247894..793b7dd 100644 --- a/command/kick.js +++ b/src/command/kick.ts @@ -1,23 +1,23 @@ -module.exports = { - name: 'kick', - aliases: ['k'], - description: 'Untuk mengeluarkan angota di group\nPenggunaan: !kick _tag_', - execute (client, chat, pesan) { - if (!client.isGroup) return client.reply(pesan.error.group) - if (!client.isGroupAdmins) return client.reply(pesan.hanya.admin) - if (!client.isBotGroupAdmins) return client.reply(pesan.hanya.botAdmin) - if (chat.message.extendedTextMessage === undefined || chat.message.extendedTextMessage === null) return client.reply('Tag target yang ingin di tendang!') - mentioned = chat.message.extendedTextMessage.contextInfo.mentionedJid - if (mentioned.length > 1) { - teks = 'Perintah di terima, mengeluarkan :\n' - for (const _ of mentioned) { - teks += `@${_.split('@')[0]}\n` - } - client.mentions(teks, mentioned, true) - client.groupRemove(client.from, mentioned) - } else { - client.mentions(`Perintah di terima, mengeluarkan : @${mentioned[0].split('@')[0]}`, mentioned, true) - client.groupRemove(client.from, mentioned) - } - } -} +module.exports = { + name: 'kick', + aliases: ['k'], + description: 'Untuk mengeluarkan angota di group\nPenggunaan: !kick _tag_', + execute (client, chat, pesan) { + if (!client.isGroup) return client.reply(pesan.error.group) + if (!client.isGroupAdmins) return client.reply(pesan.hanya.admin) + if (!client.isBotGroupAdmins) return client.reply(pesan.hanya.botAdmin) + if (chat.message.extendedTextMessage === undefined || chat.message.extendedTextMessage === null) return client.reply('Tag target yang ingin di tendang!') + const mentioned = chat.message.extendedTextMessage.contextInfo.mentionedJid + if (mentioned.length > 1) { + let teks = 'Perintah di terima, mengeluarkan :\n' + for (const _ of mentioned) { + teks += `@${_.split('@')[0]}\n` + } + client.mentions(teks, mentioned, true) + client.groupRemove(client.from, mentioned) + } else { + client.mentions(`Perintah di terima, mengeluarkan : @${mentioned[0].split('@')[0]}`, mentioned, true) + client.groupRemove(client.from, mentioned) + } + } +} diff --git a/command/notes.js b/src/command/notes.ts similarity index 99% rename from command/notes.js rename to src/command/notes.ts index f7348cd..b23e516 100644 --- a/command/notes.js +++ b/src/command/notes.ts @@ -1,3 +1,4 @@ +export {} const { databaseView, databaseInput } = require('../utils/db') module.exports = { diff --git a/command/nulis.js b/src/command/nulis.ts similarity index 97% rename from command/nulis.js rename to src/command/nulis.ts index ca60a55..41f9f9c 100644 --- a/command/nulis.js +++ b/src/command/nulis.ts @@ -1,18 +1,19 @@ -const { MessageType } = require('@adiwajshing/baileys') -const { getBuffer } = require('../utils/functions') -const { fetchJson } = require('../utils/fetcher') - -module.exports = { - name: 'nulis', - aliases: ['n'], - description: 'Untuk menuliskan di buku bot\nPenggunaan !nulis _tulisan_', - execute (client, chat, pesan, args) { - const value = args.slice().join(' ') - fetchJson(`https://mhankbarbar.tech/nulis?text=${value}&apiKey=${client.apiKey}`, { method: 'get' }) - .then(async (hasil) => { - client.reply(pesan.tunggu) - const buffer = await getBuffer(hasil.result) - client.sendMessage(client.from, buffer, MessageType.image, { quoted: chat, caption: pesan.berhasil }) - }).catch((err) => console.log(err)) - } -} +export {} +const { MessageType } = require('@adiwajshing/baileys') +const { getBuffer } = require('../utils/functions') +const { fetchJson } = require('../utils/fetcher') + +module.exports = { + name: 'nulis', + aliases: ['n'], + description: 'Untuk menuliskan di buku bot\nPenggunaan !nulis _tulisan_', + execute (client, chat, pesan, args) { + const value = args.slice().join(' ') + fetchJson(`https://mhankbarbar.tech/nulis?text=${value}&apiKey=${client.apiKey}`, { method: 'get' }) + .then(async (hasil) => { + client.reply(pesan.tunggu) + const buffer = await getBuffer(hasil.result) + client.sendMessage(client.from, buffer, MessageType.image, { quoted: chat, caption: pesan.berhasil }) + }).catch((err) => console.log(err)) + } +} diff --git a/command/nulis2.js b/src/command/nulis2.ts similarity index 97% rename from command/nulis2.js rename to src/command/nulis2.ts index e726a4c..f382408 100644 --- a/command/nulis2.js +++ b/src/command/nulis2.ts @@ -1,16 +1,17 @@ -const { MessageType } = require('@adiwajshing/baileys') -const { getBuffer } = require('../utils/functions') - -module.exports = { - name: 'nulis2', - aliases: ['n2'], - description: 'Untuk menuliskan di buku bot\nPenggunaan !nulis _tulisan_', - execute (client, chat, pesan, args) { - const value = args.slice().join(' ') - getBuffer(`https://api.zeks.xyz/api/nulis?text=${value}&apikey=administrator`) - .then((hasil) => { - client.reply(pesan.tunggu) - client.sendMessage(client.from, hasil, MessageType.image, { quoted: chat, caption: pesan.berhasil }) - }).catch((err) => console.log(err)) - } -} +export {} +const { MessageType } = require('@adiwajshing/baileys') +const { getBuffer } = require('../utils/functions') + +module.exports = { + name: 'nulis2', + aliases: ['n2'], + description: 'Untuk menuliskan di buku bot\nPenggunaan !nulis _tulisan_', + execute (client, chat, pesan, args) { + const value = args.slice().join(' ') + getBuffer(`https://api.zeks.xyz/api/nulis?text=${value}&apikey=administrator`) + .then((hasil) => { + client.reply(pesan.tunggu) + client.sendMessage(client.from, hasil, MessageType.image, { quoted: chat, caption: pesan.berhasil }) + }).catch((err) => console.log(err)) + } +} diff --git a/command/ping.js b/src/command/ping.ts similarity index 97% rename from command/ping.js rename to src/command/ping.ts index 24007fe..96feb5e 100644 --- a/command/ping.js +++ b/src/command/ping.ts @@ -1,12 +1,13 @@ -const { MessageType } = require('@adiwajshing/baileys') -const moment = require('moment-timezone') -const { processTime } = require('../utils/functions') - -module.exports = { - name: 'ping', - cooldown: 10, - description: 'Menampilkan rata-rata bot merespon', - execute (client) { - client.sendMessage(client.from, `Pong!!\n${processTime(client.pingStart, moment())} _detik_`, MessageType.text).catch(console.error) - } -} +export {} +const { MessageType } = require('@adiwajshing/baileys') +const moment = require('moment-timezone') +const { processTime } = require('../utils/functions') + +module.exports = { + name: 'ping', + cooldown: 10, + description: 'Menampilkan rata-rata bot merespon', + execute (client) { + client.sendMessage(client.from, `Pong!!\n${processTime(client.pingStart, moment())} _detik_`, MessageType.text).catch(console.error) + } +} diff --git a/command/promote.js b/src/command/promote.ts similarity index 87% rename from command/promote.js rename to src/command/promote.ts index 15bc8fa..c9e2ad3 100644 --- a/command/promote.js +++ b/src/command/promote.ts @@ -1,23 +1,23 @@ -module.exports = { - name: 'promote', - aliases: ['pm'], - description: 'Untuk manjadikan admin anggota di group\nPenggunaan: !promote _tag_', - execute (client, chat, pesan) { - if (!client.isGroup) return client.reply(pesan.error.group) - if (!client.isGroupAdmins) return client.reply(pesan.hanya.admin) - if (!client.isBotGroupAdmins) return client.reply(pesan.hanya.botAdmin) - if (chat.message.extendedTextMessage === undefined || chat.message.extendedTextMessage === null) return client.reply('Tag target yang ingin di promote!') - mentioned = chat.message.extendedTextMessage.contextInfo.mentionedJid - if (mentioned.length > 1) { - teks = 'Perintah di terima, promote :\n' - for (const _ of mentioned) { - teks += `@${_.split('@')[0]}\n` - } - client.mentions(teks, mentioned, true) - client.groupMakeAdmin(client.from, mentioned) - } else { - client.mentions(`Perintah di terima, menjadikan admin : @${mentioned[0].split('@')[0]} di group`, mentioned, true) - client.groupMakeAdmin(client.from, mentioned) - } - } -} +module.exports = { + name: 'promote', + aliases: ['pm'], + description: 'Untuk manjadikan admin anggota di group\nPenggunaan: !promote _tag_', + execute (client, chat, pesan) { + if (!client.isGroup) return client.reply(pesan.error.group) + if (!client.isGroupAdmins) return client.reply(pesan.hanya.admin) + if (!client.isBotGroupAdmins) return client.reply(pesan.hanya.botAdmin) + if (chat.message.extendedTextMessage === undefined || chat.message.extendedTextMessage === null) return client.reply('Tag target yang ingin di promote!') + const mentioned = chat.message.extendedTextMessage.contextInfo.mentionedJid + if (mentioned.length > 1) { + let teks = 'Perintah di terima, promote :\n' + for (const _ of mentioned) { + teks += `@${_.split('@')[0]}\n` + } + client.mentions(teks, mentioned, true) + client.groupMakeAdmin(client.from, mentioned) + } else { + client.mentions(`Perintah di terima, menjadikan admin : @${mentioned[0].split('@')[0]} di group`, mentioned, true) + client.groupMakeAdmin(client.from, mentioned) + } + } +} diff --git a/command/slap.js b/src/command/slap.ts similarity index 92% rename from command/slap.js rename to src/command/slap.ts index 003c40a..61c4775 100644 --- a/command/slap.js +++ b/src/command/slap.ts @@ -1,24 +1,24 @@ -module.exports = { - name: 'slap', - description: 'Untuk menampol orang\nPenggunaan !slap _tag_', - execute (client, chat, pesan, args) { - if (!client.isGroup) return client.reply(pesan.error.group) - if (chat.message.extendedTextMessage === undefined || chat.message.extendedTextMessage === null) return client.reply('Tag target yang ingin di tonjok!') - mentioned = chat.message.extendedTextMessage.contextInfo.mentionedJid - const tagList = [] - const dari = client.sender - const target = mentioned[0] - tagList.push(dari, target) - const data = [ - `@${dari.split('@')[0]} melempar *pisang busuk* ke @${target.split('@')[0]}`, - `@${dari.split('@')[0]} bersiap-siap untuk melempar *sekop* ke @${target.split('@')[0]}`, - `@${dari.split('@')[0]} manapar dengan keras @${target.split('@')[0]} dengan *50jt TON truk*`, - `@${dari.split('@')[0]} mulai *memukul* @${target.split('@')[0]} dengan sendok`, - `@${dari.split('@')[0]} menjatuhkan *meteor* ke @${target.split('@')[0]}`, - `@${dari.split('@')[0]} bersiap-siap *me-rasengan* @${target.split('@')[0]}`, - `@${dari.split('@')[0]} menulis nama @${target.split('@')[0]} di *death note*` - ] - const dataslap = data[Math.floor(Math.random() * data.length)] - client.mentions(`${dataslap}`, tagList, true) - } -} +module.exports = { + name: 'slap', + description: 'Untuk menampol orang\nPenggunaan !slap _tag_', + execute (client, chat, pesan, args) { + if (!client.isGroup) return client.reply(pesan.error.group) + if (chat.message.extendedTextMessage === undefined || chat.message.extendedTextMessage === null) return client.reply('Tag target yang ingin di tonjok!') + const mentioned = chat.message.extendedTextMessage.contextInfo.mentionedJid + const tagList = [] + const dari = client.sender + const target = mentioned[0] + tagList.push(dari, target) + const data = [ + `@${dari.split('@')[0]} melempar *pisang busuk* ke @${target.split('@')[0]}`, + `@${dari.split('@')[0]} bersiap-siap untuk melempar *sekop* ke @${target.split('@')[0]}`, + `@${dari.split('@')[0]} manapar dengan keras @${target.split('@')[0]} dengan *50jt TON truk*`, + `@${dari.split('@')[0]} mulai *memukul* @${target.split('@')[0]} dengan sendok`, + `@${dari.split('@')[0]} menjatuhkan *meteor* ke @${target.split('@')[0]}`, + `@${dari.split('@')[0]} bersiap-siap *me-rasengan* @${target.split('@')[0]}`, + `@${dari.split('@')[0]} menulis nama @${target.split('@')[0]} di *death note*` + ] + const dataslap = data[Math.floor(Math.random() * data.length)] + client.mentions(`${dataslap}`, tagList, true) + } +} diff --git a/command/sticker.js b/src/command/sticker.ts similarity index 89% rename from command/sticker.js rename to src/command/sticker.ts index 80c8942..f69c23f 100644 --- a/command/sticker.js +++ b/src/command/sticker.ts @@ -1,9 +1,11 @@ /* eslint-disable no-mixed-operators */ +export {} const { MessageType } = require('@adiwajshing/baileys') const { exec } = require('child_process') const { getRandom } = require('../utils/functions') const ffmpeg = require('fluent-ffmpeg') const fs = require('fs') +const { removeBackgroundclient } = require('remove.bg') module.exports = { name: 'sticker', @@ -11,12 +13,11 @@ module.exports = { cooldown: 600, description: 'Untuk menjadikan video atau gambar menjadi sticker\nPenggunaan: quoted gambar/vidio !sticker rbg: remove background, nobg: no background on sticker, default sticker dengan background', async execute (client, chat, pesan, args) { - const colors = ['red', 'white', 'black', 'blue', 'yellow', 'green'] if ((client.isMedia && !chat.message.videoMessage || client.isQuotedImage) && args[0] == 'nobg') { if (!client.isPmium && !client.isOwner) return client.reply(pesan.error.premium) const encmedia = client.isQuotedImage ? JSON.parse(JSON.stringify(chat).replace('quotedM', 'm')).message.extendedTextMessage.contextInfo : chat const media = await client.downloadAndSaveMediaMessage(encmedia) - ranw = getRandom('.webp') + const ranw = getRandom('.webp') client.reply(pesan.tunggu) await ffmpeg(`./${media}`) .input(media) @@ -41,7 +42,7 @@ module.exports = { if (!client.isPmium && !client.isOwner) return client.reply(pesan.error.premium) const encmedia = client.isQuotedVideo ? JSON.parse(JSON.stringify(chat).replace('quotedM', 'm')).message.extendedTextMessage.contextInfo : chat const media = await client.downloadAndSaveMediaMessage(encmedia) - ranw = getRandom('.webp') + const ranw = getRandom('.webp') client.reply(pesan.tunggu) await ffmpeg(`./${media}`) .inputFormat(media.split('.')[1]) @@ -51,7 +52,7 @@ module.exports = { .on('error', function (err) { console.log(`[SERVER] Error : ${err}`) fs.unlinkSync(media) - tipe = media.endsWith('.mp4') ? 'video' : 'gif' + const tipe = media.endsWith('.mp4') ? 'video' : 'gif' client.reply(`❌ Gagal, pada saat mengkonversi ${tipe} ke stiker`) }) .on('end', function () { @@ -67,13 +68,13 @@ module.exports = { if (!client.isPmium && !client.isOwner) return client.reply(pesan.error.premium) const encmedia = client.isQuotedImage ? JSON.parse(JSON.stringify(chat).replace('quotedM', 'm')).message.extendedTextMessage.contextInfo : chat const media = await client.downloadAndSaveMediaMessage(encmedia) - ranw = getRandom('.webp') - ranp = getRandom('.png') + const ranw = getRandom('.webp') + const ranp = getRandom('.png') client.reply(pesan.tunggu) - keyrmbg = process.env.KEY_REMOVEBG - await removeBackgroundclient.fromImageFile({ path: media, apiKey: keyrmbg.result, size: 'auto', type: 'auto', ranp }).then(res => { + const keyrmbg = process.env.KEY_REMOVEBG + await removeBackgroundclient.fromImageFile({ path: media, apiKey: keyrmbg, size: 'auto', type: 'auto', ranp }).then(res => { fs.unlinkSync(media) - const buffer = Buffer.client.from(res.base64img, 'base64') + const buffer = Buffer.from(res.base64img, 'base64') fs.writeFileSync(ranp, buffer, (err) => { if (err) return client.reply('Gagal, Terjadi kesalahan, silahkan coba beberapa saat lagi.') }) @@ -86,7 +87,7 @@ module.exports = { } else if ((client.isMedia || client.isQuotedImage) && args.length == 0) { const encmedia = client.isQuotedImage ? JSON.parse(JSON.stringify(chat).replace('quotedM', 'm')).message.extendedTextMessage.contextInfo : chat const media = await client.downloadAndSaveMediaMessage(encmedia) - ranw = getRandom('.webp') + const ranw = getRandom('.webp') await ffmpeg(`./${media}`) .on('start', function (cmd) { console.log('[SERVER] Started :', cmd) @@ -101,7 +102,7 @@ module.exports = { fs.unlinkSync(media) fs.unlinkSync(ranw) }) - .addOutputOptions(['-vcodec', 'libwebp', '-vf', `scale='min(320,iw)':min'(320,ih)':force_original_aspect_ratio=decrease,fps=15, pad=320:320:-1:-1:color=white@0.0, split [a][b]; [a] palettegen=reserve_transparent=off [p]; [b][p] paletteuse`]) + .addOutputOptions(['-vcodec', 'libwebp', '-vf', 'scale=\'min(320,iw)\':min\'(320,ih)\':force_original_aspect_ratio=decrease,fps=15, pad=320:320:-1:-1:color=white@0.0, split [a][b]; [a] palettegen=reserve_transparent=off [p]; [b][p] paletteuse']) .toFormat('webp') .save(ranw) } else { diff --git a/krypton.js b/src/krypton.ts similarity index 98% rename from krypton.js rename to src/krypton.ts index b8a1454..899ab5f 100644 --- a/krypton.js +++ b/src/krypton.ts @@ -1,240 +1,240 @@ -const { - WAConnection, MessageType -} = require('@adiwajshing/baileys') -const { Collection } = require('discord.js') -const { readdirSync } = require('fs') -const { join } = require('path') -const { start, success, getGroupAdmins, banner } = require('./utils/functions') -const { color } = require('./utils/color') -const fs = require('fs') -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') - -async function krypton () { - /*** - * Initial Database - **/ - // Black List - databaseInput('CREATE TABLE IF NOT EXISTS blacklist( id VARCHAR(30) PRIMARY KEY NOT NULL , reason CHAR(225) DEFAULT \'No Reason\')') - .catch(err => console.log(err)) - // Filters - databaseInput('CREATE TABLE IF NOT EXISTS filters( gid VARCHAR(50) NOT NULL , key VARCHAR(225) NOT NULL, res VARCHAR(225) NOT NULL )') - .catch(err => console.log(err)) - // Notes - databaseInput('CREATE TABLE IF NOT EXISTS notes( gid VARCHAR(50) NOT NULL , key VARCHAR(225) NOT NULL, res VARCHAR(225) NOT NULL )') - .catch(err => console.log(err)) - // Premium - databaseInput('CREATE TABLE IF NOT EXISTS gmium( gid VARCHAR(50) PRIMARY KEY NOT NULL, lifetime VARCHAR(10) NOT NULL, signature VARCHAR(30) NOT NULL, waktu TIMESTAMP NOT NULL DEFAULT now() )') - .catch(err => console.log(err)) - databaseInput('CREATE TABLE IF NOT EXISTS pmium( gid VARCHAR(50) PRIMARY KEY NOT NULL, waktu TIMESTAMP NOT NULL DEFAULT now() )') - .catch(err => console.log(err)) - // Blacklist text - databaseInput('CREATE TABLE IF NOT EXISTS bllist( gid VARCHAR(50) NOT NULL , text VARCHAR(225) NOT NULL)') - .catch(err => console.log(err)) - // Blacklist user - databaseInput('CREATE TABLE IF NOT EXISTS warn( gid VARCHAR(50) NOT NULL, uid VARCHAR(30) NOT NULL , warn VARCHAR(100) NOT NULL)') - .catch(err => console.log(err)) - // Sudo - databaseInput('CREATE TABLE IF NOT EXISTS sudo( id VARCHAR(30) PRIMARY KEY NOT NULL )') - .catch(err => console.log(err)) - // Sudo - 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' - console.log(banner.string) - await client.on('qr', () => { - console.log(color('[', 'white'), color('!', 'red'), color(']', 'white'), color(' Scan the QR code above')) - }) - - // Connect to sessions if already exist - if (fs.existsSync('./sessions/krypton-sessions.json')) { - await client.loadAuthInfo('./sessions/krypton-sessions.json') - await client.on('connecting', () => { - start('1', '[SERVER] Menyambungkan ke sessions yang sudah ada...') - }) - } - - // Server connecting - if (!fs.existsSync('./sessions/krypton-sessions.json')) { - await client.on('connecting', () => { - start('1', '[SERVER] Menunggu scan code QR untuk menyambungkan...') - }) - } - - // Server connected - await client.on('open', () => { - success('1', '[SERVER] Terhubung') - console.log('🤖', color('KryPtoN Bot Sudah siap!!', 'green')) - }) - - // Create file for sessions - await client.connect({ timeoutMs: 30 * 1000 }) - fs.writeFileSync('./sessions/krypton-sessions.json', JSON.stringify(client.base64EncodedAuthInfo(), null, '\t')) - - await client.on('group-participants-update', async (greeting) => { - try { - const num = greeting.participants[0] - const mdata = await client.groupMetadata(greeting.jid) - const name = client.contacts[num] != undefined ? client.contacts[num].vname || client.contacts[num].notify : undefined - const ppimg = await client.getProfilePicture(`${greeting.participants[0].split('@')[0]}@c.us`) - if (greeting.action == 'add') { - console.log('\x1b[1;31m~\x1b[1;37m>', '[\x1b[1;32mEXEC\x1b[1;37m]', time, 'client', color(greeting.participants[0].split('@')[0]), 'Masuk ke group', color(mdata.subject)) - await welcome(name, mdata.subject, ppimg).then(async (hasil) => { - await client.sendMessage(mdata.id, hasil, MessageType.image) - }) - } else if (greeting.action == 'remove') { - console.log('\x1b[1;31m~\x1b[1;37m>', '[\x1b[1;32mEXEC\x1b[1;37m]', time, 'client', color(greeting.participants[0].split('@')[0]), 'Keluar dari group', color(mdata.subject)) - await goodbye(name, mdata.subject, ppimg).then(async (hasil) => { - await client.sendMessage(mdata.id, hasil, MessageType.image) - }) - } - } catch (e) { - console.log('Error : %s', color(e, 'red')) - } - }) - - await client.on('chat-update', async (chat) => { - client.pingStart = chat.t - client.apiKey = process.env.API_KEY - if (!chat.hasNewMessage) return - const prefix = '!' - chat = JSON.parse(JSON.stringify(chat)).messages[0] - if (!chat.message) return - if (chat.key.remoteJid == 'status@broadcast') return - if (chat.key.fromMe) return - - // Variable - const type = Object.keys(chat.message)[0] - client.body = (type === 'conversation' && chat.message.conversation.startsWith(prefix)) ? chat.message.conversation : (type == 'imageMessage') && chat.message.imageMessage.caption.startsWith(prefix) ? chat.message.imageMessage.caption : (type == 'videoMessage') && chat.message.videoMessage.caption.startsWith(prefix) ? chat.message.videoMessage.caption : (type == 'extendedTextMessage') && chat.message.extendedTextMessage.text.startsWith(prefix) ? chat.message.extendedTextMessage.text : '' - const args = client.body.trim().split(/ +/).slice(1) - const isCmd = client.body.startsWith(prefix) - const commandName = client.body.slice(1).trim().split(/ +/).shift().toLowerCase() - const content = JSON.stringify(chat.message) - const botNumber = client.user.jid - const ownerNumber = process.env.OWNER_PHONE // Isi di .env - client.from = chat.key.remoteJid - client.isGroup = client.from.endsWith('@g.us') - client.sender = client.isGroup ? chat.participant : chat.key.remoteJid - const groupMetadata = client.isGroup ? await client.groupMetadata(client.from) : '' - const groupName = client.isGroup ? groupMetadata.subject : '' - client.groupMembers = client.isGroup ? groupMetadata.participants : '' - const groupAdmins = client.isGroup ? getGroupAdmins(client.groupMembers) : '' - client.groupId = client.isGroup ? groupMetadata.jid : '' - client.isGroup = client.from.endsWith('@g.us') - client.isBotGroupAdmins = groupAdmins.includes(botNumber) || false - client.isGroupAdmins = groupAdmins.includes(client.sender) || false - client.isOwner = client.sender.includes(ownerNumber) - client.isUrl = (url) => { - // eslint-disable-next-line prefer-regex-literals - return url.match(new RegExp(/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)/, 'gi')) - } - client.reply = (teks) => { - client.sendMessage(client.from, teks, MessageType.text, { quoted: chat }) - } - client.sendMess = (id, text) => { - client.sendMessage(id, text, MessageType.text) - } - client.mentions = (teks, id, bolean) => { - (bolean == null || bolean == undefined || bolean == false) ? client.sendMessage(client.from, teks.trim(), MessageType.extendedText, { contextInfo: { mentionedJid: id } }) : client.sendMessage(client.from, teks.trim(), MessageType.extendedText, { quoted: chat, contextInfo: { mentionedJid: id } }) - } - - client.isMedia = (type === 'imageMessage' || type === 'videoMessage') - client.isQuotedImage = type === 'extendedTextMessage' && content.includes('imageMessage') - client.isQuotedVideo = type === 'extendedTextMessage' && content.includes('videoMessage') - client.isQuotedSticker = type === 'extendedTextMessage' && content.includes('stickerMessage') - - // Premuim - const viewPm = await databaseView('SELECT * FROM pmium') - const pmWhiteList = JSON.stringify(viewPm) - client.isPmium = pmWhiteList.includes(client.sender) - - const viewGc = await databaseView('SELECT * FROM gmium') - const gcWhiteList = JSON.stringify(viewGc) - client.isGmium = gcWhiteList.includes(client.groupId) - - const sudo = await databaseView('SELECT * FROM sudo') - const sList = JSON.stringify(sudo) - client.isSudo = sList.includes(client.sender) - - // Logging Message - if (!client.isGroup && isCmd) console.log('\x1b[1;31m~\x1b[1;37m>', '[\x1b[1;32mEXEC\x1b[1;37m]', time, color(commandName), 'client.from', color(client.sender.split('@')[0]), 'args :', color(args.length)) - if (!client.isGroup && !isCmd) console.log('\x1b[1;31m~\x1b[1;37m>', '[\x1b[1;31mRECV\x1b[1;37m]', time, color('Message'), 'client.from', color(client.sender.split('@')[0]), 'args :', color(args.length)) - if (isCmd && client.isGroup) console.log('\x1b[1;31m~\x1b[1;37m>', '[\x1b[1;32mEXEC\x1b[1;37m]', time, color(commandName), 'client.from', color(client.sender.split('@')[0]), 'in', color(groupName), 'args :', color(args.length)) - if (!isCmd && client.isGroup) console.log('\x1b[1;31m~\x1b[1;37m>', '[\x1b[1;31mRECV\x1b[1;37m]', time, color('Message'), 'client.from', color(client.sender.split('@')[0]), 'in', color(groupName), 'args :', color(args.length)) - - pesan = { - tunggu: '⌛ Sedang di Prosess ⌛', - gagal: '❌ Gagal melaksanakan perintah ❌', - berhasil: '✔️ Berhasil ✔️', - hanya: { - admin: '❌ Perintah ini hanya bisa di gunakan oleh admin group! ❌', - botAdmin: '❌ Perintah ini hanya bisa di gunakan ketika bot menjadi admin! ❌', - owner: '❌ Perintah hanya untuk owner/sudo! ❌' - }, - error: { - group: '❌ Perintah ini hanya bisa di gunakan dalam group! ❌', - args: '❌ Perintah anda salah! ❌', - premium: '❌ Perintah hanya untuk pelanggan premium! ❌' - } - } - - /** - * Import all commands - */ - const commandFiles = readdirSync(join(__dirname, 'command')).filter((file) => file.endsWith('.js')) - for (const file of commandFiles) { - const command = require(join(__dirname, 'command', `${file}`)) - client.cmd.set(command.name, command) - } - - if (!isCmd) return - - const command = - client.cmd.get(commandName) || - client.cmd.find((cmd) => cmd.aliases && cmd.aliases.includes(commandName)) - - if (!command) return - - if (!cooldowns.has(command.name)) { - cooldowns.set(command.name, new Collection()) - } - - // Time durations - if (!client.isPmium || !client.isGmium || !client.isOwner) { - const now = Date.now() - const timestamps = cooldowns.get(command.name) - const cooldownAmount = (command.cooldown || 1) * 1000 - - if (timestamps.has(client.from)) { - const expirationTime = timestamps.get(client.from) + cooldownAmount - - if (now < expirationTime) { - const timeLeft = (expirationTime - now) / 1000 - return client.sendMessage(client.from, - `[Slow mode] Mohon tunggu lebih dari ${timeLeft.toFixed(1)} detik sebelum menggunakan perintah *${command.name}* kembali.\n\n Berlangganan lah agar tidak selalu menunggu seperti ini, ketik *!pricing* untuk info harga, dll`, - MessageType.text - ) - } - } - - timestamps.set(client.from, now) - setTimeout(() => timestamps.delete(client.from), cooldownAmount) - } - - try { - command.execute(client, chat, pesan, args) - } catch (e) { - console.log('Error : %s', color(e, 'red')) - client.sendMessage(client.from, 'Telah terjadi error setelah menggunakan command ini.', MessageType.text) - } - }) -} - -krypton().catch((err) => console.log('Error : %s', color(err, 'red'))) +const { + WAConnection, MessageType +} = require('@adiwajshing/baileys') +const { Collection } = require('discord.js') +const { readdirSync } = require('fs') +const { join } = require('path') +const { start, success, getGroupAdmins, banner } = require('./utils/functions') +const { color } = require('./utils/color') +const fs = require('fs') +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') + +async function krypton () { + /*** + * Initial Database + **/ + // Black List + databaseInput('CREATE TABLE IF NOT EXISTS blacklist( id VARCHAR(30) PRIMARY KEY NOT NULL , reason CHAR(225) DEFAULT \'No Reason\')') + .catch(err => console.log(err)) + // Filters + databaseInput('CREATE TABLE IF NOT EXISTS filters( gid VARCHAR(50) NOT NULL , key VARCHAR(225) NOT NULL, res VARCHAR(225) NOT NULL )') + .catch(err => console.log(err)) + // Notes + databaseInput('CREATE TABLE IF NOT EXISTS notes( gid VARCHAR(50) NOT NULL , key VARCHAR(225) NOT NULL, res VARCHAR(225) NOT NULL )') + .catch(err => console.log(err)) + // Premium + databaseInput('CREATE TABLE IF NOT EXISTS gmium( gid VARCHAR(50) PRIMARY KEY NOT NULL, lifetime VARCHAR(10) NOT NULL, signature VARCHAR(30) NOT NULL, waktu TIMESTAMP NOT NULL DEFAULT now() )') + .catch(err => console.log(err)) + databaseInput('CREATE TABLE IF NOT EXISTS pmium( gid VARCHAR(50) PRIMARY KEY NOT NULL, waktu TIMESTAMP NOT NULL DEFAULT now() )') + .catch(err => console.log(err)) + // Blacklist text + databaseInput('CREATE TABLE IF NOT EXISTS bllist( gid VARCHAR(50) NOT NULL , text VARCHAR(225) NOT NULL)') + .catch(err => console.log(err)) + // Blacklist user + databaseInput('CREATE TABLE IF NOT EXISTS warn( gid VARCHAR(50) NOT NULL, uid VARCHAR(30) NOT NULL , warn VARCHAR(100) NOT NULL)') + .catch(err => console.log(err)) + // Sudo + databaseInput('CREATE TABLE IF NOT EXISTS sudo( id VARCHAR(30) PRIMARY KEY NOT NULL )') + .catch(err => console.log(err)) + // Sudo + 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' + console.log(banner.string) + await client.on('qr', () => { + console.log(color('[', 'white'), color('!', 'red'), color(']', 'white'), color(' Scan the QR code above')) + }) + + // Connect to sessions if already exist + if (fs.existsSync('./sessions/krypton-sessions.json')) { + await client.loadAuthInfo('./sessions/krypton-sessions.json') + await client.on('connecting', () => { + start('1', '[SERVER] Menyambungkan ke sessions yang sudah ada...') + }) + } + + // Server connecting + if (!fs.existsSync('./sessions/krypton-sessions.json')) { + await client.on('connecting', () => { + start('1', '[SERVER] Menunggu scan code QR untuk menyambungkan...') + }) + } + + // Server connected + await client.on('open', () => { + success('1', '[SERVER] Terhubung') + console.log('🤖', color('KryPtoN Bot Sudah siap!!', 'green')) + }) + + // Create file for sessions + await client.connect({ timeoutMs: 30 * 1000 }) + fs.writeFileSync('./sessions/krypton-sessions.json', JSON.stringify(client.base64EncodedAuthInfo(), null, '\t')) + + await client.on('group-participants-update', async (greeting) => { + try { + const num = greeting.participants[0] + const mdata = await client.groupMetadata(greeting.jid) + const name = client.contacts[num] != undefined ? client.contacts[num].vname || client.contacts[num].notify : undefined + const ppimg = await client.getProfilePicture(`${greeting.participants[0].split('@')[0]}@c.us`) + if (greeting.action == 'add') { + console.log('\x1b[1;31m~\x1b[1;37m>', '[\x1b[1;32mEXEC\x1b[1;37m]', time, 'client', color(greeting.participants[0].split('@')[0]), 'Masuk ke group', color(mdata.subject)) + await welcome(name, mdata.subject, ppimg).then(async (hasil) => { + await client.sendMessage(mdata.id, hasil, MessageType.image) + }) + } else if (greeting.action == 'remove') { + console.log('\x1b[1;31m~\x1b[1;37m>', '[\x1b[1;32mEXEC\x1b[1;37m]', time, 'client', color(greeting.participants[0].split('@')[0]), 'Keluar dari group', color(mdata.subject)) + await goodbye(name, mdata.subject, ppimg).then(async (hasil) => { + await client.sendMessage(mdata.id, hasil, MessageType.image) + }) + } + } catch (e) { + console.log('Error : %s', color(e, 'red')) + } + }) + + await client.on('chat-update', async (chat) => { + client.pingStart = chat.t + client.apiKey = process.env.API_KEY + if (!chat.hasNewMessage) return + const prefix = '!' + chat = JSON.parse(JSON.stringify(chat)).messages[0] + if (!chat.message) return + if (chat.key.remoteJid == 'status@broadcast') return + if (chat.key.fromMe) return + + // Variable + const type = Object.keys(chat.message)[0] + client.body = (type === 'conversation' && chat.message.conversation.startsWith(prefix)) ? chat.message.conversation : (type == 'imageMessage') && chat.message.imageMessage.caption.startsWith(prefix) ? chat.message.imageMessage.caption : (type == 'videoMessage') && chat.message.videoMessage.caption.startsWith(prefix) ? chat.message.videoMessage.caption : (type == 'extendedTextMessage') && chat.message.extendedTextMessage.text.startsWith(prefix) ? chat.message.extendedTextMessage.text : '' + const args = client.body.trim().split(/ +/).slice(1) + const isCmd = client.body.startsWith(prefix) + const commandName = client.body.slice(1).trim().split(/ +/).shift().toLowerCase() + const content = JSON.stringify(chat.message) + const botNumber = client.user.jid + const ownerNumber = process.env.OWNER_PHONE // Isi di .env + client.from = chat.key.remoteJid + client.isGroup = client.from.endsWith('@g.us') + client.sender = client.isGroup ? chat.participant : chat.key.remoteJid + const groupMetadata = client.isGroup ? await client.groupMetadata(client.from) : '' + const groupName = client.isGroup ? groupMetadata.subject : '' + client.groupMembers = client.isGroup ? groupMetadata.participants : '' + const groupAdmins = client.isGroup ? getGroupAdmins(client.groupMembers) : '' + client.groupId = client.isGroup ? groupMetadata.jid : '' + client.isGroup = client.from.endsWith('@g.us') + client.isBotGroupAdmins = groupAdmins.includes(botNumber) || false + client.isGroupAdmins = groupAdmins.includes(client.sender) || false + client.isOwner = client.sender.includes(ownerNumber) + client.isUrl = (url) => { + // eslint-disable-next-line prefer-regex-literals + return url.match(new RegExp(/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)/, 'gi')) + } + client.reply = (teks) => { + client.sendMessage(client.from, teks, MessageType.text, { quoted: chat }) + } + client.sendMess = (id, text) => { + client.sendMessage(id, text, MessageType.text) + } + client.mentions = (teks, id, bolean) => { + (bolean == null || bolean == undefined || bolean == false) ? client.sendMessage(client.from, teks.trim(), MessageType.extendedText, { contextInfo: { mentionedJid: id } }) : client.sendMessage(client.from, teks.trim(), MessageType.extendedText, { quoted: chat, contextInfo: { mentionedJid: id } }) + } + + client.isMedia = (type === 'imageMessage' || type === 'videoMessage') + client.isQuotedImage = type === 'extendedTextMessage' && content.includes('imageMessage') + client.isQuotedVideo = type === 'extendedTextMessage' && content.includes('videoMessage') + client.isQuotedSticker = type === 'extendedTextMessage' && content.includes('stickerMessage') + + // Premuim + const viewPm = await databaseView('SELECT * FROM pmium') + const pmWhiteList = JSON.stringify(viewPm) + client.isPmium = pmWhiteList.includes(client.sender) + + const viewGc = await databaseView('SELECT * FROM gmium') + const gcWhiteList = JSON.stringify(viewGc) + client.isGmium = gcWhiteList.includes(client.groupId) + + const sudo = await databaseView('SELECT * FROM sudo') + const sList = JSON.stringify(sudo) + client.isSudo = sList.includes(client.sender) + + // Logging Message + if (!client.isGroup && isCmd) console.log('\x1b[1;31m~\x1b[1;37m>', '[\x1b[1;32mEXEC\x1b[1;37m]', time, color(commandName), 'client.from', color(client.sender.split('@')[0]), 'args :', color(args.length)) + if (!client.isGroup && !isCmd) console.log('\x1b[1;31m~\x1b[1;37m>', '[\x1b[1;31mRECV\x1b[1;37m]', time, color('Message'), 'client.from', color(client.sender.split('@')[0]), 'args :', color(args.length)) + if (isCmd && client.isGroup) console.log('\x1b[1;31m~\x1b[1;37m>', '[\x1b[1;32mEXEC\x1b[1;37m]', time, color(commandName), 'client.from', color(client.sender.split('@')[0]), 'in', color(groupName), 'args :', color(args.length)) + if (!isCmd && client.isGroup) console.log('\x1b[1;31m~\x1b[1;37m>', '[\x1b[1;31mRECV\x1b[1;37m]', time, color('Message'), 'client.from', color(client.sender.split('@')[0]), 'in', color(groupName), 'args :', color(args.length)) + + const pesan = { + tunggu: '⌛ Sedang di Prosess ⌛', + gagal: '❌ Gagal melaksanakan perintah ❌', + berhasil: '✔️ Berhasil ✔️', + hanya: { + admin: '❌ Perintah ini hanya bisa di gunakan oleh admin group! ❌', + botAdmin: '❌ Perintah ini hanya bisa di gunakan ketika bot menjadi admin! ❌', + owner: '❌ Perintah hanya untuk owner/sudo! ❌' + }, + error: { + group: '❌ Perintah ini hanya bisa di gunakan dalam group! ❌', + args: '❌ Perintah anda salah! ❌', + premium: '❌ Perintah hanya untuk pelanggan premium! ❌' + } + } + + /** + * Import all commands + */ + const commandFiles = readdirSync(join(__dirname, 'command')).filter((file) => file.endsWith('.js')) + for (const file of commandFiles) { + const command = require(join(__dirname, 'command', `${file}`)) + client.cmd.set(command.name, command) + } + + if (!isCmd) return + + const command = + client.cmd.get(commandName) || + client.cmd.find((cmd) => cmd.aliases && cmd.aliases.includes(commandName)) + + if (!command) return + + if (!cooldowns.has(command.name)) { + cooldowns.set(command.name, new Collection()) + } + + // Time durations + if (!client.isPmium || !client.isGmium || !client.isOwner) { + const now = Date.now() + const timestamps = cooldowns.get(command.name) + const cooldownAmount = (command.cooldown || 1) * 1000 + + if (timestamps.has(client.from)) { + const expirationTime = timestamps.get(client.from) + cooldownAmount + + if (now < expirationTime) { + const timeLeft = (expirationTime - now) / 1000 + return client.sendMessage(client.from, + `[Slow mode] Mohon tunggu lebih dari ${timeLeft.toFixed(1)} detik sebelum menggunakan perintah *${command.name}* kembali.\n\n Berlangganan lah agar tidak selalu menunggu seperti ini, ketik *!pricing* untuk info harga, dll`, + MessageType.text + ) + } + } + + timestamps.set(client.from, now) + setTimeout(() => timestamps.delete(client.from), cooldownAmount) + } + + try { + command.execute(client, chat, pesan, args) + } catch (e) { + console.log('Error : %s', color(e, 'red')) + client.sendMessage(client.from, 'Telah terjadi error setelah menggunakan command ini.', MessageType.text) + } + }) +} + +krypton().catch((err) => console.log('Error : %s', color(err, 'red'))) diff --git a/utils/color.js b/src/utils/color.ts similarity index 95% rename from utils/color.js rename to src/utils/color.ts index 9576bdd..9c796c3 100644 --- a/utils/color.js +++ b/src/utils/color.ts @@ -1,14 +1,15 @@ -const chalk = require('chalk') - -const color = (text, color) => { - return !color ? chalk.green(text) : chalk.keyword(color)(text) -} - -const bgcolor = (text, bgcolor) => { - return !bgcolor ? chalk.green(text) : chalk.bgKeyword(bgcolor)(text) -} - -module.exports = { - color, - bgcolor -} +export {} +const chalk = require('chalk') + +const color = (text, color) => { + return !color ? chalk.green(text) : chalk.keyword(color)(text) +} + +const bgcolor = (text, bgcolor) => { + return !bgcolor ? chalk.green(text) : chalk.bgKeyword(bgcolor)(text) +} + +module.exports = { + color, + bgcolor +} diff --git a/utils/db.js b/src/utils/db.ts similarity index 98% rename from utils/db.js rename to src/utils/db.ts index d8af109..1fcd51e 100644 --- a/utils/db.js +++ b/src/utils/db.ts @@ -1,3 +1,4 @@ +export {} const { Pool } = require('pg') const pool = new Pool({ connectionString: process.env.DATABASE_URL, diff --git a/utils/fetcher.js b/src/utils/fetcher.ts similarity index 80% rename from utils/fetcher.js rename to src/utils/fetcher.ts index f6ccc34..e3f372d 100644 --- a/utils/fetcher.js +++ b/src/utils/fetcher.ts @@ -1,7 +1,8 @@ +export {} const fetch = require('node-fetch') const fs = require('fs') -exports.getBase64 = getBase64 = async (url) => { +const getBase64 = async (url) => { const response = await fetch(url, { headers: { 'User-Agent': 'okhttp/4.5.0' } }) if (!response.ok) throw new Error(`unexpected response ${response.statusText}`) const buffer = await response.buffer() @@ -9,7 +10,7 @@ exports.getBase64 = getBase64 = async (url) => { if (buffer) { return videoBase64 } } -exports.getBuffer = getBuffer = async (url) => { +const getBuffer = async (url) => { const res = await fetch(url, { headers: { 'User-Agent': 'okhttp/4.5.0' }, method: 'GET' }) const anu = fs.readFileSync('./src/emror.jpg') if (!res.ok) return { type: 'image/jpeg', result: anu } @@ -17,7 +18,7 @@ exports.getBuffer = getBuffer = async (url) => { if (buff) { return { type: res.headers.get('content-type'), result: buff } } } -exports.fetchJson = fetchJson = (url, options) => new Promise((resolve, reject) => { +const fetchJson = (url, options) => new Promise((resolve, reject) => { fetch(url, options) .then(response => response.json()) .then(json => { @@ -29,7 +30,7 @@ exports.fetchJson = fetchJson = (url, options) => new Promise((resolve, reject) }) }) -exports.fetchText = fetchText = (url, options) => new Promise((resolve, reject) => { +const fetchText = (url, options) => new Promise((resolve, reject) => { fetch(url, options) .then(response => response.text()) .then(text => { @@ -42,3 +43,10 @@ exports.fetchText = fetchText = (url, options) => new Promise((resolve, reject) }) // exports.getBase64 = getBase64; + +module.exports = { + getBase64, + getBuffer, + fetchJson, + fetchText +} diff --git a/utils/functions.js b/src/utils/functions.ts similarity index 87% rename from utils/functions.js rename to src/utils/functions.ts index 0a7bf9a..b182e4b 100644 --- a/utils/functions.js +++ b/src/utils/functions.ts @@ -1,97 +1,98 @@ -const Spin = require('spinnies') -const moment = require('moment-timezone') -const axios = require('axios') -const cfonts = require('cfonts') - -const spinner = { - interval: 120, - frames: [ - '🕐', - '🕑', - '🕒', - '🕓', - '🕔', - '🕕', - '🕖', - '🕗', - '🕘', - '🕙', - '🕚', - '🕛' - ] -} - -let globalSpinner - -const getGlobalSpinner = (disableSpins = false) => { - if (!globalSpinner) globalSpinner = new Spin({ color: 'blue', succeedColor: 'green', spinner, disableSpins }) - return globalSpinner -} - -spins = getGlobalSpinner(false) - -const start = (id, text) => { - spins.add(id, { text: text }) -} - -const success = (id, text) => { - spins.succeed(id, { text: text }) -} - -/** - * Get Time duration - * @param {Date} timestamp - * @param {Date} now - */ -const processTime = (timestamp, now) => { - // timestamp => timestamp when message was received - return moment.duration(now - moment(timestamp * 1000)).asSeconds() -} - -const getGroupAdmins = (participants) => { - admins = [] - for (const i of participants) { - i.isAdmin ? admins.push(i.jid) : '' - } - return admins -} - -const banner = cfonts.render(('KRYPTON|WHATSAPP|BOT'), { - font: 'block', - colors: ['red', 'blue'], - align: 'center', - lineHeight: 2 -}) - -const getBuffer = async (url, options) => { - try { - options || {} - const res = await axios({ - method: 'get', - url, - headers: { - DNT: 1, - 'Upgrade-Insecure-Request': 1 - }, - ...options, - responseType: 'arraybuffer' - }) - return res.data - } catch (e) { - console.log(`Error : ${e}`) - } -} - -const getRandom = (ext) => { - return `${Math.floor(Math.random() * 10000)}${ext}` -} - -module.exports = { - start, - success, - processTime, - getGroupAdmins, - banner, - getBuffer, - getRandom -} +export {} +let Spin = require('spinnies') +const moment = require('moment-timezone') +const axios = require('axios') +const cfonts = require('cfonts') + +const spinner = { + interval: 120, + frames: [ + '🕐', + '🕑', + '🕒', + '🕓', + '🕔', + '🕕', + '🕖', + '🕗', + '🕘', + '🕙', + '🕚', + '🕛' + ] +} + +let globalSpinner + +const getGlobalSpinner = (disableSpins = false) => { + if (!globalSpinner) globalSpinner = new Spin({ color: 'blue', succeedColor: 'green', spinner, disableSpins }) + return globalSpinner +} + +Spin = getGlobalSpinner(false) + +const start = (id, text) => { + Spin.add(id, { text: text }) +} + +const success = (id, text) => { + Spin.succeed(id, { text: text }) +} + +/** + * Get Time duration + * @param {Date} timestamp + * @param {Date} now + */ +const processTime = (timestamp, now) => { + // timestamp => timestamp when message was received + return moment.duration(now - moment(timestamp * 1000)).asSeconds() +} + +const getGroupAdmins = (participants) => { + const admins = [] + for (const i of participants) { + i.isAdmin ? admins.push(i.jid) : '' + } + return admins +} + +const banner = cfonts.render(('KRYPTON|WHATSAPP|BOT'), { + font: 'block', + colors: ['red', 'blue'], + align: 'center', + lineHeight: 2 +}) + +const getBuffer = async (url, options) => { + try { + options || {} + const res = await axios({ + method: 'get', + url, + headers: { + DNT: 1, + 'Upgrade-Insecure-Request': 1 + }, + ...options, + responseType: 'arraybuffer' + }) + return res.data + } catch (e) { + console.log(`Error : ${e}`) + } +} + +const getRandom = (ext) => { + return `${Math.floor(Math.random() * 10000)}${ext}` +} + +module.exports = { + start, + success, + processTime, + getGroupAdmins, + banner, + getBuffer, + getRandom +} diff --git a/utils/greeting.js b/src/utils/greeting.ts similarity index 99% rename from utils/greeting.js rename to src/utils/greeting.ts index 215afb3..40798cf 100644 --- a/utils/greeting.js +++ b/src/utils/greeting.ts @@ -1,3 +1,4 @@ +export {} const Canvas = require('wa-canvas') const welcome = (pushname, gcname, picprofil) => new Promise((resolve, reject) => { diff --git a/start.js b/start.js new file mode 100644 index 0000000..4fdb547 --- /dev/null +++ b/start.js @@ -0,0 +1,10 @@ +const { execSync } = require('child_process') + +start() + +function start () { + console.info('[INFO] Compiling source...') + execSync('npm run compile') + console.info('[INFO] Done compiling, starting the bot...') + require('./dist/krypton.js') +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..e01a5c7 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "allowJs": true, + "target": "ES2020", + "module": "commonjs", + "outDir": "dist", + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "skipLibCheck": true, + "noEmitHelpers": true, + "importHelpers": true, + "incremental": true, + "resolveJsonModule": true, + }, + "include": ["src/*/**.ts", "src/*.ts"] +}