fix
Deploy app frontend / app frontend (push) Successful in 2m40s
Deploy db-migrations / db-migrations (push) Successful in 1m8s
Deploy service message-delivery-method-web-push / service message-delivery-method-web-push (push) Successful in 1m30s
Deploy service tg-bot / service tg-bot (push) Failing after 1m51s
Deploy app frontend / app frontend (push) Successful in 2m40s
Deploy db-migrations / db-migrations (push) Successful in 1m8s
Deploy service message-delivery-method-web-push / service message-delivery-method-web-push (push) Successful in 1m30s
Deploy service tg-bot / service tg-bot (push) Failing after 1m51s
This commit is contained in:
@@ -4,6 +4,7 @@ import { MyContext } from "../types/myContext";
|
||||
import { env } from "../config/env";
|
||||
import { CouchDBStorageAdapter } from "./storageAdapters/CouchDBStorageAdapter";
|
||||
import { loadUserMiddleware } from "./middleware/loadUser";
|
||||
import { replayToQrCodeMessageMiddleware } from "./middleware/replayToQrCodeMessageMiddleware";
|
||||
import { tgBotSessionsDb } from "../dbs";
|
||||
import { startCommand } from "./commands/start";
|
||||
import { helpCommand } from "./commands/help";
|
||||
@@ -39,13 +40,16 @@ export const createBot = ({
|
||||
// Подключаем сессии. По необходимости определите initial state для сессии
|
||||
bot.use(session({ storage, initial: () => ({}) }));
|
||||
|
||||
// Middleware для загрузки или создания пользователя
|
||||
bot.use(loadUserMiddleware);
|
||||
|
||||
// Middleware для обработки ответов на сообщения
|
||||
bot.use(replayToQrCodeMessageMiddleware);
|
||||
|
||||
// Подключаем conversations для многошаговых сценариев
|
||||
bot.use(conversations());
|
||||
bot.use(createConversation(newQRCodeConversation));
|
||||
|
||||
// Middleware для загрузки или создания пользователя
|
||||
bot.use(loadUserMiddleware);
|
||||
|
||||
// Регистрация команд
|
||||
bot.command("start", startCommand);
|
||||
bot.command("help", helpCommand);
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { MyContext } from "../../types/myContext";
|
||||
import { qrDb, messagesDb } from "../../dbs";
|
||||
import type { MessageDocument } from "@hereconnect/types";
|
||||
import { secondsToISOString } from "../../utils/date";
|
||||
|
||||
/**
|
||||
* Middleware for handling replies to messages containing QR code identifiers.
|
||||
*
|
||||
* This middleware checks if a received message is a reply to another message
|
||||
* containing a specific pattern with QR code and chat identifiers. If the
|
||||
* pattern is found, it logs and processes the identifiers and sends a reply
|
||||
* acknowledging the response. If the pattern is not found or if the message
|
||||
* is not a reply, appropriate logs and responses are generated.
|
||||
*
|
||||
* @param ctx - The context object containing the message and other request details.
|
||||
* @param next - The next middleware function in the stack to be executed.
|
||||
*/
|
||||
export const replayToQrCodeMessageMiddleware = async (
|
||||
ctx: MyContext,
|
||||
next: () => Promise<void>,
|
||||
) => {
|
||||
if (!ctx.has(":text")) {
|
||||
return next();
|
||||
}
|
||||
if (!ctx.msg.reply_to_message) {
|
||||
console.log("Это не ответное сообщение.");
|
||||
return next();
|
||||
}
|
||||
|
||||
// Получаем текст сообщения, на которое пришёл ответ
|
||||
const originalMessage = ctx.msg.reply_to_message.text;
|
||||
|
||||
const m = originalMessage?.match(/#qr(?<qr_code_uri>\S+)_c(?<chat>\S+)/);
|
||||
if (!m?.groups) {
|
||||
console.log("m.groups is empty", m, m?.groups);
|
||||
await ctx.reply(
|
||||
`Я не смогу обработать это сообщение.\nВыберете в телеграм ответить у любого сообщения QR-кода чтобы я его мог переслать в диалог.`,
|
||||
);
|
||||
return next();
|
||||
}
|
||||
|
||||
const { qr_code_uri, chat } = m.groups;
|
||||
console.log(qr_code_uri, chat);
|
||||
|
||||
// Логируем исходное сообщение и ответ
|
||||
console.log("Ответ на сообщение: ", originalMessage);
|
||||
console.log("Ответное сообщение: ", ctx.msg.text);
|
||||
|
||||
const qrCodeDoc = await qrDb.get(`qr_code:${qr_code_uri}`).catch((error) => {
|
||||
if (error.name === "not_found") return;
|
||||
throw error;
|
||||
});
|
||||
|
||||
if (!qrCodeDoc) {
|
||||
await ctx.reply(
|
||||
`Я не смогу обработать это сообщение. QR-код с ID ${qr_code_uri} не найден.`,
|
||||
);
|
||||
return next();
|
||||
}
|
||||
|
||||
if (!ctx.userDoc) {
|
||||
await ctx.reply(`Я не смогу обработать это сообщение. Вы не авторизованы`);
|
||||
return next();
|
||||
}
|
||||
|
||||
console.log(ctx.userDoc?.telegram_id, "!==", qrCodeDoc.telegram_id);
|
||||
|
||||
if (ctx.userDoc?.telegram_id !== qrCodeDoc.telegram_id) {
|
||||
await ctx.reply(`Я не смогу обработать это сообщение. Это не ваш QR-код`);
|
||||
return next();
|
||||
}
|
||||
|
||||
const created_at = secondsToISOString(ctx.msg.date);
|
||||
const user_uuid = ctx.userDoc!.user_uuid;
|
||||
const message: MessageDocument = {
|
||||
_id: `message:${qr_code_uri}:${chat}:${created_at}`,
|
||||
type: "message",
|
||||
qr_code_uri,
|
||||
chat,
|
||||
from: "owner",
|
||||
body: ctx.msg.text.trim(),
|
||||
user_uuid,
|
||||
created_at,
|
||||
};
|
||||
|
||||
await messagesDb.put(message);
|
||||
|
||||
// Вы можете выполнить любую логику с этими данными
|
||||
await ctx.reply(
|
||||
`Вы ответили на сообщение: "${originalMessage}" с текстом: "${ctx.msg.text}"`,
|
||||
);
|
||||
};
|
||||
@@ -3,11 +3,10 @@ import { ServiceSeqTrackerDatabase } from "@hereconnect/lib-service-seq-tracker"
|
||||
|
||||
import type {
|
||||
QRCodeDocument,
|
||||
MessageDeliveryMethodWebPushVapid,
|
||||
UserChatSettingsDocument,
|
||||
WebPushSubscriptionDocument,
|
||||
PublicSettingsDocument,
|
||||
UserDocument,
|
||||
MessageDocument,
|
||||
} from "@hereconnect/types";
|
||||
|
||||
import type { ServiceSeqTrackerDocument } from "@hereconnect/lib-service-seq-tracker";
|
||||
@@ -26,17 +25,11 @@ export const MESSAGES_DB_NAME = "messages";
|
||||
export const TG_BOT_DB_URL = `${env.API_URL}/${TG_BOT_DB_NAME}`;
|
||||
export const MESSAGES_DB_URL = `${env.API_URL}/${MESSAGES_DB_NAME}`;
|
||||
|
||||
export const messagesDb = new PouchDB<MessageDocument>(MESSAGES_DB_URL, {
|
||||
skip_setup: true,
|
||||
});
|
||||
export const messagesServiceSeqTrackerDb =
|
||||
new PouchDB<ServiceSeqTrackerDocument>(MESSAGES_DB_URL, {
|
||||
skip_setup: true,
|
||||
});
|
||||
|
||||
export const serverSettingsDb = new PouchDB<MessageDeliveryMethodWebPushVapid>(
|
||||
`${env.API_URL}/server_settings`,
|
||||
{
|
||||
skip_setup: true,
|
||||
},
|
||||
);
|
||||
messagesDb satisfies PouchDB.Database as unknown as PouchDB.Database<ServiceSeqTrackerDocument>;
|
||||
|
||||
export const publicSettingsDb = new PouchDB<PublicSettingsDocument>(
|
||||
`${env.API_URL}/public_settings`,
|
||||
@@ -75,7 +68,6 @@ export const usersDb = new PouchDB<UserDocument>(`${env.API_URL}/_users`, {
|
||||
|
||||
const checkDatabases = async () => {
|
||||
const databases = {
|
||||
serverSettingsDb,
|
||||
publicSettingsDb,
|
||||
qrDb,
|
||||
usersDb,
|
||||
|
||||
@@ -53,7 +53,7 @@ async function handleChange(msgDoc: MessageDocument, bot: Bot<MyContext>) {
|
||||
console.log(`sending to ${telegramUsersDocs.length} telegram accounts`);
|
||||
}
|
||||
|
||||
const hashTag = `#qr_${qrDoc.uri}_c${msgDoc.chat}`;
|
||||
const hashTag = `#qr${qrDoc.uri}_c${msgDoc.chat}`;
|
||||
const manageMessageUrl = `${env.APP_BASE_URL}/manage/qr/${qrDoc.uri}/chat/${msgDoc.chat}#message-${encodeURIComponent(msgDoc.created_at)}`;
|
||||
// const manageMessageUrl = `tg://resolve?domain=${bot.botInfo.username}&start=message:${qrDoc.uri}:${msgDoc.created_at}`;
|
||||
// const msgCaption = ` — ${link("сообщение", manageMessageUrl)} QR-кода «${qrDoc.name}»`;
|
||||
|
||||
@@ -2,3 +2,11 @@
|
||||
export function getIsoDate(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
export function secondsToISOString(seconds: number): string {
|
||||
// Преобразуем секунды в миллисекунды
|
||||
const milliseconds = seconds * 1000;
|
||||
|
||||
// Создаем объект Date и преобразуем в ISOString
|
||||
return new Date(milliseconds).toISOString();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user