Skip to content

Commit

Permalink
fix multiple requests processing issue
Browse files Browse the repository at this point in the history
  • Loading branch information
chupapee committed Jul 14, 2023
1 parent 4a9edaf commit 088af0a
Show file tree
Hide file tree
Showing 17 changed files with 101 additions and 45 deletions.
4 changes: 3 additions & 1 deletion src/entities/twitter/api/twitterApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import { TweetJson } from '../model';

const API_JSON_DATA = 'https://twitter.com/i/api/graphql';

export const getPage = async (twitterLink: string): Promise<TweetJson> => {
export const getPage = async (
twitterLink: string
): Promise<TweetJson | undefined> => {
try {
const browser = await puppeteer.launch({
executablePath: puppeteerExecutablePath,
Expand Down
1 change: 1 addition & 0 deletions src/features/bot/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './processMessages';
33 changes: 33 additions & 0 deletions src/features/bot/processMessages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { IContextBot } from '../../shared/config';

export const addMsgToRemoveList = (messageId: number, ctx: IContextBot) => {
const user = ctx.from!;
if (!ctx.session.usersList) {
ctx.session.usersList = [{ ...user, messagesToRemove: [messageId] }];
return;
}

const oldU = ctx.session.usersList.find((u) => u.id === user.id);
if (oldU) {
oldU.messagesToRemove.push(messageId);
}
};

const getMsgToRemoveList = (ctx: IContextBot) => {
const msgToRemoveList = ctx.session.usersList?.find(
(u) => u.id === ctx.from?.id
)?.messagesToRemove;
return msgToRemoveList ?? [];
};

export const removeTempMessages = (ctx: IContextBot) => {
const msgIdList = getMsgToRemoveList(ctx);
const chatId = ctx.chat?.id;
if (msgIdList.length > 0 && chatId) {
for (const msgId of msgIdList) {
ctx.telegram
.deleteMessage(chatId, msgId)
.catch((error) => console.error(error));
}
}
};
2 changes: 0 additions & 2 deletions src/features/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1 @@
export { onBotUp } from './onBotUp';
export { onServiceFinish } from './onServiceFinish';
export { onServiceInit } from './onServiceInit';
12 changes: 6 additions & 6 deletions src/features/onBotUp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,19 @@ export const onBotUp = async () => {
try {
const dbUsers = await getUsers();
await timeout(500);
if (dbUsers && !dbUsers?.socialBotUpFlag) {
if (dbUsers && !dbUsers.socialBotUpFlag) {
const users = [
...dbUsers?.insta,
...dbUsers?.twitter,
...dbUsers?.tiktok,
...dbUsers?.you,
...dbUsers.insta,
...dbUsers.twitter,
...dbUsers.tiktok,
...dbUsers.you,
].filter((v, i, a) => a.findIndex((v2) => v2.id === v.id) === i); // unique users only;

for (const user of users) {
try {
await bot.telegram.sendMessage(
user.id as number,
i18n.t(user.language_code ?? 'en', 'botWokeUp'),
i18n.t(user.language_code ?? 'en', 'botUpText'),
{ parse_mode: 'Markdown' }
);
await timeout(500);
Expand Down
2 changes: 2 additions & 0 deletions src/features/scenes/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { onServiceFinish } from './onServiceFinish';
export { onServiceInit } from './onServiceInit';
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { SocialMediaType } from '../entities/storage';
import { BOT_ADMIN_ID, IContextBot } from '../shared/config';
import { notifyAdmin } from '../shared/notifyAdmin';
import { saveServiceFinisher } from './storage';
import { SocialMediaType } from '../../entities/storage';
import { BOT_ADMIN_ID, IContextBot } from '../../shared/config';
import { notifyAdmin } from '../../shared/notifyAdmin';
import { removeTempMessages } from '../bot';
import { saveServiceFinisher } from '../storage';

interface OnServiceInitArgs {
ctx: IContextBot;
Expand Down Expand Up @@ -30,4 +31,6 @@ export const onServiceFinish = ({
saveServiceFinisher(user, socialMediaType);
}
}
ctx.scene.leave();
removeTempMessages(ctx);
};
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { SocialMediaType } from '../entities/storage';
import { BOT_ADMIN_ID, IContextBot } from '../shared/config';
import { notifyAdmin } from '../shared/notifyAdmin';
import { saveServiceInitiator } from './storage';
import { SocialMediaType } from '../../entities/storage';
import { BOT_ADMIN_ID, IContextBot } from '../../shared/config';
import { notifyAdmin } from '../../shared/notifyAdmin';
import { saveServiceInitiator } from '../storage';

interface OnServiceInitArgs {
ctx: IContextBot;
Expand Down
4 changes: 0 additions & 4 deletions src/getScenesData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,18 @@ export const getScenesData = () => {
return [
{
urls: YOUTUBE_URL,
reply: 'preparingVideo',
scene: youtubeScene.id,
},
{
urls: [TWITTER_URL],
reply: 'preparingLink',
scene: twitterScene.id,
},
{
urls: [INSTAGRAM_URL],
reply: 'preparingLink',
scene: instagramScene.id,
},
{
urls: [TIKTOK_URL],
reply: 'preparingVideo',
scene: tiktokScene.id,
},
];
Expand Down
35 changes: 27 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Scenes, session, Telegraf } from 'telegraf';

import { onBotUp } from './features';
import { addMsgToRemoveList } from './features/bot';
// import { onBotUp } from './features';
import { getScenesData } from './getScenesData';
import { feedbackScene } from './scenes/feedback';
import { instagramScene } from './scenes/instagram';
Expand All @@ -27,11 +28,7 @@ bot.catch((error) => {
console.error(error, 'INDEX.TS');
});

onBotUp();

bot.start(async (ctx) => {
await ctx.reply(ctx.i18n.t('start', { userId: ctx.from.id }));
});
// onBotUp();

const lang = {
ru: '🇷🇺 Язык изменен на русский!',
Expand All @@ -52,6 +49,24 @@ bot.command('feedback', async (ctx) => {
await ctx.scene.enter(feedbackScene.id);
});

bot.use(async (ctx, next) => {
/** While the user is in a certain scene,
* new commands are not processed */
const isStarted = ctx.state.isStarted;
const isRunning = ctx.scene.current;

if (!isStarted && isRunning) {
const { message_id } = await ctx.reply(ctx.i18n.t('pleaseWait'));
addMsgToRemoveList(message_id, ctx);
return;
}
return next();
});

bot.start(async (ctx) => {
await ctx.reply(ctx.i18n.t('start', { userId: ctx.from.id }));
});

bot.on('message', async (ctx) => {
const handleMessage = async () => {
if ('text' in ctx.message) {
Expand All @@ -62,8 +77,12 @@ bot.on('message', async (ctx) => {
urls.some((url) => link.includes(url))
);
if (selectedAction) {
const { scene, reply } = selectedAction;
await ctx.reply(ctx.i18n.t(reply));
ctx.state.isStarted = true;
const { scene } = selectedAction;
const { message_id } = await ctx.reply(
ctx.i18n.t('processingLink')
);
addMsgToRemoveList(message_id, ctx);
await ctx.scene.enter(scene);
} else await ctx.reply(ctx.i18n.t('invalidLink'));
}
Expand Down
2 changes: 1 addition & 1 deletion src/scenes/instagram/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Scenes } from 'telegraf';

import { getPage, parsePage } from '../../entities/instagram';
import { onServiceFinish, onServiceInit } from '../../features';
import {
sendFewVideos,
sendManyFiles,
sendSingleFile,
} from '../../features/instagram';
import { onServiceFinish, onServiceInit } from '../../features/scenes';
import { IContextBot } from '../../shared/config';

export const instagramScene = new Scenes.BaseScene<IContextBot>(
Expand Down
2 changes: 1 addition & 1 deletion src/scenes/tiktok/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Scenes } from 'telegraf';

import { getPage, parsePage } from '../../entities/tiktok';
import { onServiceFinish, onServiceInit } from '../../features';
import { onServiceFinish, onServiceInit } from '../../features/scenes';
import { IContextBot } from '../../shared/config';
import { calcLinkSize, retryGettingPage } from '../../shared/utils';

Expand Down
2 changes: 1 addition & 1 deletion src/scenes/twitter/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
getPage,
processTweetJson,
} from '../../entities/twitter';
import { onServiceFinish, onServiceInit } from '../../features';
import { onServiceFinish, onServiceInit } from '../../features/scenes';
import { IContextBot } from '../../shared/config';

const ACTION_ID = 'action';
Expand Down
2 changes: 1 addition & 1 deletion src/scenes/youtube/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
getPage,
parsePage,
} from '../../entities/youtube';
import { onServiceFinish, onServiceInit } from '../../features';
import { onServiceFinish, onServiceInit } from '../../features/scenes';
import { IContextBot } from '../../shared/config';
import { retryGettingPage } from '../../shared/utils';

Expand Down
7 changes: 4 additions & 3 deletions src/shared/config/context.interface.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { Context, Scenes } from 'telegraf';
import { User } from 'typegram';

export interface UserSessionData {
userId: number;
export interface UserSession extends User {
messagesToRemove: number[];
}

interface SceneSession extends Scenes.SceneSession {
data: UserSessionData[];
usersList: UserSession[] | undefined;
}

export interface IContextBot extends Context {
Expand Down
9 changes: 5 additions & 4 deletions src/shared/config/locales/en.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"//start_command": "",
"start": "🔗 Please send the link",
"preparingVideo": "⏳ Preparing the video, it will take no more than a minute",
"preparingLink": "⏳ Processing the link, it will take no more than a minute",
"processingLink": "⏳ Processing the link, it will take no more than a minute",
"invalidLink": "🚫 Please send a valid link.",
"pleaseWait": "⚡️ Your request is being processed\n⌛️ Please be patient",

"//insta_scene": "",
"downloadAll": "📥 Download all",
Expand Down Expand Up @@ -36,6 +36,7 @@
"uploadingMedia": "📤 Uploading to Telegram...",
"uploadingVideo": "📤 Uploading the video to Telegram...",
"savedByBot": "📤 Saved by: @insta_twitter_youtube_bot",
"botWokeUpTechIssues": "Hey! 👋\nTechnical issues have been resolved 🛠✅\nYou can use the bot again 🚀",
"botWokeUp": "⚡️ ***Update*** ⚡️\n\n💡 Added support for ***TikTok links!***\n🛠 Additionally, minor bugs with Twitter links have been fixed. You can try re-uploading the links that had errors"

"botUpTechIssues": "Hey! 👋\nTechnical issues have been resolved 🛠✅\nYou can use the bot again 🚀",
"botUpText": "⚡️ ***Update*** ⚡️\n\n💡 Added support for ***TikTok links!***\n🛠 Additionally, minor bugs with Twitter links have been fixed. You can try re-uploading the links that had errors"
}
10 changes: 5 additions & 5 deletions src/shared/config/locales/ru.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"//start-command": "",
"start": "🔗 Отправьте ссылку",
"preparingVideo": "Подготавливаем видео, это займёт не больше минуты",
"preparingLink": "⏳ Обработка ссылки, это займёт не больше минуты",
"invalidLink": "🚫 Отправьте корректную ссылку.",
"processingLink": "Обработываем ссылку, это займёт не больше минуты",
"pleaseWait": "⚡️ Ваш запрос обрабатывается\n⌛️ Пожалуйста, подождите",
"invalidLink": "🚫 Отправьте корректную ссылку",

"//insta-scene": "",
"downloadAll": "📥 Скачать все",
Expand Down Expand Up @@ -35,6 +35,6 @@
"uploadingVideo": "📤 Загружаем видео в телеграм...",
"savedByBot": "📤 Загружено при помощи: @insta_twitter_youtube_bot",
"chooseQuality": "🎥 Выберите разрешение:",
"botWokeUpTechIssues": "Привет! 👋\nТехнические неполадки разрешены 🛠✅\nМожете вновь пользоваться ботом 🚀",
"botWokeUp": "⚡️ ***Обновление*** ⚡️\n\n💡 Теперь поддерживаются ***ссылки с TikTok***!\n🛠 Также исправлены незначительные баги со ссылками с twitter, можете попробовать загрузить заново ссылки с ошибками"
"botUpTechIssues": "Привет! 👋\nТехнические неполадки разрешены 🛠✅\nМожете вновь пользоваться ботом 🚀",
"botUpText": "⚡️ ***Обновление*** ⚡️\n\n💡 Теперь поддерживаются ***ссылки с TikTok***!\n🛠 Также исправлены незначительные баги со ссылками с twitter, можете попробовать загрузить заново ссылки с ошибками"
}

0 comments on commit 088af0a

Please sign in to comment.