-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
72 lines (69 loc) · 2.32 KB
/
index.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
import sanitizeHtml from "sanitize-html";
export async function TelegramMessageScraper(channelName) {
function cleanText(item) {
return sanitizeHtml(item, {
allowedTags: [],
allowedAttributes: {},
});
}
function getUserImage(html) {
const regex = /<img src="(.*?)"/g;
return regex.exec(html)?.[1];
}
function getUserLink(html) {
const regex = /<a class="tgme_widget_message_owner_name" href="(.*?)"/g;
return regex.exec(html)?.[1];
}
function getUserName(html) {
const regex = /<span dir="auto">(.*?)<\/span>/g;
return regex.exec(html)?.[1];
}
function getMessageDate(html) {
const regex = /<time datetime="(.*?)"/g;
return regex.exec(html)?.[1];
}
function getImage(html) {
const regex = /url\('(.*?)'/g;
return regex.exec(html)?.[1];
}
function getMessage(html) {
const regex =
/<div class="tgme_widget_message_text js-message_text" dir="auto">(.*?)<\/div>/g;
return cleanText(regex.exec(html)?.[1]);
}
function getViews(html) {
const regex = /<span class="tgme_widget_message_views">(.*?)<\/span>/g;
return regex.exec(html)?.[1];
}
function getActionLink(html) {
const regex =
/<a class="tgme_widget_message_inline_button url_button" href="(.*?)"/g;
return regex.exec(html)?.[1];
}
async function getChannelMessages(channelName) {
const url = `https://t.me/s/${channelName}`;
const result = await fetch(url);
const data = await result.text();
if (data.indexOf("tgme_channel_history js-message_history") === -1) {
console.error("Channel not found");
return null;
}
const messageContainer = data.split('class="tgme_widget_message_user">');
messageContainer.shift();
const messages = [];
messageContainer.forEach((message) => {
messages.push({
userName: getUserName(message),
userImage: getUserImage(message),
userLink: getUserLink(message),
date: getMessageDate(message),
message: getMessage(message),
image: getImage(message),
views: getViews(message),
actionLink: getActionLink(message),
});
});
return messages;
}
return await getChannelMessages(channelName);
}