From 26bc26a3b8053a256432469d3b809df26c60f399 Mon Sep 17 00:00:00 2001 From: pseudoyu Date: Sun, 27 Oct 2024 21:37:37 +0700 Subject: [PATCH] feat(route/telegram): add telegram session scripts and logics --- lib/config.ts | 1 + lib/routes/telegram/channel.ts | 17 ++++++-- .../telegram/scripts/get-telegram-session.mjs | 41 +++++++++++++++++++ lib/routes/telegram/tglib/channel.ts | 4 ++ 4 files changed, 59 insertions(+), 4 deletions(-) create mode 100644 lib/routes/telegram/scripts/get-telegram-session.mjs diff --git a/lib/config.ts b/lib/config.ts index e2e933e6eaf875..782e831a1ac52e 100644 --- a/lib/config.ts +++ b/lib/config.ts @@ -286,6 +286,7 @@ export type Config = { }; telegram: { token?: string; + session?: string; }; tophub: { cookie?: string; diff --git a/lib/routes/telegram/channel.ts b/lib/routes/telegram/channel.ts index 15ca3ced5c5c32..38abd90b9fae2e 100644 --- a/lib/routes/telegram/channel.ts +++ b/lib/routes/telegram/channel.ts @@ -92,7 +92,13 @@ For backward compatibility reasons, invalid \`routeParams\` will be treated as \ `, }, features: { - requireConfig: false, + requireConfig: [ + { + name: 'TELEGRAM_SESSION', + optional: true, + description: '', + }, + ], requirePuppeteer: false, antiCrawler: false, supportBT: false, @@ -110,13 +116,12 @@ For backward compatibility reasons, invalid \`routeParams\` will be treated as \ handler, description: ` :::tip - Due to Telegram restrictions, some channels involving pornography, copyright, and politics cannot be subscribed. You can confirm by visiting \`https://t.me/s/:username\`. + Due to Telegram restrictions, some channels involving pornography, copyright, and politics cannot be subscribed. You can confirm by visiting \`https://t.me/s/:username\`, it's recommended to deploy your own instance with configs (create your telegram via \`https://core.telegram.org/api/obtaining_api_id\`, run this command \`node ./lib/routes/telegram/scripts/get-telegram-session.mjs\` to get \`TELEGRAM_SESSION\` and set it as Environment Variable). :::`, }; async function handler(ctx) { - const useWeb = ctx.req.param('routeParams') || !config.telegram.session; - if (!useWeb) { + if (ctx.req.param('routeParams') && config.telegram.session) { return tglibchannel(ctx); } @@ -191,6 +196,10 @@ async function handler(ctx) { : $('.tgme_widget_message_wrap:not(.tgme_widget_message_wrap:has(.service_message,.tme_no_messages_found))'); // also exclude service messages if (list.length === 0 && $('.tgme_channel_history').length === 0) { + if (config.telegram.session) { + return tglibchannel(ctx); + } + throw new Error(`Unable to fetch message feed from this channel. Please check this URL to see if you can view the message preview: ${resourceUrl}`); } diff --git a/lib/routes/telegram/scripts/get-telegram-session.mjs b/lib/routes/telegram/scripts/get-telegram-session.mjs new file mode 100644 index 00000000000000..a819073d66fe9d --- /dev/null +++ b/lib/routes/telegram/scripts/get-telegram-session.mjs @@ -0,0 +1,41 @@ +import { TelegramClient } from 'telegram'; +import { StringSession } from 'telegram/sessions/index.js'; +import readline from 'readline'; + +function userInput(question) { + const rl = readline.createInterface({ + input: process.stdin, + output: process.stdout + }); + return new Promise((resolve) => { + rl.question(question, (answer) => { + rl.close(); + resolve(answer); + }); + }); +} + +async function getSessionString() { + const apiId = parseInt(await userInput('Please enter your API ID: ')); + const apiHash = await userInput('Please enter your API Hash: '); + const stringSession = new StringSession(''); + const client = new TelegramClient(stringSession, apiId, apiHash, { + connectionRetries: 5, + }); + await client.start({ + phoneNumber: async () => await userInput('Please enter your phone number: '), + password: async () => await userInput('Please enter your password: '), + phoneCode: async () => await userInput('Please enter the code you received: '), + onError: (err) => console.log(err), + }); + + console.log('You are now connected.'); + const sessionString = client.session.save(); + + console.log('Your session string is:', sessionString); + await client.disconnect(); + return sessionString; +} + +// Run the function +getSessionString().catch(console.error); diff --git a/lib/routes/telegram/tglib/channel.ts b/lib/routes/telegram/tglib/channel.ts index 73864bf364b6f0..d9b85e2f0be8bd 100644 --- a/lib/routes/telegram/tglib/channel.ts +++ b/lib/routes/telegram/tglib/channel.ts @@ -117,6 +117,10 @@ export default async function handler(ctx) { const chat = await client.getInputEntity(ctx.req.param('username')); const channelInfo = await client.getEntity(chat); + if (channelInfo.className !== 'Channel') { + throw new Error(`${ctx.req.param('username')} is not a channel`); + } + let attachments = []; const messages = await client.getMessages(chat, { limit: 50 });