Skip to content

Commit 9eda82c

Browse files
committed
Prettify
1 parent 1e224bb commit 9eda82c

File tree

1 file changed

+75
-40
lines changed

1 file changed

+75
-40
lines changed

bot.js

Lines changed: 75 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -23,49 +23,55 @@ const reply_markup = {
2323

2424
const processUrl = async (msg, ctx) => {
2525
try {
26-
const url = await unshort(msg);
27-
const productUrl = "http" + url.split("http")[1].split(" ")[0].replace("dl.", "www.")
28-
if (isUrl(productUrl)) {
29-
const merchant = productUrl.replace("www.", "").split("//")[1].split(".")[0];
30-
if (merchant.match(/amazon|flipkart|snapdeal/gi)) {
31-
const noOfProducts = ( await manageProducts({ userId: ctx.from.id }, "read") )?.result?.length;
26+
const url = await unshort(msg);
27+
const productUrl = "http" + url.split("http")[1].split(" ")[0].replace("dl.", "www.")
28+
29+
if (isUrl(productUrl)) {
30+
const merchant = productUrl.replace("www.", "").split("//")[1].split(".")[0];
31+
32+
if (merchant.match(/amazon|flipkart|snapdeal/gi)) {
33+
const noOfProducts = (await manageProducts({ userId: ctx.from.id }, "read"))?.result?.length;
34+
3235
if (noOfProducts < LIMIT) {
3336
const sentMsg = await ctx.reply(`Tracking ${merchant} product...`, { reply_to_message_id: ctx.message.message_id });
3437
const details = await getProductDetails(productUrl, merchant);
35-
38+
3639
if (details.ok) {
3740
try {
3841
const tracking_id = getRandomId();
3942
await manageProducts(
4043
{ tracking_id, userId: ctx.from.id, merchant, title: details.title, link: details.link, initPrice: details.price, price: details.price, },
4144
"update"
42-
);
43-
await ctx.api.editMessageText(
44-
ctx.chat.id, sentMsg.message_id,
45-
`<a href="${details.image}"> </a>\nTracking <b>${details.title}</b>\n\nCurrent Price: <b>${details.price}</b>\nLink: <a href="${details.link}">${merchant}</a>\n\nTo stop tracking send /stop_${tracking_id}`,
46-
{ parse_mode: "HTML", reply_markup }
45+
);
46+
47+
await ctx.api.editMessageText(
48+
ctx.chat.id, sentMsg.message_id,
49+
`<a href="${details.image}"> </a>\nTracking <b>${details.title}</b>\n\nCurrent Price: <b>${details.price}</b>\nLink: <a href="${details.link}">${merchant}</a>\n\nTo stop tracking send /stop_${tracking_id}`,
50+
{ parse_mode: "HTML", reply_markup }
4751
);
4852
} catch (e) { }
4953
} else {
5054
await ctx.api.editMessageText(
5155
ctx.chat.id, sentMsg.message_id,
5256
`Sorry, I couldn't track this product. Make sure you've sent correct product link.`,
5357
{ parse_mode: "Markdown", reply_markup }
54-
).catch(e => {});
55-
}
56-
} else {
57-
ctx.reply( "I'm sorry, but you can't add more products as you've already reached the maximum limit.\n\nPlease delete atleast one product. And try again.\n\nTo get list send /list",
58-
{ reply_to_message_id: ctx.message.message_id } ).catch(e => {});
58+
).catch(e => { });
5959
}
60+
6061
} else {
61-
ctx.reply( `Sorry, I can't track this product. Cuz the link you sent is not a amazon or flipkart product link.` ).catch(e => {});
62+
ctx.reply("I'm sorry, but you can't add more products as you've already reached the maximum limit.\n\nPlease delete atleast one product. And try again.\n\nTo get list send /list",
63+
{ reply_to_message_id: ctx.message.message_id }).catch(e => { });
6264
}
65+
6366
} else {
64-
ctx.reply( `Sorry ${ctx.message.chat.first_name}, I can't track this product. Make sure you've sent correct product link.` ).catch(e => {});
67+
ctx.reply(`Sorry, I can't track this product. Cuz the link you sent is not a amazon or flipkart product link.`).catch(e => { });
6568
}
66-
} catch(e){
67-
console.error(e)
69+
} else {
70+
ctx.reply(`Sorry ${ctx.message.chat.first_name}, I can't track this product. Make sure you've sent correct product link.`).catch(e => { });
6871
}
72+
} catch (e) {
73+
console.error(e)
74+
}
6975
}
7076

7177

@@ -74,9 +80,13 @@ bot.command("start", (ctx) => {
7480
try {
7581
ctx.reply(
7682
`Hello ${ctx.message.chat.first_name}, I can track price for Amazon & Flipkart products (Soon more).\n\nCheck /help to get started.\n`,
77-
{ reply_to_message_id: ctx.message.message_id, reply_markup, }
78-
).catch(() => {})
79-
manageUsers( { id: ctx.message.from.id, name: ctx.message.from.first_name }, "update" );
83+
{
84+
reply_to_message_id: ctx.message.message_id,
85+
reply_markup,
86+
}
87+
).catch(() => { })
88+
89+
manageUsers({ id: ctx.message.from.id, name: ctx.message.from.first_name }, "update");
8090
} catch (e) {
8191
console.log("Error", e);
8292
}
@@ -91,7 +101,7 @@ bot.command("help", (ctx) => {
91101
reply_to_message_id: ctx.message.message_id,
92102
reply_markup,
93103
}
94-
).catch(() => {})
104+
).catch(() => { })
95105
} catch (e) { }
96106
});
97107

@@ -100,16 +110,18 @@ bot.command("track", async (ctx) => {
100110
const message = ctx.message.text.replace("/track ", "");
101111
processUrl(message, ctx);
102112
});
103-
113+
104114
bot.command("list", async (ctx) => {
105115
try {
106116
const products = await manageProducts({ 'users.userId': ctx.from.id }, "read");
117+
107118
const list = products.result
108119
.map(
109120
(product) =>
110121
`<b>${product.title}</b>\nLast Price: ${product.price}\nLink: <a href="${product.link}">${product.merchant}</a>\nTo stop send /stop_${product.users.filter(u => u.userId == ctx.from.id)[0].tracking_id}`
111122
)
112123
.join("\n\n");
124+
113125
ctx.reply(`Here is your tracking list:\n\n${list}`, {
114126
reply_to_message_id: ctx.message.message_id,
115127
parse_mode: "HTML",
@@ -124,10 +136,12 @@ bot.command("list", async (ctx) => {
124136

125137
bot.hears(/^\/stop_([a-z0-9])/, async (ctx) => {
126138
const tracking_id = ctx.message.text.replace("/stop_", "");
139+
127140
const result = await manageProducts(
128141
{ tracking_id, userId: ctx.from.id },
129142
"delete"
130143
);
144+
131145
ctx.reply(
132146
result.ok
133147
? `Stopped tracking product with tracking id ${tracking_id}`
@@ -139,7 +153,9 @@ bot.command("broadcast", async (ctx) => {
139153
if (ADMINS.includes(ctx.from.id)) {
140154
let msg = ctx.message.text.replace("/broadcast ", "");
141155
const inline_keyboard = ctx.message.text.split("inline_keyboard:")[1];
156+
142157
msg = msg.replace("inline_keyboard:", "").replace(inline_keyboard, "");
158+
143159
const users = await manageUsers({}, "read");
144160
await Promise.all(
145161
users.result.map(async (user) => {
@@ -168,6 +184,7 @@ bot.command("broadcast", async (ctx) => {
168184
bot.command("users", async (ctx) => {
169185
if (ADMINS.includes(ctx.from.id)) {
170186
let users = await manageUsers({}, "read");
187+
171188
users =
172189
"List Of Users: \n\n" +
173190
users.result
@@ -176,27 +193,30 @@ bot.command("users", async (ctx) => {
176193
`${user.id} - <a href="tg://user?id=${user.id}">${user.name}</a>`
177194
)
178195
.join("\n");
196+
179197
ctx.reply(users, { parse_mode: "HTML" });
180198
}
181199
});
182200

183201
bot.command("stats", async (ctx) => {
184-
try{
185-
const[users, products] = await Promise.all([manageUsers, manageProducts].map(
202+
try {
203+
const [users, products] = await Promise.all([manageUsers, manageProducts].map(
186204
async (func) => await func({}, "read")
205+
187206
));
188207
let prodCount = 0;
189208
products.result.map(prod => prodCount += prod.users.length);
209+
190210
ctx.reply(
191211
`Total Users: ${users.result.length}\nTotal Products: ${prodCount}`
192212
);
193-
}catch(e){
213+
} catch (e) {
194214
console.log(e)
195215
}
196216
});
197217

198218
bot.on('::url', async ctx => {
199-
if(ctx.chat.type === "private"){
219+
if (ctx.chat.type === "private") {
200220
const message = ctx.message.text;
201221
processUrl(message, ctx);
202222
}
@@ -207,10 +227,12 @@ bot.callbackQuery("stopTracking", async (ctx) => {
207227
ctx.update?.callback_query?.message?.reply_markup?.inline_keyboard[1][0]?.text?.split(
208228
" - "
209229
)[1];
230+
210231
const result = await manageProducts(
211232
{ tracking_id, userId: ctx.from.id },
212233
"delete"
213234
);
235+
214236
ctx.api.editMessageText(
215237
ctx.update?.callback_query?.message?.chat?.id,
216238
ctx.update?.callback_query?.message?.message_id,
@@ -224,16 +246,26 @@ const track = async () => {
224246
try {
225247
const products = await manageProducts({}, "read");
226248
// Process 10 products at a time
227-
for (let i = 0; i < products.result.length; i = i + 10 ) {
228-
const temp = products.result.slice(i, i + 10)
229-
249+
for (let i = 0; i < products.result.length; i = i + 10) {
250+
const temp = products.result.slice(i, i + 10)
251+
230252
await Promise.all(
231253
temp.map(async (product) => {
232254
const details = await getProductDetails(product.link, product.merchant);
233255

234256
if (details.ok && !isNaN(details.price) && details.price !== product.price) {
235257
try {
236-
await manageProducts({ tracking_id: product.tracking_id, userId: product.userId, merchant: product.merchant, title: details.title, link: product.link, initPrice: product.price, price: details.price, users: product.users}, "update");
258+
await manageProducts({
259+
tracking_id: product.tracking_id,
260+
userId: product.userId,
261+
merchant: product.merchant,
262+
title: details.title,
263+
link: product.link,
264+
initPrice: product.price,
265+
price: details.price,
266+
users: product.users
267+
}, "update");
268+
237269
await Promise.all(product.users.map(async user => {
238270
bot.api.sendMessage(
239271
user.userId,
@@ -246,28 +278,28 @@ const track = async () => {
246278
parse_mode: "HTML",
247279
reply_markup: {
248280
inline_keyboard: details?.link ? [
249-
[{ text: "Buy Now", url: productCommonUrl(details.link, true) }],
250-
[{ text: "Stop Tracking - " + user.tracking_id, callback_data: `stopTracking`, }]]
251-
: []
281+
[{ text: "Buy Now", url: productCommonUrl(details.link, true) }],
282+
[{ text: "Stop Tracking - " + user.tracking_id, callback_data: `stopTracking`, }]]
283+
: []
252284
}
253285
}).catch(e => console.log(`🚀 ~ file: bot.js:255 ~ temp.map ~ e:`, e))
254286
}))
255287

256288
// wait for 1 sec
257289
await new Promise(resolve => setTimeout(resolve, 1000))
258-
} catch (e) {
290+
} catch (e) {
259291
console.log(`🚀 ~ file: bot.js:260 ~ temp.map ~ e:`, e)
260292
bot.start()
261293
// wait for 5 sec
262294
await new Promise(resolve => setTimeout(resolve, 5000))
263-
}
295+
}
264296
}
265297
})
266298
);
267299
}
268300
} catch (e) {
269301
console.log(`🚀 ~ file: bot.js:270 ~ track ~ e:`, e)
270-
}
302+
}
271303
};
272304

273305
bot.command("update", async (ctx) => {
@@ -279,10 +311,13 @@ bot.command("update", async (ctx) => {
279311

280312
bot.catch((err) => {
281313
console.error("err");
314+
282315
const ctx = err.ctx;
283316
console.error(`Error while handling update ${ctx.update.update_id}:`);
317+
284318
const e = err.error;
285319
console.error("Error: ", e.description);
320+
286321
bot.start();
287322
});
288323

0 commit comments

Comments
 (0)