feat: chatbot отвечает только при @упоминании или reply на его сообщение
Бот больше не реагирует на все сообщения в чате. Отвечает только когда: - упомянут через @username в тексте - сообщение является ответом (reply) на сообщение бота @mention автоматически вырезается из текста перед отправкой в Claude. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
32
src/index.ts
32
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');
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user