From 1a48f3297cbd0575753393968e8e634d69e9c533 Mon Sep 17 00:00:00 2001 From: Marcos Leandro Date: Thu, 1 Aug 2024 14:05:16 +0000 Subject: [PATCH 1/5] Node to bun migrations and MySQL library bump. --- package.json | 10 +++------- src/library/telegram/TelegramBotApi.ts | 2 -- src/library/telegram/context/Chat.ts | 7 ++++--- 3 files changed, 7 insertions(+), 12 deletions(-) diff --git a/package.json b/package.json index 573ce72..75bf08f 100644 --- a/package.json +++ b/package.json @@ -5,11 +5,9 @@ "main": "src/index.ts", "type": "module", "scripts": { - "start": "node -r dotenv/config ./dist/index.js", + "start": "bun -r dotenv/config ./dist/index.js", "build": "tsc --project ./", - "watch": "nodemon --watch './**/*.{ts,graphql}' --exec 'npm run watch-arg'", - "watch-arg": "node --loader ts-node/esm -r dotenv/config -r tsconfig-paths/register src/index.ts", - "dev": "tsc-watch --onSuccess \"npm run watch\"" + "watch": "bun --watch ./src/index.ts" }, "repository": { "type": "git", @@ -25,13 +23,11 @@ "dotenv": "^10.0.0", "express": "^4.17.1", "mysql": "^2.18.1", - "mysql2": "^2.3.3", - "node-fetch": "^3.1.0" + "mysql2": "^3.11.0" }, "devDependencies": { "@types/express": "^4.17.13", "@types/mysql": "^2.15.19", - "nodemon": "^2.0.15", "ts-node": "^10.9.1", "tsc-watch": "^4.5.0", "tsconfig-paths": "^3.12.0", diff --git a/src/library/telegram/TelegramBotApi.ts b/src/library/telegram/TelegramBotApi.ts index 5856931..a7167c3 100644 --- a/src/library/telegram/TelegramBotApi.ts +++ b/src/library/telegram/TelegramBotApi.ts @@ -9,8 +9,6 @@ * @license GPLv3 */ -import fetch from "node-fetch"; - export default class TelegramBotApi { /** diff --git a/src/library/telegram/context/Chat.ts b/src/library/telegram/context/Chat.ts index e9a8e89..a33db58 100644 --- a/src/library/telegram/context/Chat.ts +++ b/src/library/telegram/context/Chat.ts @@ -433,7 +433,8 @@ export default class Chat { try { const response = await sendMessage.post(); - return await response.json(); + const json = await response.json(); + return new Message(json.result); } catch (error: any) { Log.save(error.message); @@ -466,8 +467,8 @@ export default class Chat { try { const response = await sendChatAction.post(); - console.log(response); - return await response.json(); + const json = await response.json(); + return new Message(json.result); } catch (error: any) { Log.save(error.message); From 5c56cb32b4d1539940717289a6410a30fcc1fb7a Mon Sep 17 00:00:00 2001 From: Marcos Leandro Date: Thu, 1 Aug 2024 14:11:29 +0000 Subject: [PATCH 2/5] Fixed the chat action bug. --- src/library/telegram/context/Chat.ts | 65 ++++++++++--------- .../telegram/resource/SendChatAction.ts | 4 +- 2 files changed, 35 insertions(+), 34 deletions(-) diff --git a/src/library/telegram/context/Chat.ts b/src/library/telegram/context/Chat.ts index a33db58..8562537 100644 --- a/src/library/telegram/context/Chat.ts +++ b/src/library/telegram/context/Chat.ts @@ -10,6 +10,7 @@ */ import SendMessage from "../resource/SendMessage.js"; +import SendChatAction from "../resource/SendChatAction.js"; import GetChatAdministrators from "../resource/GetChatAdministrators.js"; import Message from "./Message.js"; import { ChatLocation } from "../type/ChatLocation.js"; @@ -46,7 +47,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-05 * - * @returns {number} + * @return {number} */ public getId(): number { return this.context.chat.id; @@ -58,7 +59,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-05 * - * @returns {string} + * @return {string} */ public getType(): string { return this.context.chat.type; @@ -70,7 +71,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-05 * - * @returns {string|undefined} + * @return {string|undefined} */ public getTitle(): string|undefined { return this.context.chat.title; @@ -82,7 +83,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {string|undefined} + * @return {string|undefined} */ public getUsername(): string|undefined { return this.context.chat.username; @@ -94,7 +95,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {string|undefined} + * @return {string|undefined} */ public getFirstName(): string|undefined { return this.context.chat.firstName; @@ -106,7 +107,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {string|undefined} + * @return {string|undefined} */ public getLastName(): string|undefined { return this.context.chat.lastName; @@ -118,7 +119,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {string|undefined} + * @return {string|undefined} */ public getIsForum(): boolean|undefined { return this.context.chat.isForum; @@ -130,7 +131,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {string|undefined} + * @return {string|undefined} */ public getPhoto(): ChatPhoto|undefined { return this.context.chat.photo; @@ -142,7 +143,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {string|undefined} + * @return {string|undefined} */ public getActiveUsernames(): string[]|undefined { return this.context.chat.activeUsernames; @@ -154,7 +155,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {string|undefined} + * @return {string|undefined} */ public getEmojiStatusCustomEmojiId(): string|undefined { return this.context.chat.emojiStatusCustomEmojiId; @@ -166,7 +167,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {string|undefined} + * @return {string|undefined} */ public getBio(): string|undefined { return this.context.chat.bio; @@ -178,7 +179,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {string|undefined} + * @return {string|undefined} */ public getHasPrivateForwards(): boolean|undefined { return this.context.chat.hasPrivateForwards; @@ -190,7 +191,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {boolean|undefined} + * @return {boolean|undefined} */ public getHasRestrictedVoiceAndVideoMessages(): boolean|undefined { return this.context.chat.hasRestrictedVoiceAndVideoMessages; @@ -202,7 +203,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {boolean|undefined} + * @return {boolean|undefined} */ public getJoinToSendMessages(): boolean|undefined { return this.context.chat.joinToSendMessages; @@ -214,7 +215,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {boolean|undefined} + * @return {boolean|undefined} */ public getJoinByRequest(): boolean|undefined { return this.context.chat.joinByRequest; @@ -226,7 +227,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {string|undefined} + * @return {string|undefined} */ public getDescription(): string|undefined { return this.context.chat.description; @@ -238,7 +239,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {string|undefined} + * @return {string|undefined} */ public getInviteLink(): string|undefined { return this.context.chat.inviteLink; @@ -250,7 +251,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {MessageType|undefined} + * @return {MessageType|undefined} */ public getPinnedMessage(): MessageType|undefined { return this.context.chat.pinnedMessage; @@ -262,7 +263,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {ChatPermissions|undefined} + * @return {ChatPermissions|undefined} */ public getPermissions(): ChatPermissions|undefined { return this.context.chat.permissions; @@ -274,7 +275,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {number|undefined} + * @return {number|undefined} */ public getSlowModeDelay(): number|undefined { return this.context.chat.slowModeDelay; @@ -286,7 +287,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {number|undefined} + * @return {number|undefined} */ public getMessageAutoDeleteTime(): number|undefined { return this.context.chat.messageAutoDeleteTime; @@ -298,7 +299,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {boolean|undefined} + * @return {boolean|undefined} */ public getHasAggressiveAntiSpamEnabled(): boolean|undefined { return this.context.chat.hasAggressiveAntiSpamEnabled; @@ -310,7 +311,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {boolean|undefined} + * @return {boolean|undefined} */ public getHasHiddenMembers(): boolean|undefined { return this.context.chat.hasHiddenMembers; @@ -322,7 +323,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {boolean|undefined} + * @return {boolean|undefined} */ public getHasProtectedContent(): boolean|undefined { return this.context.chat.hasProtectedContent; @@ -334,7 +335,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {string|undefined} + * @return {string|undefined} */ public getStickerSetName(): string|undefined { return this.context.chat.stickerSetName; @@ -346,7 +347,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {boolean|undefined} + * @return {boolean|undefined} */ public getCanSetStickerSet(): boolean|undefined { return this.context.chat.canSetStickerSet; @@ -358,7 +359,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {number|undefined} + * @return {number|undefined} */ public getLinkedChatId(): number|undefined { return this.context.chat.linkedChatId; @@ -370,7 +371,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-06 * - * @returns {ChatLocation|undefined} + * @return {ChatLocation|undefined} */ public getLocation(): ChatLocation|undefined { return this.context.chat.location; @@ -382,7 +383,7 @@ export default class Chat { * @author Marcos Leandro * @since 2023-06-05 * - * @returns + * @return {Promise>} */ public async getChatAdministrators(): Promise> { @@ -413,7 +414,7 @@ export default class Chat { * @param text * @param parseMode * - * @returns {Promise} + * @return {Promise} */ public async sendMessage(text: string, options?: Record): Promise { @@ -451,7 +452,7 @@ export default class Chat { * * @param action * - * @returns {Promise} + * @return {Promise} */ public async sendChatAction(action: string): Promise { @@ -461,7 +462,7 @@ export default class Chat { .setAction(action); if (typeof this.context.messageThreadId !== "undefined") { - sendChatAction.setThreadId(this.context.messageThreadId); + sendChatAction.setMessageThreadId(this.context.messageThreadId); } try { diff --git a/src/library/telegram/resource/SendChatAction.ts b/src/library/telegram/resource/SendChatAction.ts index 94714d5..3d208e7 100644 --- a/src/library/telegram/resource/SendChatAction.ts +++ b/src/library/telegram/resource/SendChatAction.ts @@ -56,7 +56,7 @@ export default class SendChatAction extends TelegramBotApi { * * @return {SendChatAction} */ - public messageThreadId(messageThreadId: number): SendChatAction { + public setMessageThreadId(messageThreadId: number): SendChatAction { this.payload.messageThreadId = messageThreadId; return this; } @@ -71,7 +71,7 @@ export default class SendChatAction extends TelegramBotApi { * * @return {SendChatAction} */ - public businessConnectionId(businessConnectionId: String): SendChatAction { + public setBusinessConnectionId(businessConnectionId: String): SendChatAction { this.payload.businessConnectionId = businessConnectionId; return this; } From b96a9b19e1ce2e309e474819f324ab8153015389 Mon Sep 17 00:00:00 2001 From: Marcos Leandro Date: Thu, 8 Aug 2024 16:35:14 +0000 Subject: [PATCH 3/5] Added the message entities parsing. --- src/callback/CaptchaConfirmation.ts | 10 +++++- src/callback/Warning.ts | 1 - src/command/Ban.ts | 14 +++++--- src/command/Rules.ts | 9 ++--- src/command/Send.ts | 11 +++--- src/lang/br.ts | 3 ++ src/lang/us.ts | 3 ++ src/library/telegram/context/Message.ts | 46 ++++++++++++++++++++++++- 8 files changed, 78 insertions(+), 19 deletions(-) diff --git a/src/callback/CaptchaConfirmation.ts b/src/callback/CaptchaConfirmation.ts index eb192c1..734b30d 100644 --- a/src/callback/CaptchaConfirmation.ts +++ b/src/callback/CaptchaConfirmation.ts @@ -14,6 +14,7 @@ import Context from "../library/telegram/context/Context.js"; import UserHelper from "../helper/User.js"; import ChatHelper from "../helper/Chat.js"; import RelUsersChats from "../model/RelUsersChats.js"; +import Lang from "../helper/Lang.js"; import { ChatPermissions } from "../library/telegram/type/ChatPermissions.js"; export default class CaptchaConfirmation extends Callback { @@ -40,7 +41,7 @@ export default class CaptchaConfirmation extends Callback { */ public async run(): Promise { - if (this.context.callbackQuery?.callbackData.d.userId !== this.context.user.getId()) { + if (!this.context.callbackQuery?.callbackData) { return; } @@ -56,6 +57,12 @@ export default class CaptchaConfirmation extends Callback { return; } + Lang.set(chat.language || "us"); + if (this.context.callbackQuery.callbackData.d.userId !== this.context.user.getId()) { + this.context.callbackQuery.answer(Lang.get("captchaNotSameUser")); + return; + } + const relUsersChats = new RelUsersChats(); relUsersChats .update() @@ -83,6 +90,7 @@ export default class CaptchaConfirmation extends Callback { canManageTopics: false }; + this.context.callbackQuery.answer(Lang.get("captchaConfirmed")); await this.context.user.setPermissions(permissions); if (chat.restrict_new_users) { diff --git a/src/callback/Warning.ts b/src/callback/Warning.ts index 9c3afab..1ca3823 100644 --- a/src/callback/Warning.ts +++ b/src/callback/Warning.ts @@ -15,7 +15,6 @@ import Context from "../library/telegram/context/Context.js"; import UserHelper from "../helper/User.js"; import ChatHelper from "../helper/Chat.js"; import Lang from "../helper/Lang.js"; -import { parse } from "dotenv"; export default class Warning extends Callback { diff --git a/src/command/Ban.ts b/src/command/Ban.ts index e44a626..1d0276a 100644 --- a/src/command/Ban.ts +++ b/src/command/Ban.ts @@ -78,7 +78,7 @@ export default class Ban extends Command { let params = command.getParams() || []; const replyToMessage = this.context.message.getReplyToMessage(); - if (replyToMessage && command.command === "delban") { + if (replyToMessage && command.getCommand() === "delban") { replyToMessage.delete(); } @@ -112,10 +112,12 @@ export default class Ban extends Command { */ private async banByReply(replyToMessage: Message, reason: string): Promise { - if (await replyToMessage.getUser().ban()) { - this.saveBan(replyToMessage.getUser(), reason); + if (!await replyToMessage.getUser().ban()) { + const message = Lang.get("banErrorMessage"); + return this.context.chat.sendMessage(message, { parseMode: "HTML" }); } + this.saveBan(replyToMessage.getUser(), reason); return Promise.resolve(); } @@ -129,10 +131,12 @@ export default class Ban extends Command { */ private async banByMention(mention: User, reason: string): Promise { - if (await mention.ban()) { - this.saveBan(mention, reason); + if (!await mention.ban()) { + const message = Lang.get("banErrorMessage"); + return this.context.chat.sendMessage(message, { parseMode: "HTML" }); } + this.saveBan(mention, reason); return Promise.resolve(); } diff --git a/src/command/Rules.ts b/src/command/Rules.ts index 22841a5..10e249c 100644 --- a/src/command/Rules.ts +++ b/src/command/Rules.ts @@ -136,17 +136,12 @@ export default class Rules extends Command { */ private async addrules(): Promise { - const text = this.context.message.getText().split(/\s+/); + const text = this.context.message.getText().replace(`/${this.command.getCommand()}`, "").trim(); if (!text.length || text.length < 2) { return; } - const rules = text - .slice(1) - .join(" ") - .replace(/^\\n/, "") - .replace(/\\n$/, "") - .trim(); + const rules = text.replace(/^\\n/, "").replace(/\\n$/, "").trim(); try { diff --git a/src/command/Send.ts b/src/command/Send.ts index 90f6409..0d765d2 100644 --- a/src/command/Send.ts +++ b/src/command/Send.ts @@ -54,13 +54,16 @@ export default class setCommands extends Command { return; } + const currentCommand = command.getCommand(); + let text = this.context.message.getText(); + text = text.replace(`/${currentCommand}`, "").trim(); + this.context.message.delete(); - const params = command.getParams(); - if (!params || !params.length) { - return; + if (!text.length) { + return Promise.resolve(); } - this.context.chat.sendMessage(params.join(" ")); + this.context.chat.sendMessage(text, { parseMode: "HTML" }); } } diff --git a/src/lang/br.ts b/src/lang/br.ts index 823cbd8..fa04ade 100644 --- a/src/lang/br.ts +++ b/src/lang/br.ts @@ -23,6 +23,7 @@ export default { askToAskLink: "https://dontasktoask.com/pt-br", bannedMessage: "{username} banido.\nMotivo: {reason}", unbannedMessage: "Tudo bem. {username} pode se juntar ao grupo novamente.", + banErrorMessage: "Não foi possível banir o usuário.", adaShieldMessage: "{username} banido.\nMotivo: AdaShield.", casMessage: "{username} banido.\nMotivo: CAS.", adaShieldStatus: "Status do AdaShield: {status}", @@ -30,6 +31,8 @@ export default { textEnabled: "ativado", textDisabled: "desativado", captchaButton: "Pressione aqui para confirmar que não é um robô", + captchaNotSameUser: "Você não deveria tentar confirmar o captcha para outro usuário.", + captchaConfirmed: "Captcha confirmado com sucesso!", emptyGreetingsMessage: "Não existe uma mensagem de boas-vindas configurada.", greetingsMessageDemo: "A mensagem de saudação atual é:\n\n{greetings}", pongMessage: "Esta sou eu!", diff --git a/src/lang/us.ts b/src/lang/us.ts index 55cdc21..0a198ce 100644 --- a/src/lang/us.ts +++ b/src/lang/us.ts @@ -23,6 +23,7 @@ export default { askToAskLink: "https://dontasktoask.com", bannedMessage: "{username} banned.\nReason: {reason}", unbannedMessage: "Alright. {username} can join the group again.", + banErrorMessage: "Couldn't ban the user.", adaShieldMessage: "{username} banned.\nReason: AdaShield banned.", casMessage: "{username} banned.\nReason: CAS banned.", adaShieldStatus: "AdaShield status: {status}", @@ -30,6 +31,8 @@ export default { textEnabled: "enabled", textDisabled: "disabled", captchaButton: "Press here to confirm you are not a robot", + captchaNotSameUser: "You shouldn't try to confirm the captcha for another user.", + captchaConfirmed: "Captcha confirmed successfully!", emptyGreetingsMessage: "There is no greetings message configured.", greetingsMessageDemo: "The current greetings message is:\n\n{greetings}", pongMessage: "Hey! It's me!", diff --git a/src/library/telegram/context/Message.ts b/src/library/telegram/context/Message.ts index 5ff8a8a..815fa07 100644 --- a/src/library/telegram/context/Message.ts +++ b/src/library/telegram/context/Message.ts @@ -216,7 +216,20 @@ export default class Message { * @return {string} */ public getText(): string { - return this.context.text || ""; + + let text = this.context.text || ""; + let entities = this.getEntities(); + + if (!entities.length) { + return text; + } + + for (let i = entities.length - 1; i >= 0; i--) { + const entity = entities[i]; + text = this.addEntity(entity, text); + } + + return text; } /** @@ -610,4 +623,35 @@ export default class Message { return response; } + + private addEntity(entity: Record, message: string): string { + + const entities = { + spoiler: "$1", + blockquote: "
$1
", + code: "$1", + strikethrough: "$1", + underline: "$1", + italic: "$1", + bold: "$1", + text_link: "$1" + }; + + const start = entity.offset; + const end = start + entity.length; + + const prefix = message.substring(0, start); + const content = message.substring(start, end); + const suffix = message.substring(end); + + let tag = entities[entity.type as keyof typeof entities]; + if (!tag) { + return message; + } + + tag = tag.replace("$2", entity.url || ""); + tag = tag.replace("$1", content); + + return `${prefix}${tag}${suffix}`; + } } From b6281542121adc0dad1b136ba6102094768d3cf2 Mon Sep 17 00:00:00 2001 From: Marcos Leandro Date: Thu, 8 Aug 2024 23:36:29 +0000 Subject: [PATCH 4/5] Fixed the rules command types. --- src/command/Rules.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/command/Rules.ts b/src/command/Rules.ts index 10e249c..d1b8640 100644 --- a/src/command/Rules.ts +++ b/src/command/Rules.ts @@ -40,7 +40,7 @@ export default class Rules extends Command { * @author Marcos Leandro * @since 2024-07-30 */ - private chat: Record; + private chat: Record | undefined; /** * Command context. @@ -50,7 +50,7 @@ export default class Rules extends Command { * * @var {CommandContext} */ - private command: CommandContext; + private command: CommandContext | undefined; /** * The constructor. @@ -84,7 +84,7 @@ export default class Rules extends Command { Lang.set(chat?.language || "us"); this.command = command; - this.chat = chat; + this.chat = chat || { id: null }; this.context.message.delete(); switch (this.command.getCommand()) { @@ -136,7 +136,7 @@ export default class Rules extends Command { */ private async addrules(): Promise { - const text = this.context.message.getText().replace(`/${this.command.getCommand()}`, "").trim(); + const text = this.context.message.getText().replace(`/${this.command!.getCommand()}`, "").trim(); if (!text.length || text.length < 2) { return; } @@ -168,7 +168,7 @@ export default class Rules extends Command { const chatRules = new ChatRules(); chatRules .delete() - .where("chat_id").equal(this.chat.id); + .where("chat_id").equal(this.chat!.id); await chatRules.execute(); } @@ -187,7 +187,7 @@ export default class Rules extends Command { chatRules .select() - .where("chat_id").equal(this.chat.id); + .where("chat_id").equal(this.chat!.id); const result = await chatRules.execute(); if (result.length) { @@ -195,14 +195,14 @@ export default class Rules extends Command { chatRules .update() .set("rules", rules) - .where("chat_id").equal(this.chat.id); + .where("chat_id").equal(this.chat!.id); return await chatRules.execute(); } chatRules .insert() - .set("chat_id", this.chat.id) + .set("chat_id", this.chat!.id) .set("rules", rules); return await chatRules.execute(); From b1b713e18ba4b81f73cd0b29b2b40a04ad99cfab Mon Sep 17 00:00:00 2001 From: Marcos Leandro Date: Fri, 9 Aug 2024 15:39:15 +0000 Subject: [PATCH 5/5] Fixed the federation join and ban commands. --- src/command/federation/Ban.ts | 39 +++++++++++++++++++--------- src/command/federation/Federation.ts | 11 +++----- src/command/federation/Group.ts | 39 +++++++++++++++++++++++++++- src/command/federation/Manage.ts | 7 +---- src/command/federation/User.ts | 2 +- src/helper/User.ts | 21 ++++++++++++++- src/lang/br.ts | 1 + src/lang/us.ts | 1 + 8 files changed, 92 insertions(+), 29 deletions(-) diff --git a/src/command/federation/Ban.ts b/src/command/federation/Ban.ts index 11fd778..606ba84 100644 --- a/src/command/federation/Ban.ts +++ b/src/command/federation/Ban.ts @@ -13,7 +13,7 @@ import Federation from "./Federation.js"; import Context from "../../library/telegram/context/Context.js"; import Message from "../../library/telegram/context/Message.js"; import User from "../../library/telegram/context/User.js"; -import { BotCommand } from "../library/telegram/type/BotCommand.js"; +import { BotCommand } from "../../library/telegram/type/BotCommand.js"; import UserHelper from "../../helper/User.js"; import ChatHelper from "../../helper/Chat.js"; import FederationHelper from "../../helper/Federation.js"; @@ -46,16 +46,16 @@ export default class Ban extends Federation { } /** - * Bans an user in the federation. + * Bans an user from the federation. * * @author Marcos Leandro - * @since 2023-07-04 + * @since 2023-08-09 * - * @return + * @return Promise */ private async ban(): Promise { - if (!await this.context.user.isAdmin()) { + if (!this.federation) { return; } @@ -99,7 +99,7 @@ export default class Ban extends Federation { */ private async banByReply(replyToMessage: Message, reason: string): Promise { - const user = UserHelper.getByTelegramId(replyToMessage.getUser().getId()); + const user = await UserHelper.getByTelegramId(replyToMessage.getUser().getId()); const federationChats = await FederationHelper.getChats(this.federation!); for (const chat of federationChats) { @@ -107,6 +107,13 @@ export default class Ban extends Federation { this.saveBan(context, reason); context.user.ban(); } + + const message = Lang.get("fedBannedMessage") + .replace("{userId}", user.user_id) + .replace("{username}", user.first_name || user.username || user.user_id) + .replace("{reason}", reason.length ? reason : "Unknown"); + + this.context.chat.sendMessage(message, { parseMode: "HTML" }); } /** @@ -127,6 +134,13 @@ export default class Ban extends Federation { this.saveBan(context, reason); context.user.ban(); } + + const message = Lang.get("fedBannedMessage") + .replace("{userId}", user.user_id) + .replace("{username}", user.first_name || user.username || user.user_id) + .replace("{reason}", reason.length ? reason : "Unknown"); + + this.context.chat.sendMessage(message, { parseMode: "HTML" }); } /** @@ -150,6 +164,13 @@ export default class Ban extends Federation { this.saveBan(context, reason); context.user.ban(); } + + const message = Lang.get("fedBannedMessage") + .replace("{userId}", user.user_id) + .replace("{username}", user.first_name || user.username || user.user_id) + .replace("{reason}", reason.length ? reason : "Unknown"); + + this.context.chat.sendMessage(message, { parseMode: "HTML" }); } /** @@ -189,12 +210,6 @@ export default class Ban extends Federation { try { await ban.execute(); - const message = Lang.get("fedBannedMessage") - .replace("{userId}", context.user.getId()) - .replace("{username}", context.user.getFirstName() || context.user.getUsername()) - .replace("{reason}", reason.length ? reason : "Unknown"); - - this.context.chat.sendMessage(message, { parseMode: "HTML" }); } catch (err: any) { Log.error(err.toString()); diff --git a/src/command/federation/Federation.ts b/src/command/federation/Federation.ts index 634e1e9..397ca6a 100644 --- a/src/command/federation/Federation.ts +++ b/src/command/federation/Federation.ts @@ -83,17 +83,12 @@ export default class Federation extends Command { return; } - if (!this.chat?.federation_id) { - return; - } + Lang.set(this.chat!.language || "us"); - this.federation = await FederationHelper.getById(Number(this.chat?.federation_id)); - if (!this.federation) { - return; + if (this.chat.federation_id) { + this.federation = await FederationHelper.getById(Number(this.chat?.federation_id)); } - Lang.set(this.chat!.language || "us"); - this.command = command; const action = this.command!.getCommand().substring(1); this[action as keyof typeof Federation.prototype](true as never); diff --git a/src/command/federation/Group.ts b/src/command/federation/Group.ts index 0fc89f8..9340411 100644 --- a/src/command/federation/Group.ts +++ b/src/command/federation/Group.ts @@ -10,12 +10,15 @@ */ import Federation from "./Federation.js"; +import ChatHelper from "../../helper/Chat.js"; import Chats from "../../model/Chats.js"; import Context from "../../library/telegram/context/Context.js"; -import { BotCommand } from "../library/telegram/type/BotCommand.js"; +import CommandContext from "../../library/telegram/context/Command.js"; +import { BotCommand } from "../../library/telegram/type/BotCommand.js"; import FederationsHelper from "../../helper/Federation.js"; import Lang from "../../helper/Lang.js"; import Log from "../../helper/Log.js"; +import UserHelper from "../../helper/User.js"; export default class Group extends Federation { @@ -28,6 +31,7 @@ export default class Group extends Federation { * @var {BotCommand[]} */ public static readonly commands: BotCommand[] = [ + { command: "fshow", description: "Shows the federation information." }, { command: "fjoin", description: "Joins a federation." }, { command: "fleave", description: "Leaves a federation." } ]; @@ -44,6 +48,39 @@ export default class Group extends Federation { super(context); } + /** + * Shows the group federation. + * + * @author Marcos Leandro + * @since 2024-09-09 + * + * @return {Promise} + */ + private async show(): Promise { + + if (this.context.chat.getType() === "private") { + this.context.message.reply(Lang.get("federationCommandOnlyGroupError")); + return; + } + + if (!this.chat?.federation_id) { + this.context.message.reply(Lang.get("federationLeaveNoFederationError")); + return; + } + + const federation = await FederationsHelper.getById(this.chat!.federation_id); + if (!federation) { + this.context.message.reply(Lang.get("federationLeaveNoFederationError")); + return; + } + + const message = Lang.get("federationDetails") + .replace("{federation}", federation.description) + .replace("{hash}", federation.hash); + + this.context.message.reply(message, { parseMode: "HTML" }); + } + /** * Joins a federation. * diff --git a/src/command/federation/Manage.ts b/src/command/federation/Manage.ts index 10c25cc..34357f9 100644 --- a/src/command/federation/Manage.ts +++ b/src/command/federation/Manage.ts @@ -14,7 +14,7 @@ import ChatHelper from "../../helper/Chat.js"; import Chats from "../../model/Chats.js"; import Context from "../../library/telegram/context/Context.js"; import CommandContext from "../../library/telegram/context/Command.js"; -import { BotCommand } from "../library/telegram/type/BotCommand.js"; +import { BotCommand } from "../../library/telegram/type/BotCommand.js"; import FederationHelper from "../../helper/Federation.js"; import Federations from "../../model/Federations.js"; import Lang from "../../helper/Lang.js"; @@ -72,11 +72,6 @@ export default class Manage extends Federation { */ public constructor(context: Context) { super(context); - this.setCommands({ - fcreate : "Creates a federation.", - flist : "List your federations.", - fdelete : "Deletes a federation." - }); } /** diff --git a/src/command/federation/User.ts b/src/command/federation/User.ts index 6fc9481..eead4b5 100644 --- a/src/command/federation/User.ts +++ b/src/command/federation/User.ts @@ -11,7 +11,7 @@ import Federation from "./Federation.js"; import Context from "../../library/telegram/context/Context.js"; -import { BotCommand } from "../library/telegram/type/BotCommand.js"; +import { BotCommand } from "../../library/telegram/type/BotCommand.js"; export default class User extends Federation { diff --git a/src/helper/User.ts b/src/helper/User.ts index dd0353e..18e9b5a 100644 --- a/src/helper/User.ts +++ b/src/helper/User.ts @@ -39,7 +39,26 @@ export default class UserHelper { return user[0]; } - return null; + users + .insert() + .set("user_id", userId) + .set("first_name", null) + .set("last_name", null) + .set("username", null) + .set("language_code", "us") + .set("is_channel", 0) + .set("is_bot", 0) + .set("is_premium", 0); + + try { + + await users.execute(); + return await this.getByTelegramId(userId); + + } catch (err) { + Log.error(err); + return null; + } } /** diff --git a/src/lang/br.ts b/src/lang/br.ts index fa04ade..732f505 100644 --- a/src/lang/br.ts +++ b/src/lang/br.ts @@ -89,6 +89,7 @@ export default { federationDeleteConfirm: "A federação {name} possui {groups} grupos vinculados.\nPara excluir esta federação, envie force como segundo parâmetro.\n\nEx.: /fdelete {hash} force", federationDeleteError: "Ocorreu um erro ao excluir a federação. Por favor, tente novamente mais tarde.", federationDeleteSuccess: "Federação excluída com sucesso!", + federationDetails: "Este grupo faz parte da federação {federation} {hash}.", fedBannedMessage: "{username} banido na federação.\nMotivo: {reason}", fedBanOnlyAdminError: "Somente administradores podem banir usuários da federação.", fedBanAdminError: "Você não pode banir administradores da federação.", diff --git a/src/lang/us.ts b/src/lang/us.ts index 0a198ce..d0995a7 100644 --- a/src/lang/us.ts +++ b/src/lang/us.ts @@ -89,6 +89,7 @@ export default { federationDeleteConfirm: "The federation {name} has {groups} attached groups.\nTo delete it, send force as the second parameter.\n\n/fdelete {hash} force", federationDeleteError: "An error occurred while deleting the federation. Please try again later.", federationDeleteSuccess: "The federation has been successfully deleted.", + federationDetails: "This group is part of the federation {federation} {hash}.", fedBannedMessage: "{username} banned in federation.\nReason: {reason}", fedBanOnlyAdminError: "Only admins can ban users in a federation.", fedBanAdminError: "You can't ban admins in a federation.",