diff --git a/src/index.ts b/src/index.ts index 6be0d46..89f60c5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -595,14 +595,42 @@ bot.on('text', async (ctx) => { } // No active project session — use chatbot if enabled + // Only respond when bot is mentioned (@username) or message is a reply to bot if (isChatbotEnabled()) { + const botInfo = bot.botInfo; + const botId = botInfo?.id; + const botUsername = botInfo?.username?.toLowerCase(); + + // Check if bot is mentioned via @username in message entities + const entities = ctx.message.entities || []; + const isMentioned = botUsername && entities.some(e => + e.type === 'mention' && + message.substring(e.offset, e.offset + e.length).toLowerCase() === `@${botUsername}` + ); + + // Check if message is a reply to bot's own message + const replyTo = ctx.message.reply_to_message; + const isReplyToBot = replyTo?.from?.id === botId; + + if (!isMentioned && !isReplyToBot) { + // Not addressed to bot — ignore silently + return; + } + + // Strip @mention from message text before sending to Claude + let cleanMessage = message; + if (isMentioned && botUsername) { + cleanMessage = message.replace(new RegExp(`@${botUsername}`, 'gi'), '').trim(); + } + if (!cleanMessage) cleanMessage = message; + const userChatId = ctx.chat.id.toString(); - console.log(`🤖 Chatbot handling message from ${from}: "${message.substring(0, 50)}..."`); + console.log(`🤖 Chatbot handling message from ${from}: "${cleanMessage.substring(0, 50)}..."`); // Fire-and-forget: don't block Telegraf's handler handleChatbotMessage( userChatId, - message, + cleanMessage, async () => { await ctx.sendChatAction('typing'); },