-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscheduled_check.js
More file actions
134 lines (113 loc) · 4.85 KB
/
Copy pathscheduled_check.js
File metadata and controls
134 lines (113 loc) · 4.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import { Telegraf } from 'telegraf';
import dotenv from 'dotenv';
import Logger from './src/utils/logger.js';
import { forceCheckAllMonitors } from './src/utils/force_check.js';
import crud from './src/crud.js';
import mongoose from 'mongoose';
// Load environment variables
dotenv.config();
// Get MongoDB URI from environment variables
const mongoUri = process.env.MONGODB_URI;
if (!mongoUri) {
console.error('MongoDB URI not found in environment variables. Please set MONGODB_URI in .env file.');
process.exit(1);
}
// Connect to MongoDB
console.log('Connecting to MongoDB...');
mongoose.connect(mongoUri)
.then(() => {
console.log('Connected to MongoDB');
startScheduler();
})
.catch(err => {
console.error('Failed to connect to MongoDB:', err);
process.exit(1);
});
// Initialize the bot
const bot = new Telegraf(process.env.TELEGRAM_BOT_TOKEN);
// Set the interval in milliseconds (default: 5 minutes)
const CHECK_INTERVAL = process.env.CHECK_INTERVAL ? parseInt(process.env.CHECK_INTERVAL) : 5 * 60 * 1000;
// Function to start the scheduler
function startScheduler() {
// Run the force check immediately on startup
console.log(`[SCHEDULED] Starting scheduled checks every ${CHECK_INTERVAL / 1000} seconds`);
runForceCheck().catch(error => {
Logger.error(`[SCHEDULED] Initial force check failed: ${error.message}`);
console.error('[SCHEDULED] Initial force check failed:', error);
});
// Set up the interval to run the force check
setInterval(runForceCheck, CHECK_INTERVAL);
}
// Function to run the force check
async function runForceCheck() {
try {
Logger.info('[SCHEDULED] Starting scheduled force check...');
console.log('[SCHEDULED] Starting scheduled force check...');
// Get admin user ID from environment variable or use the first admin from the database
let adminUserId = process.env.ADMIN_USER_IDS ? process.env.ADMIN_USER_IDS.split(',')[0].trim() : null;
if (!adminUserId) {
try {
// Get all users from the database
const users = await crud.getAllUsers();
if (users && users.length > 0) {
adminUserId = users[0].userId;
Logger.info(`[SCHEDULED] Using user ID from database: ${adminUserId}`);
console.log(`[SCHEDULED] Using user ID from database: ${adminUserId}`);
} else {
Logger.error('[SCHEDULED] No users found in database');
console.error('[SCHEDULED] No users found in database');
return;
}
} catch (dbError) {
Logger.error(`[SCHEDULED] Error getting users from database: ${dbError.message}`);
console.error('[SCHEDULED] Error getting users from database:', dbError);
return;
}
} else {
Logger.info(`[SCHEDULED] Using admin user ID from environment: ${adminUserId}`);
console.log(`[SCHEDULED] Using admin user ID from environment: ${adminUserId}`);
}
// Create a mock context object
const ctx = {
from: { id: adminUserId },
reply: async (text) => {
Logger.info(`[SCHEDULED] Would reply to user: ${text}`);
console.log(`[SCHEDULED] Would reply to user: ${text}`);
},
replyWithHTML: async (text) => {
Logger.info(`[SCHEDULED] Would reply to user with HTML: ${text}`);
console.log(`[SCHEDULED] Would reply to user with HTML: ${text}`);
}
};
// Run the force check
await forceCheckAllMonitors(ctx);
Logger.info('[SCHEDULED] Completed scheduled force check');
console.log('[SCHEDULED] Completed scheduled force check');
} catch (error) {
Logger.error(`[SCHEDULED] Error in scheduled force check: ${error.message}`);
console.error('[SCHEDULED] Error in scheduled force check:', error);
}
}
// Handle graceful shutdown
process.on('SIGINT', async () => {
Logger.info('[SCHEDULED] Shutting down scheduled checks...');
console.log('[SCHEDULED] Shutting down scheduled checks...');
try {
await mongoose.connection.close();
console.log('Closed MongoDB connection');
} catch (err) {
console.error('Error closing MongoDB connection:', err);
}
process.exit(0);
});
process.on('SIGTERM', async () => {
Logger.info('[SCHEDULED] Shutting down scheduled checks...');
console.log('[SCHEDULED] Shutting down scheduled checks...');
try {
await mongoose.connection.close();
console.log('Closed MongoDB connection');
} catch (err) {
console.error('Error closing MongoDB connection:', err);
}
process.exit(0);
});