Skip to content

Commit

Permalink
[feat] supabase added
Browse files Browse the repository at this point in the history
  • Loading branch information
chisa-dev committed Jan 3, 2025
1 parent 02eed21 commit 727d890
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 36 deletions.
56 changes: 24 additions & 32 deletions bot.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,49 +33,40 @@ bot.on('callback_query', async (query) => {
}
});

// Function for typing effect
async function sendTypingEffect(bot, chatId, text) {
let message = '';
for (let i = 0; i < text.length; i++) {
message += text[i];
await bot.editMessageText(`<code>${message}</code>\n \n click to copy`, {
chat_id: chatId,
message_id: bot.lastSentMessageId,
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: 'Translate', callback_data: 'translate' }, { text: 'Grammar Fix', callback_data: 'grammar_fix' }],
[{ text: 'Delete', callback_data: `delete:${bot.lastUserMessageId}` }]
]
}
});
await new Promise(res => setTimeout(res, 50));
}
}

// Grammar and Translation
bot.on('message', async (msg) => {
const chatId = msg.chat.id;

// Check if message has text content
if (!msg.text || msg.text.startsWith('/')) return;

try {
const correctedText = await correctGrammar(msg.text);
bot.lastUserMessageId = msg.message_id;
const { canSend, totalMessages } = await db.incrementMessageCount(chatId);
const messagesLeft = 10 - totalMessages;

// Send initial message to start typing effect
const sentMessage = await bot.sendMessage(chatId, '<code></code>', { parse_mode: 'HTML' });
bot.lastSentMessageId = sentMessage.message_id;
if (!canSend) {
return bot.sendMessage(chatId, "You've reached your daily message limit (10 messages). Upgrade to premium for unlimited usage.");
}

// Apply typing effect
await sendTypingEffect(bot, chatId, correctedText);
try {
const correctedText = await correctGrammar(msg.text);
await bot.sendMessage(
chatId,
`<code>${correctedText}</code>\n\n✅ Messages Sent: ${totalMessages}/10\n🕰️ Messages Left: ${messagesLeft}`,
{
parse_mode: 'HTML',
reply_markup: {
inline_keyboard: [
[{ text: 'Translate', callback_data: 'translate' }, { text: 'Grammar Fix', callback_data: 'grammar_fix' }]
]
}
}
);
} catch (error) {
console.error('Error handling message:', error);
console.error('Error:', error);
bot.sendMessage(chatId, "An error occurred while processing your message.");
}
});



bot.on('callback_query', async (query) => {
const chatId = query.message.chat.id;
if (query.data.startsWith('delete')) {
Expand All @@ -89,4 +80,5 @@ bot.on('callback_query', async (query) => {
}
});

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

console.log("LisanBot is running!");
43 changes: 39 additions & 4 deletions database.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,43 @@
const users = {}; // Simple in-memory storage for demonstration
const { createClient } = require('@supabase/supabase-js');
const supabaseUrl = 'https://gaexwodpzfivlcycxzgf.supabase.co';
const supabaseKey = process.env.SUPABASE_KEY;
const supabase = createClient(supabaseUrl, supabaseKey);

async function saveUser(chatId, username) {
users[chatId] = { username };
console.log(`User saved: ${chatId}`);
const { data, error } = await supabase
.from('users')
.insert([{ user_id: chatId, start_date: new Date(), total_messages: 0 }]);
if (error) console.error('Error saving user:', error);
}

module.exports = { saveUser };
async function incrementMessageCount(chatId) {
const { data, error } = 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 };

let newMessageCount = data.total_messages;

if (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;
} 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;
} else {
return { canSend: false, totalMessages: 10 };
}

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

module.exports = { saveUser, incrementMessageCount };

0 comments on commit 727d890

Please sign in to comment.