Skip to content

Commit

Permalink
Added the rules command.
Browse files Browse the repository at this point in the history
  • Loading branch information
mleandrojr committed Jul 30, 2024
1 parent 48ed931 commit 4ff1383
Show file tree
Hide file tree
Showing 12 changed files with 268 additions and 8 deletions.
7 changes: 7 additions & 0 deletions sql/update_2024-07-30_01.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
create table chat_rules (
id int(10) unsigned auto_increment not null,
chat_id int(10) unsigned not null,
rules text,
primary key (id),
unique key idx_uq_chat_id (chat_id)
);
2 changes: 1 addition & 1 deletion src/action/Action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export default abstract class Action {
* The constructor.
*
* @author Marcos Leandro
* @since 1.0.0
* @since 2023-06-07
*
* @param context
* @param type
Expand Down
12 changes: 8 additions & 4 deletions src/action/SaveMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export default class SaveMessage extends Action {
* @param context
*/
public constructor(context: Context) {
super(context, "async");
super(context, "sync");
}

/**
Expand All @@ -44,14 +44,18 @@ export default class SaveMessage extends Action {

const contextUser = this.context.newChatMember || this.context.leftChatMember || this.context.user;
const user = await UserHelper.getByTelegramId(contextUser.getId());
const userId = user?.id ?? await UserHelper.createUser(contextUser);

const chat = await ChatHelper.getByTelegramId(this.context.chat.getId());
const chatId = chat?.id ?? await ChatHelper.createChat(this.context.chat);

if (!user || !chat) {
if (!userId) {
Log.save("SaveMessage :: User ID not found " + JSON.stringify(this.context.getPayload()));
return Promise.resolve();
}

if (!user?.id?.length) {
Log.save("User ID not found " + this.context.getPayload());
if (!chatId) {
Log.save("SaveMessage :: Chat ID not found " + JSON.stringify(this.context.getPayload()));
return Promise.resolve();
}

Expand Down
3 changes: 2 additions & 1 deletion src/action/SaveUserAndChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 Log from "../helper/Log.js";

export default class SaveUserAndChat extends Action {

Expand Down Expand Up @@ -45,7 +46,7 @@ export default class SaveUserAndChat extends Action {
const chatId = chat?.id ?? await ChatHelper.createChat(this.context.chat);

if (!userId) {
Log.save("User ID not found " + this.context.getPayload());
Log.save("SaveUserAndChat :: User ID not found " + JSON.stringify(this.context.getPayload()));
return Promise.resolve();
}

Expand Down
215 changes: 215 additions & 0 deletions src/command/Rules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
/**
* Ada Lovelace Telegram Bot
*
* This file is part of Ada Lovelace Telegram Bot.
* You are free to modify and share this project or its files.
*
* @package mslovelace_bot
* @author Marcos Leandro <mleandrojr@yggdrasill.com.br>
* @license GPLv3 <http://www.gnu.org/licenses/gpl-3.0.en.html>
*/

import Command from "./Command.js";
import ChatRules from "../model/ChatRules.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 ChatHelper from "../helper/Chat.js";
import Lang from "../helper/Lang.js";
import Log from "../helper/Log.js";

export default class Rules extends Command {

/**
* Commands list.
*
* @author Marcos Leandro
* @since 2024-07-30
*
* @var {BotCommand[]}
*/
public static readonly commands: BotCommand[] = [
{ command: "rules", description: "Shows the group rules." },
{ command: "addrules", description: "Adds the group rules." },
{ command: "delrules", description: "Deletes the group rules." }
];

/**
* Chat object.
*
* @author Marcos Leandro
* @since 2024-07-30
*/
private chat: Record<string, any>;

/**
* Command context.
*
* @author Marcos Leandro
* @since 2024-07-30
*
* @var {CommandContext}
*/
private command: CommandContext;

/**
* The constructor.
*
* @author Marcos Leandro
* @since 2024-07-30
*
* @param app App instance.
*/
public constructor(context: Context) {
super(context);
}

/**
* Executes the command.
*
* @author Marcos Leandro
* @since 2023-06-07
*
* @param command
*
* @returns
*/
public async run(command: CommandContext): Promise<void> {

if (!await this.context.user.isAdmin()) {
return;
}

const chat = await ChatHelper.getByTelegramId(this.context.chat.getId());
Lang.set(chat.language || "us");

this.command = command;
this.chat = chat;

this.context.message.delete();
switch (this.command.getCommand()) {

case "rules":
return this.rules();

case "addrules":
return this.addrules();

case "delrules":
return this.delrules();
}

return Promise.resolve();
}

/**
* Shows the group rules.
*
* @author Marcos Leandro
* @since 2024-07-30
*/
private async rules(): Promise<void> {

if (!this.chat) {
return this.context.chat.sendMessage(Lang.get("rulesNotFound"));
}

const chatRules = new ChatRules();
chatRules
.select()
.where("chat_id").equal(this.chat.id);

const result = await chatRules.execute();

if (!result.length) {
return this.context.chat.sendMessage(Lang.get("rulesNotFound"));
}

return this.context.chat.sendMessage(result[0].rules, { parseMode: "HTML" });
}

/**
* Adds the group rules.
*
* @author Marcos Leandro
* @since 2024-07-30
*/
private async addrules(): Promise<void> {

const text = this.context.message.getText().split(/\s+/);
if (!text.length || text.length < 2) {
return;
}

const rules = text
.slice(1)
.join(" ")
.replace(/^\\n/, "")
.replace(/\\n$/, "")
.trim();

try {

await this.insertOrUpdateRules(rules);

let message = Lang.get("rulesUpdated");
message += "\n\n" + rules;

this.context.chat.sendMessage(message, { parseMode: "HTML" });

} catch (error: any) {
Log.save(error.message);
}
}

/**
* Deletes the rules.
*
* @author Marcos Leandro
* @since 2024-07-30
*/
private async delrules(): Promise<void> {

const chatRules = new ChatRules();
chatRules
.delete()
.where("chat_id").equal(this.chat.id);

await chatRules.execute();
}

/**
* Inserts or updates the rules.
*
* @author Marcos Leandro
* @since 2024-07-30
*
* @param rules
*/
private async insertOrUpdateRules(rules: string): Promise<void> {

const chatRules = new ChatRules();

chatRules
.select()
.where("chat_id").equal(this.chat.id);

const result = await chatRules.execute();
if (result.length) {

chatRules
.update()
.set("rules", rules)
.where("chat_id").equal(this.chat.id);

return await chatRules.execute();
}

chatRules
.insert()
.set("chat_id", this.chat.id)
.set("rules", rules);

return await chatRules.execute();
}
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
6 changes: 4 additions & 2 deletions src/config/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,12 @@ import Npm from "../command/Npm.js";
import Privacy from "../command/Privacy.js";
import Report from "../command/Report.js";
import Restrict from "../command/Restrict.js";
import Rules from "../command/Rules.js";
import Send from "../command/Send.js";
import Start from "../command/Start.js";
import Unban from "../command/Unban.js";
import Warn from "../command/Warning/Warn.js";
import Warnings from "../command/Warning/Warnings.js";
import Warn from "../command/warning/Warn.js";
import Warnings from "../command/warning/Warnings.js";
import Yarn from "../command/Yarn.js";

export const commands = [
Expand All @@ -45,6 +46,7 @@ export const commands = [
Privacy,
Report,
Restrict,
Rules,
Send,
Start,
Unban,
Expand Down
3 changes: 3 additions & 0 deletions src/lang/br.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,9 @@ export default {
adminOnlyAction: "Esta ação só pode ser executada por administradores.",
adminOnlyActionMessage: "<a href=\"tg://user?id={userid}\">{username}</a> você sabe o que quer dizer \"somente admins\"? O que você pensa que está fazendo?",
reasonUnknown: "Desconhecido",
rulesNotFound: "Não há regras configuradas para este grupo.",
rulesDeleted: "As regras do grupo foram removidas.",
rulesUpdated: "As regras do grupo foram atualizadas.",
privacyPolicy: (() => [
"Olá! Eu sou a Ada Lovelace, um bot pro Telegram. Estou aqui para ajudar, mas antes, é importante que você saiba como trato seus dados.",
"<b>Coleta de Dados:</b> Eu salvo e mantenho apenas dados públicos dos usuários e grupos dos quais faço parte. Isso inclui mensagens enviadas em grupos e informações de perfil público.",
Expand Down
3 changes: 3 additions & 0 deletions src/lang/us.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,9 @@ export default {
adminOnlyAction: "This action can only be performed by admins.",
adminOnlyActionMessage: "<a href=\"tg://user?id={userid}\">{username}</a> do you know what \"admin only\" means? What do you think you're doing?",
reasonUnknown: "Unknown",
rulesNotFound: "There are no rules configured for this group.",
rulesDeleted: "The group rules have been removed.",
rulesUpdated: "The group rules have been updated.",
privacyPolicy: (() => [
"Hello! I'm Ada Lovelace, a Telegram bot. I'm here to help, but first, it's important that you know how I handle your data.",
"<b>Data Collection:</b> I only save and maintain public data from users and groups that I'm a part of. This includes messages sent in groups and public profile information.",
Expand Down
25 changes: 25 additions & 0 deletions src/model/ChatRules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Ada Lovelace Telegram Bot
*
* This file is part of Ada Lovelace Telegram Bot.
* You are free to modify and share this project or its files.
*
* @package mslovelace_bot
* @author Marcos Leandro <mleandrojr@yggdrasill.com.br>
* @license GPLv3 <http://www.gnu.org/licenses/gpl-3.0.en.html>
*/

import DefaultModel from "./Model.js";

export default class Chats extends DefaultModel {

/**
* The constructor.
*
* @author Marcos Leandro
* @since 2024-07-30
*/
public constructor() {
super("chat_rules");
}
}

0 comments on commit 4ff1383

Please sign in to comment.