Skip to content

Commit

Permalink
Improved Flow
Browse files Browse the repository at this point in the history
  • Loading branch information
chisa-dev committed Jan 7, 2025
1 parent 4601859 commit 17e8cf3
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 56 deletions.
63 changes: 26 additions & 37 deletions database.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,65 +3,54 @@ const supabaseUrl = process.env.SUPABASE_URL;
const supabaseKey = process.env.SUPABASE_KEY;
const supabase = createClient(supabaseUrl, supabaseKey);

// Save user without last_message column
async function saveUser(chatId, username) {
// Check if the user already exists in the database
const { data, error } = await supabase
.from('users')
.select('user_id')
.eq('user_id', chatId)
.single();

// If the user already exists, return early
if (data) {
console.log(`User with ID ${chatId} already exists.`);
return;
}

// If the user does not exist, insert a new record
const { insertData, insertError } = await supabase
.from('users')
.insert([{ user_id: chatId, start_date: new Date(), total_messages: 0 }]);
if (data) return;

if (insertError) {
console.error('Error saving user:', insertError);
} else {
console.log(`User with ID ${chatId} saved successfully.`);
}
await supabase.from('users').insert([{
user_id: chatId,
username: username,
start_date: new Date(),
total_messages: 0,
last_message_date: '' // This field tracks the last message date for rate limiting
}]);
}

// Increment message count
async function incrementMessageCount(chatId) {
const { data, error } = await supabase
const { data } = await supabase
.from('users')
.select('total_messages, last_message_date')
.eq('user_id', chatId)
.single();

const today = new Date().toISOString().split('T')[0];
if (!data) return { canSend: false, totalMessages: 0 };

if (!data) {
// If no data, it means the user doesn't exist in the database, so return a default response
return { canSend: false, totalMessages: 0 };
}

let newMessageCount = data.total_messages;

// Handle case where last_message_date is null
if (data.last_message_date === null || data.last_message_date.split('T')[0] !== today) {
await supabase.from('users')
.update({ total_messages: 1, last_message_date: new Date() })
.eq('user_id', chatId);
newMessageCount = 1;
if (data.last_message_date !== today) {
await supabase.from('users').update({ total_messages: 1, last_message_date: new Date() }).eq('user_id', chatId);
return { canSend: true, totalMessages: 1 };
} else if (data.total_messages < 10) {
await supabase.from('users')
.update({ total_messages: data.total_messages + 1, last_message_date: new Date() })
.eq('user_id', chatId);
newMessageCount = data.total_messages + 1;
await supabase.from('users').update({ total_messages: data.total_messages + 1 }).eq('user_id', chatId);
return { canSend: true, totalMessages: data.total_messages + 1 };
} else {
return { canSend: false, totalMessages: 10 };
}

return { canSend: true, totalMessages: newMessageCount };
}

async function getMessageCount(chatId) {
const { data } = await supabase
.from('users')
.select('total_messages')
.eq('user_id', chatId)
.single();
return data ? data.total_messages : 0;
}

module.exports = { saveUser, incrementMessageCount };
module.exports = { saveUser, incrementMessageCount, getMessageCount };
96 changes: 77 additions & 19 deletions main.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ bot.onText(/\/start/, async (msg) => {
bot.on('callback_query', async (query) => {
const chatId = query.message.chat.id;
if (query.data === 'help') {
bot.sendMessage(chatId, "You can send a message to fix its grammar or translate it! Thank you");
bot.sendMessage(chatId, "You can send a message to fix its grammar or translate it!");
} else if (query.data === 'settings') {
const userInfo = await getUserInfo(chatId);
bot.sendPhoto(chatId, userInfo.profilePicUrl, {
Expand All @@ -47,16 +47,14 @@ bot.on('message', async (msg) => {

try {
const correctedText = await correctGrammar(msg.text);
const userMessageId = msg.message_id;
await bot.sendMessage(
chatId,
`<code>${correctedText}</code>\n\n✅ Messages Sent: ${totalMessages}/10\n🕰️ Messages Left: ${messagesLeft}`,
`What do you want to do with this message?`,
{
parse_mode: 'HTML',
reply_to_message_id: msg.message_id,
reply_markup: {
inline_keyboard: [
[{ text: 'Translate', callback_data: `translate:${encodeURIComponent(msg.text)}` }, { text: 'Grammar Fix', callback_data: 'grammar_fix' }],
[{ text: 'Delete', callback_data: `delete:${userMessageId}` }]
[{ text: 'Translate', callback_data: `translate:${msg.message_id}` }, { text: 'Grammar Fix', callback_data: `grammar_fix:${msg.message_id}` }]
]
}
}
Expand All @@ -67,29 +65,89 @@ bot.on('message', async (msg) => {
}
});


bot.on('callback_query', async (query) => {
const chatId = query.message.chat.id;

if (query.data.startsWith('delete')) {
if (query.data.startsWith('delete:')) {
try {
const [, userMessageId] = query.data.split(':');
await bot.deleteMessage(chatId, query.message.message_id);
await bot.deleteMessage(chatId, userMessageId);
// Get the message ID of the message to delete (the one that contains the inline buttons)
const messageIdToDelete = query.message.message_id;

// Delete the message that contains the inline buttons
await bot.deleteMessage(chatId, messageIdToDelete);

// Optionally, you can also delete the original message that the user replied to
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.data.startsWith('translate')) {
try {
const [, textToTranslate] = query.data.split(':');
const response = await axios.get(`${process.env.TRANSLATE_API_URL}?q=${encodeURIComponent(textToTranslate)}&target=am`);
bot.sendMessage(chatId, `Translated: ${response.data.translatedText}`);
} catch (error) {
console.error('Translation error:', error);
bot.sendMessage(chatId, "Error while translating the text.");
// Handle translation and grammar fix as before
if (query.message.reply_to_message) {
const userMessageId = query.message.reply_to_message.message_id; // Get the replied message ID

if (query.data.startsWith('translate:')) {
try {
// Get the original message that the user replied to
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);

await bot.sendMessage(
chatId,
`<code>${translatedText}</code>\n\n💰 Daily Credits Left: ${10 - await db.getMessageCount(chatId)}`,
{
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 {
// Get the original message that the user replied to
const message = query.message.reply_to_message;

const correctedText = await correctGrammar(message.text);

await bot.sendMessage(
chatId,
`<code>${correctedText}</code>\n\n💰 Daily Credits Left: ${10 - await db.getMessageCount(chatId)}`,
{
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.");
}
}
} else {
// bot.sendMessage(chatId, "No message was replied to. Please reply to a message to perform this action.");
}
});

console.log("LisanBot is running!");




console.log("LisanBot is running!");

0 comments on commit 17e8cf3

Please sign in to comment.