Skip to content

Commit 6b89efa

Browse files
committed
refactor: "Refactor CopBot initialization, shutdown, and webhook setup; remove WebHookService class"
1 parent 6510989 commit 6b89efa

File tree

3 files changed

+66
-127
lines changed

3 files changed

+66
-127
lines changed

src/app.ts

Lines changed: 37 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -3,50 +3,51 @@ import { ServiceProvider } from './service/database/ServiceProvider';
33
import logger from './utils/logger';
44

55
async function main() {
6-
const cop = CopBot.getInstance();
6+
const botInstance = CopBot.getInstance();
7+
78
try {
89
await ServiceProvider.initialize();
9-
logger.info('Initialized Database');
10+
logger.info('Database initialized.');
1011

11-
await cop.initial();
12-
logger.info('Bot initialized');
13-
} catch (error: any) {
14-
logger.error('Error during initialization:', error);
12+
await botInstance.initial();
13+
logger.info('Bot initialized.');
14+
} catch (err) {
15+
logger.error('Error during initialization:' + err);
1516
process.exit(1);
1617
}
18+
19+
// Graceful shutdown
1720
process.on('SIGTERM', async () => {
18-
logger.info('SIGTERM signal received. Closing bot...');
19-
try {
20-
const db = ServiceProvider.getInstance();
21-
await db.close();
22-
logger.info('Database closed.');
23-
await cop.stop();
24-
logger.info('Bot stopped.');
25-
} catch (error: any) {
26-
logger.error('Error during shutdown:', error);
27-
} finally {
28-
logger.info('Shutting down bot process');
29-
process.exit(0);
30-
}
21+
logger.info('SIGTERM signal received. Shutting down...');
22+
await shutdown(botInstance);
3123
});
32-
process.on('unhandledRejection', (reason, promise) => {
33-
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
24+
25+
process.on('SIGINT', async () => {
26+
logger.info('SIGINT signal received. Shutting down...');
27+
await shutdown(botInstance);
28+
});
29+
30+
process.on('unhandledRejection', (reason) => {
31+
logger.error('Unhandled Rejection:' + reason);
3432
});
35-
process.on('uncaughtException', async (error: any) => {
36-
logger.error('Uncaught Exception:', error);
37-
try {
38-
const db = ServiceProvider.getInstance();
39-
await db.close();
40-
logger.info('Database closed due to uncaught exception.');
41-
} catch (shutdownError: any) {
42-
logger.error('Error during shutdown:', shutdownError);
43-
} finally {
44-
process.exit(1);
45-
}
33+
34+
process.on('uncaughtException', async (err) => {
35+
logger.error('Uncaught Exception:' + err);
36+
await shutdown(botInstance, 1);
4637
});
4738
}
4839

49-
main().catch((error) => {
50-
logger.error('Application error during startup:', error);
51-
process.exit(1); // Exit if the main function fails
52-
});
40+
async function shutdown(botInstance: CopBot, exitCode = 0) {
41+
try {
42+
const db = ServiceProvider.getInstance();
43+
await db.close();
44+
logger.info('Database closed.');
45+
await botInstance.stop();
46+
} catch (err) {
47+
logger.error('Error during shutdown:' + err);
48+
} finally {
49+
process.exit(exitCode);
50+
}
51+
}
52+
53+
main();

src/bot/index.ts

Lines changed: 29 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Bot } from 'grammy';
1+
import { Bot, webhookCallback } from 'grammy';
22
import type { Context } from 'grammy';
33
import { Catch } from '../decorators/Catch';
44
import Config from '../config';
@@ -9,7 +9,8 @@ import { AdminCommands } from './commands/admin/AdminCommands';
99
import { SaveUserData } from '../decorators/Database';
1010
import { MessageValidator } from '../decorators/Context';
1111
import { BotReply } from '../utils/chat/BotReply';
12-
import { WebHookService } from '../service/WebHook';
12+
import logger from '../utils/logger';
13+
import * as express from 'express';
1314
export class CopBot {
1415
private static instance: CopBot;
1516
private _bot: Bot<Context>;
@@ -33,60 +34,62 @@ export class CopBot {
3334
const startBot = async (mode: string) => {
3435
await this._bot.start({
3536
onStart: (botInfo) => {
36-
console.log(`Bot started in ${mode} mode! Username: ${botInfo.username}`);
37+
logger.info(`Bot started in ${mode} mode! Username: ${botInfo.username}`);
3738
},
3839
});
3940
};
41+
4042
const isProduction = Config.environment === 'production';
41-
const webhookURL = `${Config.web_hook}/bot/${Config.token}`;
43+
const webhookPath = `/bot/${Config.token}`;
44+
const webhookURL = `${Config.web_hook}${webhookPath}`;
4245
const mode = isProduction ? 'webhook' : 'long-polling';
43-
console.log(`Environment: ${Config.environment}`);
44-
console.log(`Web hook Url: ${webhookURL}`);
45-
console.log(`Running in ${isProduction ? 'webhook' : 'long-polling'} mode`);
46+
47+
logger.info(`Environment: ${Config.environment}`);
48+
logger.info(`Webhook URL: ${webhookURL}`);
49+
logger.info(`Running in ${mode} mode`);
50+
4651
if (isProduction) {
47-
console.log('Setting webhook...');
4852
try {
49-
console.log('Setting up webhook...');
50-
const _webhookService = WebHookService.getInstance(this._bot);
51-
await _webhookService.setupWebHook();
52-
await _webhookService.initial()
53-
_webhookService.startServer();
54-
await startBot(mode);
55-
const webhookInfo = await this._bot.api.getWebhookInfo();
56-
console.log(`Bot started in webhook mode`);
57-
console.log('webhookInfo', webhookInfo);
53+
const app = express();
54+
app.use(express.json());
55+
56+
app.post(webhookPath, webhookCallback(this._bot, 'express'));
57+
58+
const port = process.env.PORT || 3000;
59+
app.listen(port, async () => {
60+
logger.info(`Webhook server running on port ${port}`);
61+
await this._bot.api.setWebhook(webhookURL);
62+
const webhookInfo = await this._bot.api.getWebhookInfo();
63+
logger.info(`Webhook set: ${webhookInfo.url}`);
64+
});
5865
} catch (err) {
59-
console.error('Error setting up webhook:', err);
66+
logger.error('Error setting up webhook:' + err);
6067
process.exit(1);
6168
}
6269
} else {
63-
console.log('Running in long-polling mode...');
6470
try {
6571
await this._bot.api.deleteWebhook();
6672
await startBot(mode);
6773
} catch (err) {
68-
console.error('Error in long-polling mode:', err);
74+
logger.error('Error during long-polling mode:' + err);
6975
process.exit(1);
7076
}
7177
}
7278
}
73-
@Catch()
7479
async initial(): Promise<void> {
7580
new GenerateCommand(this._bot).generate();
7681
this._bot.on('my_chat_member', (ctx) => this.handleJoinNewChat(ctx));
7782
this._bot.on('message', (ctx) => this.handleMessage(ctx));
7883

79-
// Error handling
8084
this._bot.catch((err) => {
81-
console.error('Error in middleware:', err);
85+
logger.error('Middleware error:' + err);
8286
});
8387

8488
await this.start();
85-
console.log('Bot is running');
89+
logger.info('Bot is running');
8690
}
8791
@SaveUserData()
8892
@MessageValidator()
89-
@Catch()
9093
async handleMessage(ctx: Context) {
9194
console.log('ctx.message.text:', ctx.message?.text);
9295
console.log('ctx.chat', ctx.chat);
@@ -101,8 +104,7 @@ export class CopBot {
101104
await reply.textReply(responseMessage);
102105
}
103106
const command = messageText?.split(' ')[0]?.replace('/', '');
104-
const botCommand = ctx.message?.entities?.[0].type === 'bot_command';
105-
if (botCommand && command) {
107+
if (command && ctx.message?.entities?.[0].type === 'bot_command') {
106108
const handler = (GeneralCommands as any)[command] || (UserCommands as any)[command] || (AdminCommands as any)[command];
107109
if (typeof handler === 'function') {
108110
await handler(ctx);

src/service/WebHook.ts

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

0 commit comments

Comments
 (0)