feat: implement word-by-word streaming typing effect
This commit is contained in:
@@ -45,36 +45,48 @@ export async function sendFormatted(ctx, text) {
|
|||||||
export async function sendStreamingMessage(ctx, text, options = {}) {
|
export async function sendStreamingMessage(ctx, text, options = {}) {
|
||||||
if (!text) return;
|
if (!text) return;
|
||||||
|
|
||||||
const { delay = 50, maxChunkSize = 1000 } = options;
|
const {
|
||||||
|
delay = 100,
|
||||||
|
minDelay = 50,
|
||||||
|
maxDelay = 250,
|
||||||
|
charMode = false // Set to true for character-by-character, false for word-by-word
|
||||||
|
} = options;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Stream chunks with typing indicator
|
// Send initial "typing..." indicator
|
||||||
const chunks = splitMessage(text);
|
const sendTyping = () => ctx.api.sendChatAction(ctx.chat.id, 'typing').catch(() => {});
|
||||||
let delayTimer = null;
|
|
||||||
|
if (charMode) {
|
||||||
for (const chunk of chunks) {
|
// Character-by-character streaming
|
||||||
// Clear previous typing indicator
|
let sentText = '';
|
||||||
if (delayTimer) {
|
const chars = text.split('');
|
||||||
clearTimeout(delayTimer);
|
|
||||||
delayTimer = null;
|
for (const char of chars) {
|
||||||
|
sentText += char;
|
||||||
|
|
||||||
|
// Send message with the accumulated text
|
||||||
|
await ctx.reply(sentText, { parse_mode: 'Markdown' });
|
||||||
|
|
||||||
|
// Random delay between min and max
|
||||||
|
const delayMs = minDelay + Math.random() * (maxDelay - minDelay);
|
||||||
|
await new Promise(resolve => setTimeout(resolve, delayMs));
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
// Send chunk with minimal delay for real-time effect
|
// Word-by-word streaming (default)
|
||||||
await ctx.reply(chunk, { parse_mode: 'Markdown' });
|
const words = text.split(' ');
|
||||||
|
let sentText = '';
|
||||||
// Show typing indicator between chunks
|
|
||||||
if (chunks.length > 1) {
|
for (let i = 0; i < words.length; i++) {
|
||||||
delayTimer = setTimeout(() => {
|
sentText += (i > 0 ? ' ' : '') + words[i];
|
||||||
ctx.api.sendChatAction(ctx.chat.id, 'typing').catch(() => {});
|
|
||||||
}, delay);
|
// Send accumulated text
|
||||||
|
await ctx.reply(sentText, { parse_mode: 'Markdown' });
|
||||||
|
|
||||||
|
// Variable delay based on word length
|
||||||
|
const wordDelay = Math.max(minDelay, Math.min(maxDelay, delay + words[i].length * 10));
|
||||||
|
await new Promise(resolve => setTimeout(resolve, wordDelay));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear typing indicator
|
|
||||||
if (delayTimer) {
|
|
||||||
clearTimeout(delayTimer);
|
|
||||||
delayTimer = null;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('Streaming send failed:', error);
|
logger.error('Streaming send failed:', error);
|
||||||
// Fallback to non-streaming
|
// Fallback to non-streaming
|
||||||
|
|||||||
Reference in New Issue
Block a user