Skip to content

Commit ccc9b5a

Browse files
committed
Переписать на puregram
1 parent 1c6ccf6 commit ccc9b5a

File tree

5 files changed

+27
-29
lines changed

5 files changed

+27
-29
lines changed

apps/api/package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,9 @@
2424
"elysia-helmet": "^2.0.0",
2525
"ky": "^1.7.2",
2626
"node-rsa": "^1.1.1",
27-
"node-telegram-bot-api": "^0.66.0",
2827
"pg": "^8.13.1",
2928
"pg-hstore": "^2.3.4",
29+
"puregram": "^2.26.8",
3030
"rand-token": "^1.0.1",
3131
"sequelize": "^6.37.5",
3232
"sequelize-simple-cache": "^1.3.5"

apps/api/src/worker/notificator/bot/botLogic/registerLogic.ts

+16-21
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,27 @@
11
// @ts-ignore
22
import { b64 } from '@diary-spo/crypto'
3-
import type TelegramBot from 'node-telegram-bot-api'
43
import { AuthModel } from '../../../../models/Auth'
54
import { DiaryUserModel } from '../../../../models/DiaryUser'
65
import { SubscribeModel } from '../../../../models/Subscribe'
76
import { INTERVAL_RUN } from '../../config'
7+
import {Telegram} from "puregram";
88

9-
export const registerLogic = (bot: TelegramBot | null) => {
9+
export const registerLogic = (bot: Telegram | null) => {
1010
if (!bot) return
11-
bot.on('message', async (msg) => {
11+
bot.updates.on('message', async (msg) => {
1212
const chatId = msg.chat.id
1313

14-
if (!msg.text) bot.sendMessage(chatId, 'Такое сообщение не поддерживается')
14+
if (!msg.text) {
15+
msg.reply('Такое сообщение не поддерживается')
16+
return
17+
}
1518

1619
const command = (msg.text ?? '').split(' ')
1720

1821
switch (command[0]) {
1922
case '/subscribe': {
2023
if (command.length < 2) {
21-
bot.sendMessage(
22-
chatId,
24+
msg.reply(
2325
'Передайте вторым параметром актуальный токен, чтобы подписаться на уведомления'
2426
)
2527
return
@@ -30,17 +32,15 @@ export const registerLogic = (bot: TelegramBot | null) => {
3032
try {
3133
tokenSecure = atob(command[1])
3234
} catch {
33-
bot.sendMessage(
34-
chatId,
35+
msg.reply(
3536
'Вы что-то не то шлёте и всё ломаете. В бан захотели?'
3637
)
3738
return
3839
}
3940
const secureTokenParams = tokenSecure.split(':')
4041

4142
if (secureTokenParams.length !== 2 && !Number(secureTokenParams[0])) {
42-
bot.sendMessage(
43-
chatId,
43+
msg.reply(
4444
'У вашего токена неверная структура. В бан захотел(-а)?'
4545
)
4646
return
@@ -53,7 +53,7 @@ export const registerLogic = (bot: TelegramBot | null) => {
5353
})
5454

5555
if (!auth) {
56-
bot.sendMessage(chatId, 'Переданная авторизация не найдена ...')
56+
msg.reply('Переданная авторизация не найдена ...')
5757
return
5858
}
5959

@@ -65,8 +65,7 @@ export const registerLogic = (bot: TelegramBot | null) => {
6565
const secureToken = await b64(JSON.stringify(tokenObject))
6666

6767
if (secureToken !== secureTokenParams[1]) {
68-
bot.sendMessage(
69-
chatId,
68+
msg.reply(
7069
`Ваш токен какой-то не такой. Если вы ничего не трогали, то проблема у нас.\nПожалуйста, покажите это сообщение разработчикам.\nDebug info: ${btoa(
7170
JSON.stringify({
7271
tokenSecure,
@@ -84,8 +83,7 @@ export const registerLogic = (bot: TelegramBot | null) => {
8483
})
8584

8685
if (subscribes.length >= 1) {
87-
bot.sendMessage(
88-
chatId,
86+
msg.reply(
8987
'Вы уже подписаны на уведомления. Сначала отпишитесь (/unsubscribe)'
9088
)
9189
return
@@ -103,8 +101,7 @@ export const registerLogic = (bot: TelegramBot | null) => {
103101
}
104102
})
105103

106-
bot.sendMessage(
107-
chatId,
104+
msg.reply(
108105
`<b><i>${user?.firstName} ${user?.lastName}!</i></b> Вы успешно подписались на уведомления.\nПрежде чем Вы начнёте получать уведомления, нам нужно извлечь все ваши оценки (это просиходит примерно каждые <b>${INTERVAL_RUN} секунд</b>).\nПо окончанию подготовительных процедур, мы уведомим Вас о готовности принимать уведомления.\nСпасибо, что выбираете нас!`,
109106
{ parse_mode: 'HTML' }
110107
)
@@ -116,14 +113,12 @@ export const registerLogic = (bot: TelegramBot | null) => {
116113
tgId: chatId
117114
}
118115
})
119-
bot.sendMessage(
120-
chatId,
116+
msg.reply(
121117
'Вы успешно отписались от всех аккаунтов. Можете привязать новый (/subscribe)'
122118
)
123119
break
124120
default:
125-
bot.sendMessage(
126-
chatId,
121+
msg.reply(
127122
'Этой команды нету, но есть такие:' +
128123
'\n/subscribe <code>[token]</code> — подписаться на уведомления по токену' +
129124
'\n/unsubscribe — отписаться от уведомлений',
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
import { BOT_TOKEN } from '@config'
2-
import TelegramBot from 'node-telegram-bot-api'
32
import { registerLogic } from './registerLogic'
3+
import {Telegram} from "puregram";
44

55
const token = BOT_TOKEN
66

77
export const bot =
88
Bun.main.includes('main.ts') || token === 'IGNORE'
99
? null
10-
: new TelegramBot(token, { polling: true })
10+
: Telegram.fromToken(token)
1111

12-
if (bot) registerLogic(bot)
12+
if (bot) {
13+
registerLogic(bot)
14+
bot.updates.startPolling()
15+
}

apps/api/src/worker/notificator/index.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,10 @@ export const notificatorChecker = async (): Promise<void> => {
3838
if (!bot) return
3939
subscribe.preActionsIsSuccess = true
4040
subscribe.save()
41-
bot.sendMessage(
42-
String(subscribe.tgId),
43-
'Мы загрузили ваши оценки. Теперь вы будете получать уведомления!'
44-
)
41+
bot.api.sendMessage({
42+
chat_id: String(subscribe.tgId),
43+
text: 'Мы загрузили ваши оценки. Теперь вы будете получать уведомления!'
44+
})
4545
})
4646
continue
4747
}

bun.lockb

-52.4 KB
Binary file not shown.

0 commit comments

Comments
 (0)