Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
MR414N-ID
GitHub Repository: MR414N-ID/botku2
Path: blob/master/lib/myfunc.js
1126 views
1
/**
2
* Create By Dika Ardnt.
3
* Contact Me on wa.me/6288292024190
4
* Follow https://github.com/DikaArdnt
5
*/
6
7
const { proto, delay, getContentType } = require('@adiwajshing/baileys')
8
const chalk = require('chalk')
9
const fs = require('fs')
10
const Crypto = require('crypto')
11
const axios = require('axios')
12
const moment = require('moment-timezone')
13
const { sizeFormatter } = require('human-readable')
14
const util = require('util')
15
const Jimp = require('jimp')
16
const { defaultMaxListeners } = require('stream')
17
18
19
const unixTimestampSeconds = (date = new Date()) => Math.floor(date.getTime() / 1000)
20
21
exports.unixTimestampSeconds = unixTimestampSeconds
22
23
exports.generateMessageTag = (epoch) => {
24
let tag = (0, exports.unixTimestampSeconds)().toString();
25
if (epoch)
26
tag += '.--' + epoch; // attach epoch if provided
27
return tag;
28
}
29
30
exports.processTime = (timestamp, now) => {
31
return moment.duration(now - moment(timestamp * 1000)).asSeconds()
32
}
33
34
exports.getRandom = (ext) => {
35
return `${Math.floor(Math.random() * 10000)}${ext}`
36
}
37
38
exports.getBuffer = async (url, options) => {
39
try {
40
options ? options : {}
41
const res = await axios({
42
method: "get",
43
url,
44
headers: {
45
'DNT': 1,
46
'Upgrade-Insecure-Request': 1
47
},
48
...options,
49
responseType: 'arraybuffer'
50
})
51
return res.data
52
} catch (err) {
53
return err
54
}
55
}
56
57
exports.fetchJson = async (url, options) => {
58
try {
59
options ? options : {}
60
const res = await axios({
61
method: 'GET',
62
url: url,
63
headers: {
64
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'
65
},
66
...options
67
})
68
return res.data
69
} catch (err) {
70
return err
71
}
72
}
73
74
exports.runtime = function(seconds) {
75
seconds = Number(seconds);
76
var d = Math.floor(seconds / (3600 * 24));
77
var h = Math.floor(seconds % (3600 * 24) / 3600);
78
var m = Math.floor(seconds % 3600 / 60);
79
var s = Math.floor(seconds % 60);
80
var dDisplay = d > 0 ? d + (d == 1 ? " day, " : " days, ") : "";
81
var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
82
var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
83
var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
84
return dDisplay + hDisplay + mDisplay + sDisplay;
85
}
86
87
exports.clockString = (ms) => {
88
let h = isNaN(ms) ? '--' : Math.floor(ms / 3600000)
89
let m = isNaN(ms) ? '--' : Math.floor(ms / 60000) % 60
90
let s = isNaN(ms) ? '--' : Math.floor(ms / 1000) % 60
91
return [h, m, s].map(v => v.toString().padStart(2, 0)).join(':')
92
}
93
94
exports.sleep = async (ms) => {
95
return new Promise(resolve => setTimeout(resolve, ms));
96
}
97
98
exports.isUrl = (url) => {
99
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'))
100
}
101
102
exports.getTime = (format, date) => {
103
if (date) {
104
return moment(date).locale('id').format(format)
105
} else {
106
return moment.tz('Asia/Jakarta').locale('id').format(format)
107
}
108
}
109
110
exports.formatDate = (n, locale = 'id') => {
111
let d = new Date(n)
112
return d.toLocaleDateString(locale, {
113
weekday: 'long',
114
day: 'numeric',
115
month: 'long',
116
year: 'numeric',
117
hour: 'numeric',
118
minute: 'numeric',
119
second: 'numeric'
120
})
121
}
122
123
exports.tanggal = (numer) => {
124
myMonths = ["Januari","Februari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","November","Desember"];
125
myDays = ['Minggu','Senin','Selasa','Rabu','Kamis','Jum’at','Sabtu'];
126
var tgl = new Date(numer);
127
var day = tgl.getDate()
128
bulan = tgl.getMonth()
129
var thisDay = tgl.getDay(),
130
thisDay = myDays[thisDay];
131
var yy = tgl.getYear()
132
var year = (yy < 1000) ? yy + 1900 : yy;
133
const time = moment.tz('Asia/Jakarta').format('DD/MM HH:mm:ss')
134
let d = new Date
135
let locale = 'id'
136
let gmt = new Date(0).getTime() - new Date('1 January 1970').getTime()
137
let weton = ['Pahing', 'Pon','Wage','Kliwon','Legi'][Math.floor(((d * 1) + gmt) / 84600000) % 5]
138
139
return`${thisDay}, ${day} - ${myMonths[bulan]} - ${year}`
140
}
141
142
exports.formatp = sizeFormatter({
143
std: 'JEDEC', //'SI' = default | 'IEC' | 'JEDEC'
144
decimalPlaces: 2,
145
keepTrailingZeroes: false,
146
render: (literal, symbol) => `${literal} ${symbol}B`,
147
})
148
149
exports.jsonformat = (string) => {
150
return JSON.stringify(string, null, 2)
151
}
152
153
function format(...args) {
154
return util.format(...args)
155
}
156
157
exports.logic = (check, inp, out) => {
158
if (inp.length !== out.length) throw new Error('Input and Output must have same length')
159
for (let i in inp)
160
if (util.isDeepStrictEqual(check, inp[i])) return out[i]
161
return null
162
}
163
164
exports.generateProfilePicture = async (buffer) => {
165
const jimp = await Jimp.read(buffer)
166
const min = jimp.getWidth()
167
const max = jimp.getHeight()
168
const cropped = jimp.crop(0, 0, min, max)
169
return {
170
img: await cropped.scaleToFit(720, 720).getBufferAsync(Jimp.MIME_JPEG),
171
preview: await cropped.scaleToFit(720, 720).getBufferAsync(Jimp.MIME_JPEG)
172
}
173
}
174
175
exports.bytesToSize = (bytes, decimals = 2) => {
176
if (bytes === 0) return '0 Bytes';
177
178
const k = 1024;
179
const dm = decimals < 0 ? 0 : decimals;
180
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
181
182
const i = Math.floor(Math.log(bytes) / Math.log(k));
183
184
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
185
}
186
187
exports.getSizeMedia = (path) => {
188
return new Promise((resolve, reject) => {
189
if (/http/.test(path)) {
190
axios.get(path)
191
.then((res) => {
192
let length = parseInt(res.headers['content-length'])
193
let size = exports.bytesToSize(length, 3)
194
if(!isNaN(length)) resolve(size)
195
})
196
} else if (Buffer.isBuffer(path)) {
197
let length = Buffer.byteLength(path)
198
let size = exports.bytesToSize(length, 3)
199
if(!isNaN(length)) resolve(size)
200
} else {
201
reject('error gatau apah')
202
}
203
})
204
}
205
206
exports.parseMention = (text = '') => {
207
return [...text.matchAll(/@([0-9]{5,16}|0)/g)].map(v => v[1] + '@s.whatsapp.net')
208
}
209
210
211
/**
212
* Serialize Message
213
* @param {WAConnection} conn
214
* @param {Object} m
215
* @param {store} store
216
*/
217
exports.smsg = (conn, m, store) => {
218
if (!m) return m
219
let M = proto.WebMessageInfo
220
if (m.key) {
221
m.id = m.key.id
222
m.isBaileys = m.id.startsWith('BAE5') && m.id.length === 16
223
m.chat = m.key.remoteJid
224
m.fromMe = m.key.fromMe
225
m.isGroup = m.chat.endsWith('@g.us')
226
m.sender = conn.decodeJid(m.fromMe && conn.user.id || m.participant || m.key.participant || m.chat || '')
227
if (m.isGroup) m.participant = conn.decodeJid(m.key.participant) || ''
228
}
229
if (m.message) {
230
m.mtype = getContentType(m.message)
231
m.msg = (m.mtype == 'viewOnceMessage' ? m.message[m.mtype].message[getContentType(m.message[m.mtype].message)] : m.message[m.mtype])
232
m.body = m.message.conversation || m.msg.caption || m.msg.text || (m.mtype == 'listResponseMessage') && m.msg.singleSelectReply.selectedRowId || (m.mtype == 'buttonsResponseMessage') && m.msg.selectedButtonId || (m.mtype == 'viewOnceMessage') && m.msg.caption || m.text
233
let quoted = m.quoted = m.msg.contextInfo ? m.msg.contextInfo.quotedMessage : null
234
m.mentionedJid = m.msg.contextInfo ? m.msg.contextInfo.mentionedJid : []
235
if (m.quoted) {
236
let type = getContentType(quoted)
237
m.quoted = m.quoted[type]
238
if (['productMessage'].includes(type)) {
239
type = getContentType(m.quoted)
240
m.quoted = m.quoted[type]
241
}
242
if (typeof m.quoted === 'string') m.quoted = {
243
text: m.quoted
244
}
245
m.quoted.mtype = type
246
m.quoted.id = m.msg.contextInfo.stanzaId
247
m.quoted.chat = m.msg.contextInfo.remoteJid || m.chat
248
m.quoted.isBaileys = m.quoted.id ? m.quoted.id.startsWith('BAE5') && m.quoted.id.length === 16 : false
249
m.quoted.sender = conn.decodeJid(m.msg.contextInfo.participant)
250
m.quoted.fromMe = m.quoted.sender === (conn.user && conn.user.id)
251
m.quoted.text = m.quoted.text || m.quoted.caption || m.quoted.conversation || m.quoted.contentText || m.quoted.selectedDisplayText || m.quoted.title || ''
252
m.quoted.mentionedJid = m.msg.contextInfo ? m.msg.contextInfo.mentionedJid : []
253
m.getQuotedObj = m.getQuotedMessage = async () => {
254
if (!m.quoted.id) return false
255
let q = await store.loadMessage(m.chat, m.quoted.id, conn)
256
return exports.smsg(conn, q, store)
257
}
258
let vM = m.quoted.fakeObj = M.fromObject({
259
key: {
260
remoteJid: m.quoted.chat,
261
fromMe: m.quoted.fromMe,
262
id: m.quoted.id
263
},
264
message: quoted,
265
...(m.isGroup ? { participant: m.quoted.sender } : {})
266
})
267
268
/**
269
*
270
* @returns
271
*/
272
m.quoted.delete = () => conn.sendMessage(m.quoted.chat, { delete: vM.key })
273
274
/**
275
*
276
* @param {*} jid
277
* @param {*} forceForward
278
* @param {*} options
279
* @returns
280
*/
281
m.quoted.copyNForward = (jid, forceForward = false, options = {}) => conn.copyNForward(jid, vM, forceForward, options)
282
283
/**
284
*
285
* @returns
286
*/
287
m.quoted.download = () => conn.downloadMediaMessage(m.quoted)
288
}
289
}
290
if (m.msg.url) m.download = () => conn.downloadMediaMessage(m.msg)
291
m.text = m.msg.text || m.msg.caption || m.message.conversation || m.msg.contentText || m.msg.selectedDisplayText || m.msg.title || ''
292
/**
293
* Reply to this message
294
* @param {String|Object} text
295
* @param {String|false} chatId
296
* @param {Object} options
297
*/
298
m.reply = (text, chatId = m.chat, options = {}) => Buffer.isBuffer(text) ? conn.sendMedia(chatId, text, 'file', '', m, { ...options }) : conn.sendText(chatId, text, m, { ...options })
299
/**
300
* Copy this message
301
*/
302
m.copy = () => exports.smsg(conn, M.fromObject(M.toObject(m)))
303
304
/**
305
*
306
* @param {*} jid
307
* @param {*} forceForward
308
* @param {*} options
309
* @returns
310
*/
311
m.copyNForward = (jid = m.chat, forceForward = false, options = {}) => conn.copyNForward(jid, m, forceForward, options)
312
313
return m
314
}
315
316
317
let file = require.resolve(__filename)
318
fs.watchFile(file, () => {
319
fs.unwatchFile(file)
320
console.log(chalk.redBright(`Update ${__filename}`))
321
delete require.cache[file]
322
require(file)
323
})
324
325