From b4ef91cc77ff6a2a5173124719b1bf5dec81274b Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Thu, 17 Jan 2019 09:42:23 +0800 Subject: [PATCH] Added "createMarkdownText" and extensions for "CaptionedMediaContent" and "TextContent" --- CHANGELOG | 2 + .../TelegramBotAPI/utils/CaptionSourcer.kt | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 src/main/kotlin/com/github/insanusmokrassar/TelegramBotAPI/utils/CaptionSourcer.kt diff --git a/CHANGELOG b/CHANGELOG index eac6be6cd6..b49e4d2a2b 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -17,3 +17,5 @@ * Now `ForwardedMessage` contains nullable `from` ## 0.8.4 + +* Added `createMarkdownText` and extensions for `CaptionedMediaContent` and `TextContent` diff --git a/src/main/kotlin/com/github/insanusmokrassar/TelegramBotAPI/utils/CaptionSourcer.kt b/src/main/kotlin/com/github/insanusmokrassar/TelegramBotAPI/utils/CaptionSourcer.kt new file mode 100644 index 0000000000..2af9230a2b --- /dev/null +++ b/src/main/kotlin/com/github/insanusmokrassar/TelegramBotAPI/utils/CaptionSourcer.kt @@ -0,0 +1,38 @@ +package com.github.insanusmokrassar.TelegramBotAPI.utils + +import com.github.insanusmokrassar.TelegramBotAPI.types.MessageEntity.MessageEntity +import com.github.insanusmokrassar.TelegramBotAPI.types.message.content.TextContent +import com.github.insanusmokrassar.TelegramBotAPI.types.message.content.abstracts.CaptionedMediaContent + +fun createMarkdownText( + text: String, + messageEntities: List +): String { + val builder = StringBuilder() + var offset = 0 + for (entity in messageEntities) { + builder.append( + text.substring(offset until entity.offset) + ) + builder.append( + entity.asMarkdownSource + ) + offset += entity.length + } + builder.append( + text.substring(offset) + ) + return builder.toString() +} + +fun CaptionedMediaContent.toMarkdownCaption(): String? = caption ?.let { + createMarkdownText( + it, + captionEntities + ) +} + +fun TextContent.toMarkdownText(): String = createMarkdownText( + text, + entities +)