Repository navigation
Expand file tree
/
Copy pathnews.js
More file actions
174 lines (151 loc) · 5.6 KB
/
Copy pathnews.js
File metadata and controls
174 lines (151 loc) · 5.6 KB
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
import axios from 'axios';
class Author {
constructor(rawData = {}) {
this.id = rawData.id || null;
this.name = rawData.name || 'N/A';
this.jobTitle = rawData.jobtitle ? rawData.jobtitle.trim() : '';
}
}
class ArticleSummary {
constructor(rawData = {}) {
this.guid = rawData.guid || '';
this.title = rawData.title || 'No Title';
this.url = rawData.url || '';
this.imageUrl = rawData.image || rawData.img || '';
this.channel = rawData.channel || 'N/A';
this.section = rawData.section || 'N/A';
this.publishedDate = rawData.date ? new Date(rawData.date) : null;
}
}
class Article {
constructor(rawData, guid) {
this.guid = guid;
this.title = rawData.title || 'No Title';
this.url = rawData.urlpage || '';
this.description = rawData.description || '';
this.channel = rawData.kanal || 'N/A';
this.tags = rawData.tags || [];
this.publishedDate = new Date(rawData.date);
this.author = new Author(rawData.author);
this.editor = new Author(rawData.editor);
this.images = this._processMedia(rawData.photoblock, 'image');
this.videos = this._processMedia(rawData.videoblock, 'video');
const { html, text } = this._processContent(rawData.content);
this.contentHtml = html;
this.contentText = text;
}
_processMedia(mediaBlock = [], type) {
return mediaBlock.map(item => ({
url: item.block,
author: item.author || null,
caption: item.caption || null,
order: parseInt(item.orderid, 10),
}));
}
_processContent(contentArray = []) {
let fullHtml = contentArray
.map(htmlString => {
if (htmlString.includes('[video.1]')) {
const videoUrl = this.videos[0]?.url;
return videoUrl ? `<p><strong>[Embedded Video]</strong> <a href="${videoUrl}" target="_blank">${videoUrl}</a></p>` : '';
}
return htmlString;
})
.join('');
const plainText = fullHtml
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/(p|div|h[1-6]|ul|ol)>/gi, '\n')
.replace(/<li[^>]*>/gi, '\n* ')
.replace(/<[^>]*>/g, '')
.replace(/ /g, ' ')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/[ \t]+/g, ' ')
.replace(/\n\s*\n/g, '\n\n')
.split('\n').map(line => line.trim()).join('\n')
.trim();
return { html: fullHtml, text: plainText };
}
}
class Kompas {
constructor() {
this.baseUrl = 'https://api.kompas.com/apps';
this.recommendationUrl = 'https://recommendation.kgdata.dev/rec/kompascom/api/v2';
this.defaultHeaders = {
'User-Agent': 'kompascom-android',
'Accept-Encoding': 'gzip',
};
this.client = axios.create({ headers: this.defaultHeaders });
}
async getLatestNews(page = 1) {
const url = `${this.baseUrl}/home?pages=${page}`;
try {
const response = await this.client.get(url);
const rawArticles = response.data.latest || [];
return rawArticles.map(articleData => new ArticleSummary(articleData));
} catch (error) {
console.error(`[KompasAPI] Error fetching latest news: ${error.message}`);
throw error;
}
}
async getArticleDetail(guid) {
if (!guid) throw new Error('GUID must be provided.');
const url = `${this.baseUrl}/v1/detail?guid=${guid}`;
try {
const response = await this.client.get(url);
return new Article(response.data.result, guid);
} catch (error) {
console.error(`[KompasAPI] Error fetching article detail for ${guid}: ${error.message}`);
throw error;
}
}
}
let handler = async (m, { conn, text, usedPrefix, command }) => {
const kompas = new Kompas();
try {
await m.react('📰');
const latestNews = await kompas.getLatestNews();
if (!latestNews || latestNews.length === 0) {
return m.reply('Yah gak ada berita barui.');
}
const requestedIndex = parseInt(text, 10);
if (!isNaN(requestedIndex) && requestedIndex > 0 && requestedIndex <= latestNews.length) {
const selectedArticleSummary = latestNews[requestedIndex - 1];
await m.reply(`cari detail nya dulu yng #${requestedIndex}: *${selectedArticleSummary.title}*...`);
const articleDetail = await kompas.getArticleDetail(selectedArticleSummary.guid);
let reply = `*${articleDetail.title}*\n\n`;
reply += `> _${articleDetail.description}_\n\n`;
reply += `*Channel:* ${articleDetail.channel}\n`;
reply += `*Tanggal Terbit:* ${articleDetail.publishedDate.toLocaleDateString('id-ID', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}\n`;
reply += `*Editor:* ${articleDetail.editor.name}\n\n`;
reply += `*Sumber:* ${articleDetail.url}\n\n`;
reply += '--- *Isi Berita* ---\n\n';
reply += articleDetail.contentText.substring(0, 1000) + '...';
const imageUrl = articleDetail.images[0]?.url;
if (imageUrl) {
await conn.sendMessage(m.chat, {
image: { url: imageUrl },
caption: reply
}, { quoted: m });
} else {
m.reply(reply);
}
} else {
let reply = '*10 Berita Terbaru dari Kompas.com*\n\n';
latestNews.slice(0, 10).forEach((article, index) => {
reply += `*${index + 1}.* ${article.title}\n`;
reply += ` - _Channel: ${article.channel}_\n\n`;
});
reply += `Ketik *${usedPrefix + command} [nomor]* untuk membaca berita lebih detail.\nContoh: *${usedPrefix + command} 1*`;
m.reply(reply);
}
} catch (error) {
console.error(error);
m.reply('emro bang');
}
};
handler.help = ['kompas'];
handler.tags = ['internet', 'tools'];
handler.command = ['kompas', 'berita'];
export default handler;