-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbot.js
More file actions
222 lines (180 loc) · 8.08 KB
/
bot.js
File metadata and controls
222 lines (180 loc) · 8.08 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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
const { Telegraf, session } = require('telegraf');
const { message } = require('telegraf/filters');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const express = require('express');
const bodyParser = require('body-parser');
// Import modules
const userMiddleware = require('./middleware/userMiddleware');
const subscriptionPermissionMiddleware = require('./middleware/subscriptionPermissionMiddleware');
const commandHandlers = require('./controllers/commands');
const groupHandlers = require('./controllers/groups');
const messageHandlers = require('./controllers/messages');
const callbackHandlers = require('./controllers/callbacks');
const subscriptionUtils = require('./utils/subscriptionUtils');
// Import payment provider system and gateway configuration
const { PaymentManager } = require('./payment-providers');
const paymentGatewaysConfig = require('./payment-providers/paymentGateways');
// Load environment variables
dotenv.config();
// Set strictQuery option to suppress deprecation warning
mongoose.set('strictQuery', false);
// Initialize bot with your token
const bot = new Telegraf(process.env.BOT_TOKEN);
// Create Express app for payment webhooks
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
// Initialize payment providers
const paymentManager = new PaymentManager();
// Load payment providers dynamically from the configuration
const enabledGateways = paymentGatewaysConfig.availableGateways.filter(gateway => gateway.enabled);
console.log(`Loading ${enabledGateways.length} enabled payment gateways from config`);
// Dynamically load and register each enabled payment provider
enabledGateways.forEach(gateway => {
try {
// Import the provider class dynamically
[gateway.providerClass] = require(`./payment-providers/${gateway.id}/${gateway.providerClass}`);
// Configure the provider from environment variables
const providerConfig = {};
gateway.configParams.forEach(param => {
const envKey = `${gateway.id.toUpperCase()}_${param.toUpperCase()}`;
providerConfig[param] = process.env[envKey];
});
// Set test mode based on environment
providerConfig.testMode = process.env.NODE_ENV !== 'production';
// Create instance and register the provider
const provider = new [gateway.providerClass](providerConfig);
paymentManager.registerProvider(gateway.id, provider, gateway.default || false);
console.log(`Registered payment gateway: ${gateway.name}`);
} catch (error) {
console.error(`Failed to load payment provider '${gateway.name}':`, error);
}
});
// Connect to MongoDB
mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB');
// Add step-by-step debugging logs
console.log('Initializing session middleware...');
try {
// Add session middleware with proper error handling
bot.use(session({
// Customize session to make it more robust
getSessionKey: (ctx) => {
// Use a combination of chat ID and user ID to create a unique key
const chatId = ctx.chat?.id.toString();
const userId = ctx.from?.id.toString();
if (chatId && userId) {
return `${chatId}:${userId}`;
} else if (userId) {
return userId;
}
return null; // No session
}
})); // Ensure session middleware is added here
// Debugging to confirm session middleware is working
bot.use((ctx, next) => {
console.log('Session middleware triggered');
console.log('Session state before handler:', JSON.stringify(ctx.session || {}));
// Also log chat and user info for debugging purposes
if (ctx.chat) {
const chatInfo = {
id: ctx.chat.id,
type: ctx.chat.type,
title: ctx.chat.title
};
console.log('Chat info:', chatInfo);
// Store chat type in context for easier access in command handlers
ctx.chatType = ctx.chat.type;
}
if (ctx.from) {
console.log('From user:', {
id: ctx.from.id,
username: ctx.from.username,
first_name: ctx.from.first_name
});
}
return next();
});
console.log('Session middleware initialized');
console.log('Initializing user tracking middleware...');
bot.use(userMiddleware);
console.log('User tracking middleware initialized');
console.log('Initializing subscription permission middleware...');
bot.use(subscriptionPermissionMiddleware);
console.log('Subscription permission middleware initialized');
// Register handlers with proper error handling
console.log('Registering command handlers...');
commandHandlers.register(bot, paymentManager);
console.log('Command handlers registered');
console.log('Registering group handlers...');
groupHandlers.register(bot);
console.log('Group handlers registered');
console.log('Registering message handlers...');
messageHandlers.register(bot);
console.log('Message handlers registered');
console.log('Registering callback handlers...');
callbackHandlers.register(bot);
console.log('Callback handlers registered');
// Set up payment provider webhooks
console.log('Setting up payment webhooks...');
paymentManager.setupWebhooks(app, async (paymentData) => {
console.log('Processing successful payment:', paymentData);
const User = require('./models/user');
const Payment = require('./models/payment');
try {
// Save payment record
await new Payment({
userId: paymentData.userId,
amount: paymentData.amount,
currency: paymentData.currency,
paymentId: paymentData.paymentId,
status: paymentData.status,
providerName: paymentData.providerName,
isSubscription: paymentData.isSubscription || false
}).save();
// Update user subscription status
const subscriptionDuration = process.env.SUBSCRIPTION_DURATION_DAYS || 30;
const expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() + subscriptionDuration);
await User.findOneAndUpdate(
{ userId: paymentData.userId },
{
isSubscribed: true,
subscriptionExpiresAt: expiryDate
}
);
console.log(`Updated subscription for user ${paymentData.userId}`);
} catch (err) {
console.error('Error processing payment:', err);
}
});
console.log('Payment webhooks configured');
// Start the Express server for webhooks
const PORT = process.env.PORT || 3000;
console.log('Starting Express server on port', PORT);
app.listen(PORT, () => {
console.log(`Express server is running on port ${PORT}`);
// Start the bot after everything else is ready
console.log('Launching bot...');
bot.launch();
});
} catch (error) {
console.error('Error during bot initialization:', error);
process.exit(1);
}
}).catch(err => {
console.error('MongoDB connection error:', err);
process.exit(1); // Exit if MongoDB connection fails
});
// Add graceful shutdown
process.once('SIGINT', () => {
console.log('SIGINT received, shutting down bot...');
bot.stop('SIGINT');
});
process.once('SIGTERM', () => {
console.log('SIGTERM received, shutting down bot...');
bot.stop('SIGTERM');
});