Skip to content

Commit

Permalink
feat(route/telegram): add telegram session scripts and logics
Browse files Browse the repository at this point in the history
  • Loading branch information
pseudoyu committed Oct 27, 2024
1 parent 5e7fc99 commit 26bc26a
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 4 deletions.
1 change: 1 addition & 0 deletions lib/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,7 @@ export type Config = {
};
telegram: {
token?: string;
session?: string;
};
tophub: {
cookie?: string;
Expand Down
17 changes: 13 additions & 4 deletions lib/routes/telegram/channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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;

This comment has been minimized.

Copy link
@black-roland

black-roland Oct 31, 2024

Is it reversing the logic? 🤔

Was: use tglib if no routeParams are defined and session is defined.
Now: use tglig if routeParams are defined and session is defined.

I'm just making sure there are no unexpected bugs. Please correct me if I'm wrong.

This comment has been minimized.

Copy link
@black-roland

This comment has been minimized.

Copy link
@pseudoyu

pseudoyu Oct 31, 2024

Author Collaborator

yes, my mistake. Thank you for your feedback!

This comment has been minimized.

Copy link
@pseudoyu

pseudoyu Oct 31, 2024

Author Collaborator

Fixed now.

This comment has been minimized.

Copy link
@black-roland

black-roland Oct 31, 2024

That was quick! Thanks!

This comment has been minimized.

Copy link
@pseudoyu

pseudoyu Oct 31, 2024

Author Collaborator

Oh i made another change. tglib uses Telegram session, however it has very strict restrictions and may occur AuthKeyDuplicatedError (refer to LonamiWebs/Telethon#1488). So i consider only use it as fallback.

if (!useWeb) {
if (ctx.req.param('routeParams') && config.telegram.session) {
return tglibchannel(ctx);
}

Expand Down Expand Up @@ -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}`);
}

Expand Down
41 changes: 41 additions & 0 deletions lib/routes/telegram/scripts/get-telegram-session.mjs
Original file line number Diff line number Diff line change
@@ -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),

This comment has been minimized.

Copy link
@CaoMeiYouRen

CaoMeiYouRen Nov 2, 2024

Contributor

@pseudoyu Please remove console.log to comply with the eslint rule no-console.

This comment has been minimized.

Copy link
@pseudoyu

pseudoyu Nov 2, 2024

Author Collaborator

okay! Thank you~

});

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);
4 changes: 4 additions & 0 deletions lib/routes/telegram/tglib/channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });

Expand Down

0 comments on commit 26bc26a

Please sign in to comment.