Spaces:
Sleeping
Sleeping
Download lib/tg/public.js from Ethscriptions/cut: direct link, hf CLI and curl.
- Browser
- Download file 2.28 kB
-
https://huggingface.co/spaces/Ethscriptions/cut/resolve/main/lib/tg/public.js
- Command line
-
hf download hf://spaces/Ethscriptions/cut/lib/tg/public.js
-
curl -L -o public.js https://huggingface.co/spaces/Ethscriptions/cut/resolve/main/lib/tg/public.js
2.28 kB
| /** | |
| * Anonymous fallback for public Telegram channels: the t.me/s/<name> web | |
| * preview. Only used while the logged-in session is not live. | |
| */ | |
| const UA = | |
| 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36' | |
| const decode = (s) => | |
| String(s || '') | |
| .replace(/"/g, '"') | |
| .replace(/'/g, "'") | |
| .replace(/>/g, '>') | |
| .replace(/</g, '<') | |
| .replace(/&/g, '&') | |
| const strip = (html) => decode(String(html || '').replace(/<br\s*\/?>/gi, '\n').replace(/<[^>]+>/g, '')) | |
| function parseViews(text) { | |
| const m = /^([\d.]+)([KkMm]?)/.exec(String(text || '').replace(/[\s, ]/g, '')) | |
| if (!m) return 0 | |
| const unit = m[2].toUpperCase() | |
| return Math.round(Number(m[1]) * (unit === 'K' ? 1e3 : unit === 'M' ? 1e6 : 1)) || 0 | |
| } | |
| /** Newest ~20 posts of a public channel as raw { id, text, links, date, views }. */ | |
| async function readChannel(username) { | |
| const res = await fetch(`https://t.me/s/${encodeURIComponent(username)}`, { | |
| headers: { 'user-agent': UA, accept: 'text/html' }, | |
| signal: AbortSignal.timeout(20000), | |
| }) | |
| if (!res.ok) throw new Error(`t.me 预览 HTTP ${res.status}`) | |
| const html = await res.text() | |
| const title = decode(/<meta property="og:title" content="([^"]*)"/.exec(html)?.[1] || '').trim() || username | |
| const anchors = [...html.matchAll(/data-post="([^"]+)"/g)].map((m) => ({ index: m.index, post: m[1] })) | |
| const out = [] | |
| for (let i = 0; i < anchors.length; i += 1) { | |
| const block = html.slice(anchors[i].index, anchors[i + 1]?.index ?? html.length) | |
| const id = Number(String(anchors[i].post).split('/')[1]) | |
| if (!id) continue | |
| const body = /<div class="tgme_widget_message_text[^"]*"[^>]*>([\s\S]*?)<\/div>/.exec(block)?.[1] || '' | |
| const links = [...block.matchAll(/<a[^>]+href="(https?:\/\/[^"]+)"/g)].map((m) => decode(m[1])) | |
| const iso = /<time datetime="([^"]+)"/.exec(block)?.[1] | |
| out.push({ | |
| id, | |
| text: strip(body).trim(), | |
| links: [...new Set(links)], | |
| date: Math.floor(Date.parse(iso || '') / 1000) || Math.floor(Date.now() / 1000), | |
| views: parseViews(/class="tgme_widget_message_views">([^<]*)</.exec(block)?.[1]), | |
| }) | |
| } | |
| return { title, messages: out } | |
| } | |
| module.exports = { readChannel } | |