Skip to content

Commit 13d2b79

Browse files
committed
fix(database): Update retryConnect method to handle promise return type and add error logging
1 parent 04a7af7 commit 13d2b79

File tree

13 files changed

+172
-36
lines changed

13 files changed

+172
-36
lines changed

package.json

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,12 @@
33
"version": "4.1.0",
44
"description": "A Telegram bot for managing Telegram groups efficiently.",
55
"main": "/src/app.js",
6-
"files": ["dist", "src", "package.json", "README.md"],
6+
"files": [
7+
"dist",
8+
"src",
9+
"package.json",
10+
"README.md"
11+
],
712
"scripts": {
813
"docker:stop": "docker-compose stop",
914
"docker:down": "docker-compose down --volumes --remove-orphans",
@@ -24,7 +29,13 @@
2429
"type": "git",
2530
"url": "git+https://github.com/CodeModule-ir/cop.git"
2631
},
27-
"keywords": ["code-module", "telegram-bot", "telegram-group-management", "bot", "typescript"],
32+
"keywords": [
33+
"code-module",
34+
"telegram-bot",
35+
"telegram-group-management",
36+
"bot",
37+
"typescript"
38+
],
2839
"author": "Mahdi",
2940
"license": "MIT",
3041
"bugs": {

src/bot/commands/admin/AdminCommands.ts

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,9 @@ export class AdminCommands {
8383
const reply = new BotReply(ctx);
8484
const groupId = ctx.chat!.id;
8585
const approvedUsers = await ApprovedService.getApprovedUsers(groupId);
86+
if (!approvedUsers) {
87+
return;
88+
}
8689
if (!approvedUsers.length) {
8790
await reply.textReply('There are currently no approved users in this group.');
8891
return;
@@ -136,7 +139,11 @@ export class AdminCommands {
136139
static async warn(ctx: Context) {
137140
const reply = new BotReply(ctx);
138141
const user = ctx.message?.reply_to_message?.from!;
139-
const { isWarningLimitReached, warningApplied, warnings } = await WarnService.warnUser(ctx);
142+
const warnService = await WarnService.warnUser(ctx);
143+
if (!warnService) {
144+
return;
145+
}
146+
const { isWarningLimitReached, warningApplied, warnings } = warnService;
140147
if (isWarningLimitReached && warningApplied) {
141148
await reply.textReply(`User ${user.first_name} has been muted for 1 day due to excessive warnings.`);
142149
return;
@@ -155,8 +162,11 @@ export class AdminCommands {
155162
static async rmwarn(ctx: Context) {
156163
const reply = new BotReply(ctx);
157164
const user = ctx.message?.reply_to_message?.from!;
158-
const { warningRemoved, warnings } = await WarnService.removeWarn(ctx);
159-
165+
const warnService = await WarnService.removeWarn(ctx);
166+
if (!warnService) {
167+
return;
168+
}
169+
const { warningRemoved, warnings } = warnService;
160170
if (warningRemoved) {
161171
return await reply.textReply(`User ${user.first_name} now has ${warnings} warnings after the removal.`);
162172
} else {
@@ -174,7 +184,11 @@ export class AdminCommands {
174184
if (!replyMessage) {
175185
user = ctx.from!;
176186
}
177-
const { warnings } = await WarnService.getUserWarnById(ctx, user.id);
187+
const warnService = await WarnService.getUserWarnById(ctx, user.id);
188+
if (!warnService) {
189+
return;
190+
}
191+
const { warnings } = warnService;
178192
if (warnings >= 0) {
179193
return await reply.textReply(`User ${user.first_name} currently has ${warnings} warnings.`);
180194
} else {

src/bot/commands/user/UserCommands.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { RequireReply, RestrictToGroupChats } from '../../../decorators/Context'
1010
import { EnsureUserAndGroup } from '../../../decorators/Database';
1111
import { escapeMarkdownV2 } from '../../../utils';
1212
import { ReplyToBot } from '../../../decorators/Bot';
13+
import logger from '../../../utils/logger';
1314
export class UserCommands {
1415
/**
1516
* Sends the rules of the group.
@@ -25,13 +26,19 @@ export class UserCommands {
2526
const chatinfo = new ChatInfo(ctx);
2627
const services = ServiceProvider.getInstance();
2728
const groupRulesService = await services.getRulesService();
28-
29+
if (!groupRulesService) {
30+
logger.warn('Group service unavailable. Skipping command execution.');
31+
return;
32+
}
2933
const input = ctx.message?.text!.split(/\s+/).slice(1);
3034
const action = input![0]?.toLowerCase();
3135
const ruleContent = input!.join(' ');
3236
if (!action) {
3337
// Default behavior: Display all rules
3438
const rulesMessage = await groupRulesService.getRulesByGroupId(ctx.chat?.id!);
39+
if (!rulesMessage) {
40+
return;
41+
}
3542
if (rulesMessage.length === 0) {
3643
await reply.markdownReply('No rules have been set for this group.');
3744
} else {
@@ -55,8 +62,11 @@ export class UserCommands {
5562
}
5663
} else if (action === 'r') {
5764
// Clear all rules
58-
await groupRulesService.clearAllRulesForGroup(ctx);
59-
await reply.markdownReply('All rules have been deleted.');
65+
if (await groupRulesService.clearAllRulesForGroup(ctx)) {
66+
await reply.markdownReply('All rules have been deleted.');
67+
} else {
68+
await reply.markdownReply('Something went wrong. Please try again in a few minutes.');
69+
}
6070
} else {
6171
// Add a new rule
6272
if (!ruleContent) {

src/bot/service/admin/Approved.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
import { Context } from 'grammy';
22
import { ServiceProvider } from '../../../service/database/ServiceProvider';
3+
import logger from '../../../utils/logger';
34
export class ApprovedService {
45
static async updateApproved(groupId: number, userId: number) {
56
const { groupService, userService } = await ApprovedService.getServices();
7+
if (!groupService || !userService) {
8+
logger.warn('services unavailable. Skipping command execution.');
9+
return null;
10+
}
611
let user = await userService.getByTelegramId(userId);
712
let group = await groupService.getByGroupId(groupId);
813
const approvedUsers = group!.approved_users ? [...group!.approved_users.map(Number)] : [];
@@ -29,6 +34,10 @@ export class ApprovedService {
2934
}
3035
static async updateDisapproved(groupId: number, userId: number) {
3136
const { groupService, userService } = await ApprovedService.getServices();
37+
if (!groupService || !userService) {
38+
logger.warn('services unavailable. Skipping command execution.');
39+
return null;
40+
}
3241
// Fetch user and group data
3342
let user = await userService.getByTelegramId(userId);
3443
let group = await groupService.getByGroupId(groupId);
@@ -59,6 +68,10 @@ export class ApprovedService {
5968
}
6069
static async getApprovedUsers(groupId: number) {
6170
const { groupService, userService } = await ApprovedService.getServices();
71+
if (!groupService || !userService) {
72+
logger.warn('services unavailable. Skipping command execution.');
73+
return null;
74+
}
6275
let group = (await groupService.getByGroupId(groupId))!;
6376
const approvedUserIds = group.approved_users ? group.approved_users.map(Number) : [];
6477
const approvedUsers = [];

src/bot/service/admin/Ban.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { Context } from 'grammy';
22
import { AdminValidationService } from './validation';
33
import { ServiceProvider } from '../../../service/database/ServiceProvider';
4+
import logger from '../../../utils/logger';
45

56
export class BanService {
67
static async ban(ctx: Context): Promise<boolean> {
@@ -12,6 +13,10 @@ export class BanService {
1213
const { groupId, userId } = validationResult;
1314
const services = ServiceProvider.getInstance();
1415
const [groupService, userService] = await Promise.all([services.getGroupService(), services.getUserService()]);
16+
if (!groupService || !userService) {
17+
logger.warn('services unavailable. Skipping command execution.');
18+
return false;
19+
}
1520
let group = await groupService.getByGroupId(groupId);
1621
let user = await userService.getByTelegramId(userId);
1722
// If the user is part of the group, proceed with the removal

src/bot/service/admin/Blacklist.ts

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11
import { Context } from 'grammy';
22
import { ServiceProvider } from '../../../service/database/ServiceProvider';
3+
import logger from '../../../utils/logger';
34

45
export class BlackListService {
56
static async getAll(ctx: Context, groupId: number): Promise<string[]> {
67
const service = ServiceProvider.getInstance();
78
const groupService = await service.getGroupService();
8-
9+
if (!groupService) {
10+
logger.warn('services unavailable. Skipping command execution.');
11+
return [];
12+
}
913
// Fetch group by group ID
1014
let group = await groupService.getByGroupId(groupId);
1115

@@ -19,6 +23,10 @@ export class BlackListService {
1923
static async add(groupId: number, word: string, ctx: Context): Promise<string[]> {
2024
const service = ServiceProvider.getInstance();
2125
const groupService = await service.getGroupService();
26+
if (!groupService) {
27+
logger.warn('services unavailable. Skipping command execution.');
28+
return [];
29+
}
2230
let group = await groupService.getByGroupId(groupId);
2331
if (!group) {
2432
group = await groupService.save(ctx);
@@ -41,7 +49,10 @@ export class BlackListService {
4149
static async remove(groupId: number, ctx: Context, word?: string): Promise<string[]> {
4250
const service = ServiceProvider.getInstance();
4351
const groupService = await service.getGroupService();
44-
52+
if (!groupService) {
53+
logger.warn('services unavailable. Skipping command execution.');
54+
return [];
55+
}
4556
// Fetch group by group ID
4657
let group = await groupService.getByGroupId(groupId);
4758
if (!group) {
@@ -53,7 +64,7 @@ export class BlackListService {
5364
}
5465
} else {
5566
// Remove the specified word
56-
group.black_list = group.black_list.filter((item:string) => item !== word);
67+
group.black_list = group.black_list.filter((item: string) => item !== word);
5768
}
5869
await groupService.update({
5970
...group,
@@ -65,6 +76,10 @@ export class BlackListService {
6576
static async clear(groupId: number, ctx: Context): Promise<string[]> {
6677
const service = ServiceProvider.getInstance();
6778
const groupService = await service.getGroupService();
79+
if (!groupService) {
80+
logger.warn('services unavailable. Skipping command execution.');
81+
return [];
82+
}
6883
let group = await groupService.getByGroupId(groupId);
6984
if (!group) {
7085
group = await groupService.save(ctx);

src/bot/service/admin/Warn.ts

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@ import { Context } from 'grammy';
22
import { AdminValidationService } from './validation';
33
import { ServiceProvider } from '../../../service/database/ServiceProvider';
44
import { MuteService } from './Mute';
5+
import logger from '../../../utils/logger';
56

67
export class WarnService {
78
static async warnUser(ctx: Context): Promise<{
89
warningApplied: boolean;
910
isWarningLimitReached: boolean;
1011
warnings: number;
11-
}> {
12+
} | null> {
1213
const validationResult = await AdminValidationService.validateContext(ctx);
1314
if (!validationResult) {
1415
return {
@@ -22,6 +23,10 @@ export class WarnService {
2223
const input = ctx.message?.text!.split(/\s+/).slice(1);
2324
const reason = input!.join(' ')?.toLowerCase() || 'reason is not set for warning';
2425
const [groupService, userService, warnService] = await Promise.all([services.getGroupService(), services.getUserService(), services.getWarnsService()]);
26+
if (!groupService || !userService || !warnService) {
27+
logger.warn('services unavailable. Skipping command execution.');
28+
return null;
29+
}
2530
let group = (await groupService.getByGroupId(groupId))!;
2631
let user = (await userService.getByTelegramId(userId))!;
2732
let warn = await warnService.getByGroupId(groupId);
@@ -72,7 +77,7 @@ export class WarnService {
7277
warnings: updatedUser.warnings,
7378
};
7479
}
75-
static async removeWarn(ctx: Context): Promise<{ warningRemoved: boolean; warnings: number }> {
80+
static async removeWarn(ctx: Context): Promise<{ warningRemoved: boolean; warnings: number } | null> {
7681
const validationResult = await AdminValidationService.validateContext(ctx);
7782
if (!validationResult) {
7883
return { warningRemoved: false, warnings: 0 };
@@ -81,6 +86,10 @@ export class WarnService {
8186
const { userId } = validationResult;
8287
const services = ServiceProvider.getInstance();
8388
const userService = await services.getUserService();
89+
if (!userService) {
90+
logger.warn('services unavailable. Skipping command execution.');
91+
return null;
92+
}
8493
let user = (await userService.getByTelegramId(userId))!;
8594
const updatedUser = {
8695
...user,
@@ -92,9 +101,13 @@ export class WarnService {
92101
warnings: updatedUser.warnings,
93102
};
94103
}
95-
static async getUserWarnById(ctx: Context, userId: number): Promise<{ warnings: number }> {
104+
static async getUserWarnById(ctx: Context, userId: number): Promise<{ warnings: number } | null> {
96105
const services = ServiceProvider.getInstance();
97106
const userService = await services.getUserService();
107+
if (!userService) {
108+
logger.warn('services unavailable. Skipping command execution.');
109+
return null;
110+
}
98111
let user = await userService.getByTelegramId(userId);
99112
let replyMessage = ctx.message?.reply_to_message?.from;
100113
const userData = { first_name: replyMessage?.first_name!, id: userId, username: replyMessage?.username! };
@@ -103,7 +116,7 @@ export class WarnService {
103116
}
104117
return { warnings: user.warnings };
105118
}
106-
static async getAllWarns(ctx: Context): Promise<string> {
119+
static async getAllWarns(ctx: Context): Promise<string | null> {
107120
const replyMessage = ctx.from;
108121
// Ensure the user ID of the replied message is valid
109122
const userId = replyMessage!.id!;
@@ -113,6 +126,10 @@ export class WarnService {
113126
// Initialize services
114127
const services = ServiceProvider.getInstance();
115128
const [groupService, userService, warnService] = await Promise.all([services.getGroupService(), services.getUserService(), services.getWarnsService()]);
129+
if (!userService || !groupService || !warnService) {
130+
logger.warn('services unavailable. Skipping command execution.');
131+
return null;
132+
}
116133
let group = await groupService.getByGroupId(groupId);
117134
let user = await userService.getByTelegramId(userId);
118135
const userData = { first_name: ctx!.message?.reply_to_message?.from?.first_name!, id: userId, username: ctx.message?.reply_to_message?.from?.username! };

src/bot/service/admin/Welcome.ts

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,27 @@
11
import { Context } from 'grammy';
22
import { ServiceProvider } from '../../../service/database/ServiceProvider';
33
import { Group } from '../../../types/database/TablesTypes';
4+
import logger from '../../../utils/logger';
45
export class GroupSettingsService {
5-
static async getWelcomeMessage(ctx: Context, welcomeContent: string): Promise<Group['welcome_message']> {
6+
static async getWelcomeMessage(ctx: Context, welcomeContent: string): Promise<Group['welcome_message'] | null> {
67
const { groupService } = await GroupSettingsService.getServices();
8+
if (!groupService) {
9+
logger.warn('services unavailable. Skipping command execution.');
10+
return null;
11+
}
712
const groupId = ctx.chat?.id!;
813
let group = await groupService.getByGroupId(groupId);
914
if (!group) {
1015
group = await groupService.save(ctx);
1116
}
1217
return group.welcome_message;
1318
}
14-
static async removeWelcomeMessage(ctx: Context): Promise<string> {
19+
static async removeWelcomeMessage(ctx: Context): Promise<string | null> {
1520
const { groupService } = await GroupSettingsService.getServices();
21+
if (!groupService) {
22+
logger.warn('services unavailable. Skipping command execution.');
23+
return null;
24+
}
1625
const groupId = ctx.chat?.id!;
1726

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

3140
return updatedGroup.welcome_message ? updatedGroup.welcome_message : 'The welcome message has been removed.';
3241
}
33-
static async setWelcomeMessage(ctx: Context, welcomeContent: string): Promise<string> {
42+
static async setWelcomeMessage(ctx: Context, welcomeContent: string): Promise<string | null> {
3443
const { groupService } = await GroupSettingsService.getServices();
44+
if (!groupService) {
45+
logger.warn('services unavailable. Skipping command execution.');
46+
return null;
47+
}
3548
const groupId = ctx.chat?.id!;
3649
// Get the group by its ID
3750
let group = await groupService.getByGroupId(groupId);

src/database/models/Channel.ts

Lines changed: 0 additions & 6 deletions
This file was deleted.

0 commit comments

Comments
 (0)