Skip to content

Commit

Permalink
fix(database): Update retryConnect method to handle promise return ty…
Browse files Browse the repository at this point in the history
…pe and add error logging
  • Loading branch information
m-mdy-m committed Dec 18, 2024
1 parent 04a7af7 commit 13d2b79
Show file tree
Hide file tree
Showing 13 changed files with 172 additions and 36 deletions.
15 changes: 13 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
"version": "4.1.0",
"description": "A Telegram bot for managing Telegram groups efficiently.",
"main": "/src/app.js",
"files": ["dist", "src", "package.json", "README.md"],
"files": [
"dist",
"src",
"package.json",
"README.md"
],
"scripts": {
"docker:stop": "docker-compose stop",
"docker:down": "docker-compose down --volumes --remove-orphans",
Expand All @@ -24,7 +29,13 @@
"type": "git",
"url": "git+https://github.com/CodeModule-ir/cop.git"
},
"keywords": ["code-module", "telegram-bot", "telegram-group-management", "bot", "typescript"],
"keywords": [
"code-module",
"telegram-bot",
"telegram-group-management",
"bot",
"typescript"
],
"author": "Mahdi",
"license": "MIT",
"bugs": {
Expand Down
22 changes: 18 additions & 4 deletions src/bot/commands/admin/AdminCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ export class AdminCommands {
const reply = new BotReply(ctx);
const groupId = ctx.chat!.id;
const approvedUsers = await ApprovedService.getApprovedUsers(groupId);
if (!approvedUsers) {
return;
}
if (!approvedUsers.length) {
await reply.textReply('There are currently no approved users in this group.');
return;
Expand Down Expand Up @@ -136,7 +139,11 @@ export class AdminCommands {
static async warn(ctx: Context) {
const reply = new BotReply(ctx);
const user = ctx.message?.reply_to_message?.from!;
const { isWarningLimitReached, warningApplied, warnings } = await WarnService.warnUser(ctx);
const warnService = await WarnService.warnUser(ctx);
if (!warnService) {
return;
}
const { isWarningLimitReached, warningApplied, warnings } = warnService;
if (isWarningLimitReached && warningApplied) {
await reply.textReply(`User ${user.first_name} has been muted for 1 day due to excessive warnings.`);
return;
Expand All @@ -155,8 +162,11 @@ export class AdminCommands {
static async rmwarn(ctx: Context) {
const reply = new BotReply(ctx);
const user = ctx.message?.reply_to_message?.from!;
const { warningRemoved, warnings } = await WarnService.removeWarn(ctx);

const warnService = await WarnService.removeWarn(ctx);
if (!warnService) {
return;
}
const { warningRemoved, warnings } = warnService;
if (warningRemoved) {
return await reply.textReply(`User ${user.first_name} now has ${warnings} warnings after the removal.`);
} else {
Expand All @@ -174,7 +184,11 @@ export class AdminCommands {
if (!replyMessage) {
user = ctx.from!;
}
const { warnings } = await WarnService.getUserWarnById(ctx, user.id);
const warnService = await WarnService.getUserWarnById(ctx, user.id);
if (!warnService) {
return;
}
const { warnings } = warnService;
if (warnings >= 0) {
return await reply.textReply(`User ${user.first_name} currently has ${warnings} warnings.`);
} else {
Expand Down
16 changes: 13 additions & 3 deletions src/bot/commands/user/UserCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { RequireReply, RestrictToGroupChats } from '../../../decorators/Context'
import { EnsureUserAndGroup } from '../../../decorators/Database';
import { escapeMarkdownV2 } from '../../../utils';
import { ReplyToBot } from '../../../decorators/Bot';
import logger from '../../../utils/logger';
export class UserCommands {
/**
* Sends the rules of the group.
Expand All @@ -25,13 +26,19 @@ export class UserCommands {
const chatinfo = new ChatInfo(ctx);
const services = ServiceProvider.getInstance();
const groupRulesService = await services.getRulesService();

if (!groupRulesService) {
logger.warn('Group service unavailable. Skipping command execution.');
return;
}
const input = ctx.message?.text!.split(/\s+/).slice(1);
const action = input![0]?.toLowerCase();
const ruleContent = input!.join(' ');
if (!action) {
// Default behavior: Display all rules
const rulesMessage = await groupRulesService.getRulesByGroupId(ctx.chat?.id!);
if (!rulesMessage) {
return;
}
if (rulesMessage.length === 0) {
await reply.markdownReply('No rules have been set for this group.');
} else {
Expand All @@ -55,8 +62,11 @@ export class UserCommands {
}
} else if (action === 'r') {
// Clear all rules
await groupRulesService.clearAllRulesForGroup(ctx);
await reply.markdownReply('All rules have been deleted.');
if (await groupRulesService.clearAllRulesForGroup(ctx)) {
await reply.markdownReply('All rules have been deleted.');
} else {
await reply.markdownReply('Something went wrong. Please try again in a few minutes.');
}
} else {
// Add a new rule
if (!ruleContent) {
Expand Down
13 changes: 13 additions & 0 deletions src/bot/service/admin/Approved.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import { Context } from 'grammy';
import { ServiceProvider } from '../../../service/database/ServiceProvider';
import logger from '../../../utils/logger';
export class ApprovedService {
static async updateApproved(groupId: number, userId: number) {
const { groupService, userService } = await ApprovedService.getServices();
if (!groupService || !userService) {
logger.warn('services unavailable. Skipping command execution.');
return null;
}
let user = await userService.getByTelegramId(userId);
let group = await groupService.getByGroupId(groupId);
const approvedUsers = group!.approved_users ? [...group!.approved_users.map(Number)] : [];
Expand All @@ -29,6 +34,10 @@ export class ApprovedService {
}
static async updateDisapproved(groupId: number, userId: number) {
const { groupService, userService } = await ApprovedService.getServices();
if (!groupService || !userService) {
logger.warn('services unavailable. Skipping command execution.');
return null;
}
// Fetch user and group data
let user = await userService.getByTelegramId(userId);
let group = await groupService.getByGroupId(groupId);
Expand Down Expand Up @@ -59,6 +68,10 @@ export class ApprovedService {
}
static async getApprovedUsers(groupId: number) {
const { groupService, userService } = await ApprovedService.getServices();
if (!groupService || !userService) {
logger.warn('services unavailable. Skipping command execution.');
return null;
}
let group = (await groupService.getByGroupId(groupId))!;
const approvedUserIds = group.approved_users ? group.approved_users.map(Number) : [];
const approvedUsers = [];
Expand Down
5 changes: 5 additions & 0 deletions src/bot/service/admin/Ban.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Context } from 'grammy';
import { AdminValidationService } from './validation';
import { ServiceProvider } from '../../../service/database/ServiceProvider';
import logger from '../../../utils/logger';

export class BanService {
static async ban(ctx: Context): Promise<boolean> {
Expand All @@ -12,6 +13,10 @@ export class BanService {
const { groupId, userId } = validationResult;
const services = ServiceProvider.getInstance();
const [groupService, userService] = await Promise.all([services.getGroupService(), services.getUserService()]);
if (!groupService || !userService) {
logger.warn('services unavailable. Skipping command execution.');
return false;
}
let group = await groupService.getByGroupId(groupId);
let user = await userService.getByTelegramId(userId);
// If the user is part of the group, proceed with the removal
Expand Down
21 changes: 18 additions & 3 deletions src/bot/service/admin/Blacklist.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { Context } from 'grammy';
import { ServiceProvider } from '../../../service/database/ServiceProvider';
import logger from '../../../utils/logger';

export class BlackListService {
static async getAll(ctx: Context, groupId: number): Promise<string[]> {
const service = ServiceProvider.getInstance();
const groupService = await service.getGroupService();

if (!groupService) {
logger.warn('services unavailable. Skipping command execution.');
return [];
}
// Fetch group by group ID
let group = await groupService.getByGroupId(groupId);

Expand All @@ -19,6 +23,10 @@ export class BlackListService {
static async add(groupId: number, word: string, ctx: Context): Promise<string[]> {
const service = ServiceProvider.getInstance();
const groupService = await service.getGroupService();
if (!groupService) {
logger.warn('services unavailable. Skipping command execution.');
return [];
}
let group = await groupService.getByGroupId(groupId);
if (!group) {
group = await groupService.save(ctx);
Expand All @@ -41,7 +49,10 @@ export class BlackListService {
static async remove(groupId: number, ctx: Context, word?: string): Promise<string[]> {
const service = ServiceProvider.getInstance();
const groupService = await service.getGroupService();

if (!groupService) {
logger.warn('services unavailable. Skipping command execution.');
return [];
}
// Fetch group by group ID
let group = await groupService.getByGroupId(groupId);
if (!group) {
Expand All @@ -53,7 +64,7 @@ export class BlackListService {
}
} else {
// Remove the specified word
group.black_list = group.black_list.filter((item:string) => item !== word);
group.black_list = group.black_list.filter((item: string) => item !== word);
}
await groupService.update({
...group,
Expand All @@ -65,6 +76,10 @@ export class BlackListService {
static async clear(groupId: number, ctx: Context): Promise<string[]> {
const service = ServiceProvider.getInstance();
const groupService = await service.getGroupService();
if (!groupService) {
logger.warn('services unavailable. Skipping command execution.');
return [];
}
let group = await groupService.getByGroupId(groupId);
if (!group) {
group = await groupService.save(ctx);
Expand Down
25 changes: 21 additions & 4 deletions src/bot/service/admin/Warn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@ import { Context } from 'grammy';
import { AdminValidationService } from './validation';
import { ServiceProvider } from '../../../service/database/ServiceProvider';
import { MuteService } from './Mute';
import logger from '../../../utils/logger';

export class WarnService {
static async warnUser(ctx: Context): Promise<{
warningApplied: boolean;
isWarningLimitReached: boolean;
warnings: number;
}> {
} | null> {
const validationResult = await AdminValidationService.validateContext(ctx);
if (!validationResult) {
return {
Expand All @@ -22,6 +23,10 @@ export class WarnService {
const input = ctx.message?.text!.split(/\s+/).slice(1);
const reason = input!.join(' ')?.toLowerCase() || 'reason is not set for warning';
const [groupService, userService, warnService] = await Promise.all([services.getGroupService(), services.getUserService(), services.getWarnsService()]);
if (!groupService || !userService || !warnService) {
logger.warn('services unavailable. Skipping command execution.');
return null;
}
let group = (await groupService.getByGroupId(groupId))!;
let user = (await userService.getByTelegramId(userId))!;
let warn = await warnService.getByGroupId(groupId);
Expand Down Expand Up @@ -72,7 +77,7 @@ export class WarnService {
warnings: updatedUser.warnings,
};
}
static async removeWarn(ctx: Context): Promise<{ warningRemoved: boolean; warnings: number }> {
static async removeWarn(ctx: Context): Promise<{ warningRemoved: boolean; warnings: number } | null> {
const validationResult = await AdminValidationService.validateContext(ctx);
if (!validationResult) {
return { warningRemoved: false, warnings: 0 };
Expand All @@ -81,6 +86,10 @@ export class WarnService {
const { userId } = validationResult;
const services = ServiceProvider.getInstance();
const userService = await services.getUserService();
if (!userService) {
logger.warn('services unavailable. Skipping command execution.');
return null;
}
let user = (await userService.getByTelegramId(userId))!;
const updatedUser = {
...user,
Expand All @@ -92,9 +101,13 @@ export class WarnService {
warnings: updatedUser.warnings,
};
}
static async getUserWarnById(ctx: Context, userId: number): Promise<{ warnings: number }> {
static async getUserWarnById(ctx: Context, userId: number): Promise<{ warnings: number } | null> {
const services = ServiceProvider.getInstance();
const userService = await services.getUserService();
if (!userService) {
logger.warn('services unavailable. Skipping command execution.');
return null;
}
let user = await userService.getByTelegramId(userId);
let replyMessage = ctx.message?.reply_to_message?.from;
const userData = { first_name: replyMessage?.first_name!, id: userId, username: replyMessage?.username! };
Expand All @@ -103,7 +116,7 @@ export class WarnService {
}
return { warnings: user.warnings };
}
static async getAllWarns(ctx: Context): Promise<string> {
static async getAllWarns(ctx: Context): Promise<string | null> {
const replyMessage = ctx.from;
// Ensure the user ID of the replied message is valid
const userId = replyMessage!.id!;
Expand All @@ -113,6 +126,10 @@ export class WarnService {
// Initialize services
const services = ServiceProvider.getInstance();
const [groupService, userService, warnService] = await Promise.all([services.getGroupService(), services.getUserService(), services.getWarnsService()]);
if (!userService || !groupService || !warnService) {
logger.warn('services unavailable. Skipping command execution.');
return null;
}
let group = await groupService.getByGroupId(groupId);
let user = await userService.getByTelegramId(userId);
const userData = { first_name: ctx!.message?.reply_to_message?.from?.first_name!, id: userId, username: ctx.message?.reply_to_message?.from?.username! };
Expand Down
19 changes: 16 additions & 3 deletions src/bot/service/admin/Welcome.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,27 @@
import { Context } from 'grammy';
import { ServiceProvider } from '../../../service/database/ServiceProvider';
import { Group } from '../../../types/database/TablesTypes';
import logger from '../../../utils/logger';
export class GroupSettingsService {
static async getWelcomeMessage(ctx: Context, welcomeContent: string): Promise<Group['welcome_message']> {
static async getWelcomeMessage(ctx: Context, welcomeContent: string): Promise<Group['welcome_message'] | null> {
const { groupService } = await GroupSettingsService.getServices();
if (!groupService) {
logger.warn('services unavailable. Skipping command execution.');
return null;
}
const groupId = ctx.chat?.id!;
let group = await groupService.getByGroupId(groupId);
if (!group) {
group = await groupService.save(ctx);
}
return group.welcome_message;
}
static async removeWelcomeMessage(ctx: Context): Promise<string> {
static async removeWelcomeMessage(ctx: Context): Promise<string | null> {
const { groupService } = await GroupSettingsService.getServices();
if (!groupService) {
logger.warn('services unavailable. Skipping command execution.');
return null;
}
const groupId = ctx.chat?.id!;

// Get the group by its ID
Expand All @@ -30,8 +39,12 @@ export class GroupSettingsService {

return updatedGroup.welcome_message ? updatedGroup.welcome_message : 'The welcome message has been removed.';
}
static async setWelcomeMessage(ctx: Context, welcomeContent: string): Promise<string> {
static async setWelcomeMessage(ctx: Context, welcomeContent: string): Promise<string | null> {
const { groupService } = await GroupSettingsService.getServices();
if (!groupService) {
logger.warn('services unavailable. Skipping command execution.');
return null;
}
const groupId = ctx.chat?.id!;
// Get the group by its ID
let group = await groupService.getByGroupId(groupId);
Expand Down
6 changes: 0 additions & 6 deletions src/database/models/Channel.ts

This file was deleted.

Loading

0 comments on commit 13d2b79

Please sign in to comment.