-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathbot.js
326 lines (279 loc) · 10.5 KB
/
bot.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
// Imports
import { Bot } from "grammy"
import { BOT_TOKEN, ADMINS, LIMIT } from "./config.js"
import { isUrl, getRandomId, getProductDetails, productCommonUrl } from "./utils.js"
import { manageProducts, manageUsers } from "./db.js"
import unshort from "./unshort.js"
const bot = new Bot(BOT_TOKEN); // Initialize bot
const reply_markup = {
//common repky markup
inline_keyboard: [
[
{ text: "👨💻 Developer", url: "https://github.com/AffanTheBest" },
{ text: "🛒 Deals Channel", url: "https://t.me/aslootdeals" },
],
[
{ text: "🔃 Updates", url: "https://t.me/asprojects" },
{ text: "💁♂️ Support", url: "https://t.me/assupportchat" },
],
],
};
const processUrl = async (msg, ctx) => {
try {
const url = await unshort(msg);
const productUrl = "http" + url.split("http")[1].split(" ")[0].replace("dl.", "www.")
if (isUrl(productUrl)) {
const merchant = productUrl.replace("www.", "").split("//")[1].split(".")[0];
if (merchant.match(/amazon|flipkart|snapdeal/gi)) {
const noOfProducts = (await manageProducts({ userId: ctx.from.id }, "read"))?.result?.length;
if (noOfProducts < LIMIT) {
const sentMsg = await ctx.reply(`Tracking ${merchant} product...`, { reply_to_message_id: ctx.message.message_id });
const details = await getProductDetails(productUrl, merchant);
if (details.ok) {
try {
const tracking_id = getRandomId();
await manageProducts(
{ tracking_id, userId: ctx.from.id, merchant, title: details.title, link: details.link, initPrice: details.price, price: details.price, },
"update"
);
await ctx.api.editMessageText(
ctx.chat.id, sentMsg.message_id,
`<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}`,
{ parse_mode: "HTML", reply_markup }
);
} catch (e) { }
} else {
await ctx.api.editMessageText(
ctx.chat.id, sentMsg.message_id,
`Sorry, I couldn't track this product. Make sure you've sent correct product link.`,
{ parse_mode: "Markdown", reply_markup }
).catch(e => { });
}
} else {
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",
{ reply_to_message_id: ctx.message.message_id }).catch(e => { });
}
} else {
ctx.reply(`Sorry, I can't track this product. Cuz the link you sent is not a amazon or flipkart product link.`).catch(e => { });
}
} else {
ctx.reply(`Sorry ${ctx.message.chat.first_name}, I can't track this product. Make sure you've sent correct product link.`).catch(e => { });
}
} catch (e) {
console.error(e)
}
}
bot.command("start", (ctx) => {
// start command
try {
ctx.reply(
`Hello ${ctx.message.chat.first_name}, I can track price for Amazon & Flipkart products (Soon more).\n\nCheck /help to get started.\n`,
{
reply_to_message_id: ctx.message.message_id,
reply_markup,
}
).catch(() => { })
manageUsers({ id: ctx.message.from.id, name: ctx.message.from.first_name }, "update");
} catch (e) {
console.log("Error", e);
}
});
bot.command("help", (ctx) => {
// help command
try {
ctx.reply(
`/start - Start the bot\n/help - get this message.\n/track {Product Link} - Add product to tracking list.\n/stop_{Tracking ID} - Stop tracking.\n/list - Get list of products that are being tracked.\n\nFor more help join @@assupportchat.`,
{
reply_to_message_id: ctx.message.message_id,
reply_markup,
}
).catch(() => { })
} catch (e) { }
});
bot.command("track", async (ctx) => {
const message = ctx.message.text.replace("/track ", "");
processUrl(message, ctx);
});
bot.command("list", async (ctx) => {
try {
const products = await manageProducts({ 'users.userId': ctx.from.id }, "read");
const list = products.result
.map(
(product) =>
`<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}`
)
.join("\n\n");
ctx.reply(`Here is your tracking list:\n\n${list}`, {
reply_to_message_id: ctx.message.message_id,
parse_mode: "HTML",
disable_web_page_preview: true,
});
} catch (e) {
ctx.reply(
"An error has beem occured please report it to admin. This my be due to you've added too many products."
);
}
});
bot.hears(/^\/stop_([a-z0-9])/, async (ctx) => {
const tracking_id = ctx.message.text.replace("/stop_", "");
const result = await manageProducts(
{ tracking_id, userId: ctx.from.id },
"delete"
);
ctx.reply(
result.ok
? `Stopped tracking product with tracking id ${tracking_id}`
: `Sorry, I can't stop tracking product with tracking id ${tracking_id}.`
);
});
bot.command("broadcast", async (ctx) => {
if (ADMINS.includes(ctx.from.id)) {
let msg = ctx.message.text.replace("/broadcast ", "");
const inline_keyboard = ctx.message.text.split("inline_keyboard:")[1];
msg = msg.replace("inline_keyboard:", "").replace(inline_keyboard, "");
const users = await manageUsers({}, "read");
await Promise.all(
users.result.map(async (user) => {
try {
ctx.api.sendMessage(
user.id,
msg
.replace(/{name}/gi, "`" + user.name + "`")
.replace(/{id}/gi, user.id),
{
parse_mode: "Markdown",
disable_web_page_preview: true,
reply_markup: {
inline_keyboard: inline_keyboard
? JSON.parse(inline_keyboard)
: null,
},
}
);
} catch (e) { }
})
);
}
});
bot.command("users", async (ctx) => {
if (ADMINS.includes(ctx.from.id)) {
let users = await manageUsers({}, "read");
users =
"List Of Users: \n\n" +
users.result
.map(
(user) =>
`${user.id} - <a href="tg://user?id=${user.id}">${user.name}</a>`
)
.join("\n");
ctx.reply(users, { parse_mode: "HTML" });
}
});
bot.command("stats", async (ctx) => {
try {
const [users, products] = await Promise.all([manageUsers, manageProducts].map(
async (func) => await func({}, "read")
));
let prodCount = 0;
products.result.map(prod => prodCount += prod.users.length);
ctx.reply(
`Total Users: ${users.result.length}\nTotal Products: ${prodCount}`
);
} catch (e) {
console.log(e)
}
});
bot.on('::url', async ctx => {
if (ctx.chat.type === "private") {
const message = ctx.message.text;
processUrl(message, ctx);
}
});
bot.callbackQuery("stopTracking", async (ctx) => {
const tracking_id =
ctx.update?.callback_query?.message?.reply_markup?.inline_keyboard[1][0]?.text?.split(
" - "
)[1];
const result = await manageProducts(
{ tracking_id, userId: ctx.from.id },
"delete"
);
ctx.api.editMessageText(
ctx.update?.callback_query?.message?.chat?.id,
ctx.update?.callback_query?.message?.message_id,
result.ok
? `Stopped tracking product with tracking id ${tracking_id}`
: `Sorry, I can't stop tracking product with tracking id ${tracking_id}.`
);
});
const track = async () => {
try {
const products = await manageProducts({}, "read");
// Process 10 products at a time
for (let i = 0; i < products.result.length; i = i + 10) {
const temp = products.result.slice(i, i + 10)
await Promise.all(
temp.map(async (product) => {
const details = await getProductDetails(product.link, product.merchant);
if (details.ok && !isNaN(details.price) && details.price !== product.price) {
try {
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");
await Promise.all(product.users.map(async user => {
bot.api.sendMessage(
user.userId,
`<a href="${details.image}"> </a><b>Price has been ${details.price > product.price ? "increased" : "decreased"
} by ${Math.abs(product.price - details.price)}</b>. \n\n<b>${details.title
}</b>\n\nCurrent Price: <b>${details.price}</b>\nLink: <a href="${productCommonUrl(details.link, true)
}">${product.merchant}</a>\n\nTo stop tracking send /stop_${user.tracking_id
}`,
{
parse_mode: "HTML",
reply_markup: {
inline_keyboard: details?.link ? [
[{ text: "Buy Now", url: productCommonUrl(details.link, true) }],
[{ text: "Stop Tracking - " + user.tracking_id, callback_data: `stopTracking`, }]]
: []
}
}).catch(e => console.log(`🚀 ~ file: bot.js:255 ~ temp.map ~ e:`, e))
}))
// wait for 1 sec
await new Promise(resolve => setTimeout(resolve, 1000))
} catch (e) {
console.log(`🚀 ~ file: bot.js:260 ~ temp.map ~ e:`, e)
// bot.start()
// wait for 5 sec
await new Promise(resolve => setTimeout(resolve, 5000))
}
}
})
);
}
} catch (e) {
console.log(`🚀 ~ file: bot.js:270 ~ track ~ e:`, e)
}
};
bot.command("update", async (ctx) => {
if (ADMINS.includes(ctx.from.id)) {
track()
ctx.reply("Updating products...")
}
})
bot.catch((err) => {
console.error("err");
const ctx = err.ctx;
console.error(`Error while handling update ${ctx.update.update_id}:`);
const e = err.error;
console.error("Error: ", e.description);
// bot.start();
});
setInterval(track, 3600000); //Track every hr.
export default bot