-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
202 lines (157 loc) · 7.32 KB
/
main.js
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
require('dotenv').config();
const TelegramBot = require('node-telegram-bot-api');
const axios = require('axios');
const { correctGrammar, getUserInfo } = require('./helpers');
const db = require('./database');
const { handleInlineContent } = require('./inline_query');
const { handleYoutubeDownload } = require('./youtubeDownloader');
const fs = require('fs');
const bot = new TelegramBot(process.env.TELEGRAM_BOT_TOKEN, { polling: true });
bot.on('polling_error', (error) => {
console.error('Polling error:', error);
});
// Greet new users
bot.onText(/\/start/, async (msg) => {
const chatId = msg.chat.id;
await db.saveUser(chatId, msg.chat.username);
bot.sendMessage(chatId, `Hello ${msg.chat.first_name}! Welcome to Horan AI.\nSend me any text or image`, {
reply_markup: {
inline_keyboard: [
[{ text: 'Settings', callback_data: 'settings' }]
]
}
});
});
// Inline Query for Translation
bot.on('inline_query', (query) => handleInlineContent(bot, query));
// Check for YouTube video links and handle MP3 download first
bot.on('message', async (msg) => {
const chatId = msg.chat.id;
await db.saveUser(chatId, msg.chat.username);
if (!msg.text || msg.text.startsWith('/')) return;
const youtubeRegex = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/watch\?v=|youtu\.be\/)([\w\-]+)/;
const match = msg.text.match(youtubeRegex);
if (match) {
try {
await bot.sendMessage(chatId, "Processing your YouTube video for MP3 download...");
// Call the handleYoutubeDownload function
const mp3Path = await handleYoutubeDownload(match[0]);
// Send the MP3 file to the user
await bot.sendDocument(chatId, mp3Path);
await bot.sendMessage(chatId, "Here is your MP3 file:");
// Delete the file after successfully sending it
try {
fs.unlinkSync(mp3Path);
console.log(`Deleted file: ${mp3Path}`);
} catch (deleteError) {
console.error(`Error deleting file: ${mp3Path}`, deleteError);
}
} catch (error) {
console.error('Error handling YouTube download:', error);
bot.sendMessage(chatId, "An error occurred while processing the YouTube video.");
}
return;
}
// Existing grammar and translation functionality
try {
const correctedText = await correctGrammar(msg.text);
await bot.sendMessage(
chatId,
`What do you want to do with this message?`,
{
reply_to_message_id: msg.message_id,
reply_markup: {
inline_keyboard: [
[{ text: 'Translate', callback_data: `translate:${msg.message_id}` }, { text: 'Grammar Fix', callback_data: `grammar_fix:${msg.message_id}` }]
]
}
}
);
} catch (error) {
console.error('Error:', error);
bot.sendMessage(chatId, "An error occurred while processing your message.");
}
});
// Handle button clicks for translation and grammar fix
bot.on('callback_query', async (query) => {
const chatId = query.message.chat.id;
if (query.data.startsWith('delete:')) {
try {
const messageIdToDelete = query.message.message_id;
await bot.deleteMessage(chatId, messageIdToDelete);
const userMessageId = query.message.reply_to_message ? query.message.reply_to_message.message_id : null;
if (userMessageId) {
await bot.deleteMessage(chatId, userMessageId);
}
} catch (error) {
console.error('Error deleting messages:', error);
}
}
if (query.message.reply_to_message) {
const userMessageId = query.message.reply_to_message.message_id;
if (query.data.startsWith('translate:')) {
try {
const message = query.message.reply_to_message;
const response = await axios.get(`${process.env.TRANSLATE_API_URL}?q=${encodeURIComponent(message.text)}&target=am`);
const translatedText = decodeURIComponent(response.data.translatedText);
// Increment message count for both translation and grammar fix buttons
const { canSend, totalMessages } = await db.incrementMessageCount(chatId);
if (!canSend) {
return bot.sendMessage(chatId,
"🚨 Oops! You've reached your daily message limit (10 messages). 😔\n\nBut don't worry! You can continue using the bot by buying more credits! 💳✨\n\n👉 Click below to check out your subscription options and get more credits to keep chatting!\n\n🛒 /subscription\n\n💰 <b>Daily Credits Left</b>: 0",
{
parse_mode: 'HTML'
}
);
}
await bot.sendMessage(
chatId,
`<code>${translatedText}</code>\n\n💰 Daily Credits Left: ${10 - totalMessages}`,
{
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: 'Delete', callback_data: `delete:${query.message.message_id}` }]
]
}
}
);
} catch (error) {
console.error('Translation error:', error);
bot.sendMessage(chatId, "Error while translating the text.");
}
}
if (query.data.startsWith('grammar_fix:')) {
try {
const message = query.message.reply_to_message;
const correctedText = await correctGrammar(message.text);
// Increment message count for both translation and grammar fix buttons
const { canSend, totalMessages } = await db.incrementMessageCount(chatId);
if (!canSend) {
return bot.sendMessage(chatId,
"🚨 Oops! You've reached your daily message limit (10 messages). 😔\n\nBut don't worry! You can continue using the bot by buying more credits! 💳✨\n\n👉 Click below to check out your subscription options and get more credits to keep chatting!\n\n🛒 /subscription\n\n💰 <b>Daily Credits Left</b>: 0",
{
parse_mode: 'HTML'
}
);
}
await bot.sendMessage(
chatId,
`<code>${correctedText}</code>\n\n💰 Daily Credits Left: ${10 - totalMessages}`,
{
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: 'Delete', callback_data: `delete:${query.message.message_id}` }]
]
}
}
);
} catch (error) {
console.error('Grammar correction error:', error);
bot.sendMessage(chatId, "Error while correcting grammar.");
}
}
}
});
console.log("LisanBot is running!");