Skip to content

Commit 481121c

Browse files
committed
fix(draft,voice): defer emoji shortcut, sequential transcription, reduce context
- Emoji-only shortcut now waits DRAFT_PROBE_DELAY before generating (probe text set only after delay, not while user is in chat) - Voice transcription changed from parallel asyncio.gather to sequential loop to avoid Telegram FLOOD_WAIT on TranscribeAudio - Reduce MAX_CONTEXT_MESSAGES from 40 to 30 in config.py - Update README.md: reflect 30-message limit and sequential transcription
1 parent 0c0a1c7 commit 481121c

File tree

4 files changed

+28
-10
lines changed

4 files changed

+28
-10
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ Auto-replies work in private chats only. Draft instructions work everywhere.
1515
## Security
1616

1717
- By default, the bot **only writes drafts** and never sends messages on your behalf. Auto-sending is only possible when the auto-reply timer is explicitly enabled in `/settings`.
18-
- **Messages are not stored.** The bot doesn't save conversations — chat history is fetched via Telegram API on each event and is never persisted. The context is limited to the last 40 messages or 16,000 characters (whichever comes first); older messages are dropped.
18+
- **Messages are not stored.** The bot doesn't save conversations — chat history is fetched via Telegram API on each event and is never persisted. The context is limited to the last 30 messages or 16,000 characters (whichever comes first); older messages are dropped.
1919
- **Saved Messages** (self-chat) and **Telegram service notifications** are fully ignored — the bot doesn't read, draft, or process messages in them. Additional chats can be excluded via `IGNORED_CHAT_IDS` in `config.py`.
2020
- Telegram sessions are encrypted with `Fernet` (`SESSION_ENCRYPTION_KEY`) before being stored in the database.
2121

@@ -121,7 +121,7 @@ You can combine: `😈 tell her I miss her` — switches the style to Seducer an
121121

122122
### Voice Messages and Stickers
123123

124-
All voice messages in the chat history — from both sides (yours and the contact's) — are automatically transcribed via Telegram Premium `TranscribeAudio` and included in the AI context as text. Multiple voice messages are transcribed in parallel. If transcription fails (e.g. no Premium), the message is included as `[voice message]` so the AI still knows a voice was sent. Requires Telegram Premium on the connected account (or trial attempts for free users).
124+
All voice messages in the chat history — from both sides (yours and the contact's) — are automatically transcribed via Telegram Premium `TranscribeAudio` and included in the AI context as text. Voice messages are transcribed sequentially to avoid Telegram rate limits; results are cached so repeated reads don't re-transcribe. If transcription fails (e.g. no Premium), the message is included as `[voice message]` so the AI still knows a voice was sent. Requires Telegram Premium on the connected account (or trial attempts for free users).
125125

126126
Stickers are processed by emoji — the bot sees the sticker's emoji in the conversation context and generates an appropriate reply.
127127

clients/pyrogram_client.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -259,16 +259,18 @@ async def read_chat_history(user_id: int, chat_id: int, limit: int = MAX_CONTEXT
259259
voice_indices.append(idx)
260260
voice_msg_ids.append(msg.id)
261261

262-
# Транскрибируем все голосовые параллельно
262+
# Транскрибируем голосовые последовательно (параллельные вызовы
263+
# вызывают FLOOD_WAIT от Telegram). Кэш в transcribe_voice()
264+
# гарантирует, что повторные вызовы не обращаются к API.
263265
if voice_indices:
264-
transcriptions = await asyncio.gather(
265-
*(transcribe_voice(user_id, chat_id, mid) for mid in voice_msg_ids),
266-
)
267-
for idx, transcription in zip(voice_indices, transcriptions):
266+
ok_count = 0
267+
for idx, mid in zip(voice_indices, voice_msg_ids):
268+
transcription = await transcribe_voice(user_id, chat_id, mid)
268269
messages[idx]["text"] = transcription or "[voice message]"
270+
if transcription:
271+
ok_count += 1
269272

270273
if DEBUG_PRINT:
271-
ok_count = sum(1 for t in transcriptions if t)
272274
print(
273275
f"{get_timestamp()} [PYROGRAM] Transcribed {ok_count}/{len(voice_indices)} "
274276
f"voice messages in chat {chat_id}"

config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@
7373
SYSTEM_MESSAGES_FALLBACK_TTL_SECONDS = 300.0
7474

7575
# ====== КОНТЕКСТ ======
76-
MAX_CONTEXT_MESSAGES = 40 # Макс. кол-во сообщений из чата для контекста
76+
MAX_CONTEXT_MESSAGES = 30 # Макс. кол-во сообщений из чата для контекста
7777
MAX_CONTEXT_CHARS = 16000 # Макс. суммарная длина текста в истории (символы)
7878

7979
# ====== QR LOGIN ======

handlers/pyrogram_handlers.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -693,9 +693,25 @@ async def on_pyrogram_draft(user_id: int, chat_id: int, draft_text: str) -> None
693693
user_settings = (user or {}).get("settings") or {}
694694

695695
if not instruction:
696-
# Только emoji без инструкции — генерируем ответ как on_pyrogram_message
696+
# Только emoji без инструкции — ждём выхода из чата, потом генерируем
697697
_cancel_auto_reply(key)
698698
_bot_drafts.pop(key, None)
699+
_pending_drafts[key] = draft_text
700+
701+
await asyncio.sleep(DRAFT_PROBE_DELAY)
702+
703+
# Проверяем: пользователь не изменил черновик за время ожидания
704+
if _pending_drafts.get(key) != draft_text:
705+
return
706+
_pending_drafts.pop(key, None)
707+
708+
if DEBUG_PRINT:
709+
print(
710+
f"{get_timestamp()} [DRAFT] Processing emoji shortcut for {user_id} "
711+
f"in chat {chat_id}: {emoji_style!r}"
712+
)
713+
714+
# Пользователь вышел — показываем пробу и генерируем
699715
probe_text = (await get_system_message(lang, "draft_typing")).format(emoji=STYLE_TO_EMOJI.get(emoji_style, "🦉"))
700716
_bot_draft_echoes[key] = probe_text
701717
await pyrogram_client.set_draft(user_id, chat_id, probe_text)

0 commit comments

Comments
 (0)