fix(telegram-bot): guard structured message fallback (#1162)

This commit is contained in:
Ryanba
2026-03-06 16:48:31 +08:00
committed by GitHub
parent b9ef42fb85
commit bbf1f19310
2 changed files with 24 additions and 3 deletions
@@ -33,6 +33,18 @@ describe('parseMayStructuredMessage', () => {
expect(result).toMatchObject({ messages: ['Hello, world!', 'Hello, world!'], reply_to_message_id: '1234567890' })
})
it('should fall back to the original text when structured output omits messages', () => {
const text = '{"reply_to_message_id":"1234567890"}'
const result = parseMayStructuredMessage(text)
expect(result).toMatchObject({ messages: [text], reply_to_message_id: '1234567890' })
})
it('should fall back to the original text when structured output uses a non-array messages field', () => {
const text = '{"messages":"Hello, world!"}'
const result = parseMayStructuredMessage(text)
expect(result).toMatchObject({ messages: [text], reply_to_message_id: undefined })
})
it('should return an array of messages from multi-line elements of input', () => {
const result = parseMayStructuredMessage(`{"messages": [
"Hello,
@@ -25,10 +25,19 @@ export function parseMayStructuredMessage(responseText: string) {
if (result) {
logger.withField('text', JSON.stringify(responseText)).withField('result', result).log('Multiple messages detected')
const parsedResponse = parse(result?.[0]) as ({ messages?: string[], reply_to_message_id?: string } | undefined)
parsedResponse.messages = parsedResponse.messages?.filter(message => message.trim() !== '')
const parsedResponse = parse(result[0]) as ({ messages?: unknown, reply_to_message_id?: unknown } | undefined)
const messages = Array.isArray(parsedResponse?.messages)
? parsedResponse.messages.filter((message): message is string => typeof message === 'string' && message.trim() !== '')
: []
const replyToMessageId = typeof parsedResponse?.reply_to_message_id === 'string'
? parsedResponse.reply_to_message_id
: undefined
return parsedResponse
if (messages.length > 0) {
return { messages, reply_to_message_id: replyToMessageId }
}
return { messages: [responseText], reply_to_message_id: replyToMessageId }
}
return { messages: [responseText], reply_to_message_id: undefined }