-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.js
250 lines (223 loc) · 8.3 KB
/
bot.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
const TelegramBot = require('node-telegram-bot-api');
const axios = require('axios');
// Replace with your bot's token and TMDb API key
const token = process.env.YOUR_BOTS_TOKEN;
const tmdbApiKey = process.env.YOUR_TMDb_API_TOKEN;
// Create a bot that uses 'polling' to fetch new updates
const bot = new TelegramBot(token, { polling: true });
// Store user sessions in memory (for simplicity)
let userSessions = {};
// Define genres
const genres = {
action: 28,
adventure: 12,
comedy: 35,
drama: 18,
horror: 27,
science_fiction: 878,
romance: 10749,
thriller: 53,
animation: 16,
family: 10751,
fantasy: 14,
mystery: 9648
};
// Define languages
const languages = {
english: 'en',
hindi: 'hi',
spanish: 'es',
french: 'fr',
german: 'de',
japanese: 'ja',
korean: 'ko',
chinese: 'zh'
};
// Listen for '/start' command
bot.onText(/\/start/, (msg) => {
const chatId = msg.chat.id;
bot.sendMessage(chatId, "Welcome to MovieSuggester! 🎬 Use the button below to get started.", {
reply_markup: {
inline_keyboard: [
[{ text: 'Get Movie Recommendations', callback_data: 'recommend' }]
]
}
});
});
// Handle callback queries from inline buttons
bot.on('callback_query', async (callbackQuery) => {
const chatId = callbackQuery.message.chat.id;
const data = callbackQuery.data;
const userSession = userSessions[chatId];
if (data === 'recommend') {
startRecommendationProcess(chatId);
} else if (Object.keys(genres).includes(data)) {
handleGenreSelection(chatId, data);
} else if (Object.keys(languages).includes(data)) {
handleLanguageSelection(chatId, data);
} else if (data === 'generate_more') {
handleGenerateMore(chatId, userSession);
} else if (data === 'back_to_menu') {
startRecommendationProcess(chatId);
}
// Answer the callback query to remove the loading state
bot.answerCallbackQuery(callbackQuery.id);
});
function startRecommendationProcess(chatId) {
userSessions[chatId] = { recommendations: [] }; // Initialize a new session
bot.sendMessage(chatId, "Please choose a genre:", {
reply_markup: {
inline_keyboard: createButtonGrid(Object.keys(genres), 3)
}
});
}
function handleGenreSelection(chatId, genre) {
userSessions[chatId].genre = genre;
bot.sendMessage(chatId, "Great! Now, please choose a language:", {
reply_markup: {
inline_keyboard: createButtonGrid(Object.keys(languages), 3)
}
});
}
async function handleLanguageSelection(chatId, language) {
// Ensure user session is initialized
if (!userSessions[chatId]) {
console.log(`Initializing session for chatId: ${chatId}`);
userSessions[chatId] = { recommendations: [] }; // Initialize with an empty array
}
const userSession = userSessions[chatId];
// Check if userSession is still undefined
if (!userSession) {
console.error(`User session for chatId ${chatId} is undefined.`);
bot.sendMessage(chatId, "Something went wrong. Please start over.");
return;
}
// Check if the userSession has a genre set before setting language
if (!userSession.genre) {
bot.sendMessage(chatId, "Please select a genre first.");
return;
}
userSession.language = language;
bot.sendMessage(chatId, "Fetching movie recommendations for you...");
try {
const response = await axios.get('https://api.themoviedb.org/3/discover/movie', {
params: {
api_key: tmdbApiKey,
language: 'en-US',
sort_by: 'popularity.desc',
with_genres: genres[userSession.genre],
with_original_language: languages[language]
}
});
const movies = response.data.results;
userSession.recommendations = movies;
if (movies.length > 0) {
await sendRecommendations(chatId, movies.slice(0, 5));
userSession.recommendations = movies.slice(5);
if (userSession.recommendations.length > 0) {
bot.sendMessage(chatId, "Would you like to see more recommendations?", {
reply_markup: {
inline_keyboard: [
[{ text: 'Show More', callback_data: 'generate_more' }],
[{ text: 'Start Over', callback_data: 'recommend' }]
]
}
});
} else {
bot.sendMessage(chatId, "That's all the recommendations I have for now. Would you like to start over?", {
reply_markup: {
inline_keyboard: [
[{ text: 'Start Over', callback_data: 'recommend' }]
]
}
});
}
} else {
bot.sendMessage(chatId, `Sorry, I couldn't find any ${userSession.genre} movies in ${language}. Would you like to try again?`, {
reply_markup: {
inline_keyboard: [
[{ text: 'Try Again', callback_data: 'recommend' }]
]
}
});
}
} catch (error) {
bot.sendMessage(chatId, "Sorry, something went wrong while fetching recommendations. Please try again.", {
reply_markup: {
inline_keyboard: [
[{ text: 'Try Again', callback_data: 'recommend' }]
]
}
});
}
}
async function handleGenerateMore(chatId, userSession) {
if (!userSession) {
bot.sendMessage(chatId, "It seems that your session has expired. Please start over to get new recommendations.", {
reply_markup: {
inline_keyboard: [
[{ text: 'Start Over', callback_data: 'recommend' }]
]
}
});
return;
}
if (userSession.recommendations.length > 0) {
const moviesToShow = userSession.recommendations.slice(0, 5);
await sendRecommendations(chatId, moviesToShow);
userSession.recommendations = userSession.recommendations.slice(5);
if (userSession.recommendations.length > 0) {
bot.sendMessage(chatId, "Would you like to see more recommendations?", {
reply_markup: {
inline_keyboard: [
[{ text: 'Show More', callback_data: 'generate_more' }],
[{ text: 'Start Over', callback_data: 'recommend' }]
]
}
});
} else {
bot.sendMessage(chatId, "That's all the recommendations I have for now. Would you like to start over?", {
reply_markup: {
inline_keyboard: [
[{ text: 'Start Over', callback_data: 'recommend' }]
]
}
});
}
} else {
bot.sendMessage(chatId, "No more recommendations available. Would you like to start over?", {
reply_markup: {
inline_keyboard: [
[{ text: 'Start Over', callback_data: 'recommend' }]
]
}
});
}
}
// Function to send recommendations
const sendRecommendations = async (chatId, movies) => {
for (const movie of movies) {
const posterUrl = movie.poster_path ? `https://image.tmdb.org/t/p/w500${movie.poster_path}` : null;
const movieDetails = `
*${movie.title}* (${movie.release_date.split('-')[0]})
*Rating:* ${movie.vote_average}/10
*Overview:* ${movie.overview || 'No overview available.'}
`;
if (posterUrl) {
await bot.sendPhoto(chatId, posterUrl, { caption: movieDetails, parse_mode: 'Markdown' });
} else {
await bot.sendMessage(chatId, movieDetails, { parse_mode: 'Markdown' });
}
}
};
// Helper function to create a grid of buttons
function createButtonGrid(items, columnsPerRow) {
return items.reduce((acc, item, index) => {
const row = Math.floor(index / columnsPerRow);
if (!acc[row]) {
acc[row] = [];
}
acc[row].push({ text: item.charAt(0).toUpperCase() + item.slice(1), callback_data: item });
return acc;
}, []);
}