1
0
mirror of https://github.com/InsanusMokrassar/TelegramBotAPI.git synced 2024-06-01 15:35:24 +00:00
tgbotapi/tgbotapi.utils/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/utils/extensions/TextCaptionBotCommandsParser.kt

55 lines
1.9 KiB
Kotlin
Raw Normal View History

package dev.inmo.tgbotapi.extensions.utils.extensions
2022-05-01 16:13:40 +00:00
import dev.inmo.tgbotapi.abstracts.TextedWithTextSources
import dev.inmo.tgbotapi.types.message.abstracts.ContentMessage
import dev.inmo.tgbotapi.types.message.content.TextContent
2022-08-05 10:35:07 +00:00
import dev.inmo.tgbotapi.types.message.textsources.BotCommandTextSource
import dev.inmo.tgbotapi.types.message.textsources.TextSource
val defaultArgsSeparator = Regex(" ")
/**
* Parse commands and their args. Logic will find command, get all subsequent data as args until new command
*/
fun List<TextSource>.parseCommandsWithParams(
argsSeparator: Regex = defaultArgsSeparator
): MutableMap<String, Array<String>> {
val result = mutableMapOf<String, Array<String>>()
var currentBotCommandSource: BotCommandTextSource? = null
var currentArgs = ""
fun includeCurrent() = currentBotCommandSource ?.let {
2021-04-12 19:50:41 +00:00
currentArgs = currentArgs.trim()
2021-04-29 09:07:16 +00:00
result[it.command] = if (currentArgs.isNotEmpty()) {
currentArgs.split(argsSeparator).toTypedArray()
} else {
emptyArray()
2021-04-12 19:50:41 +00:00
}
2021-04-29 09:07:16 +00:00
currentArgs = ""
2021-04-29 09:09:45 +00:00
currentBotCommandSource = null
}
for (textSource in this) {
if (textSource is BotCommandTextSource) {
includeCurrent()
currentBotCommandSource = textSource
} else {
currentArgs += textSource.source
}
}
includeCurrent()
return result
}
/**
* Parse commands and their args. Logic will find command, get all subsequent data as args until new command
*/
fun TextedWithTextSources.parseCommandsWithParams(
argsSeparator: Regex = defaultArgsSeparator
2021-04-29 05:52:38 +00:00
) = textSources ?.parseCommandsWithParams(argsSeparator) ?: emptyMap()
2021-03-24 07:44:27 +00:00
/**
* Parse commands and their args. Logic will find command, get all subsequent data as args until new command
*/
fun ContentMessage<TextContent>.parseCommandsWithParams(
argsSeparator: Regex = defaultArgsSeparator
) = content.parseCommandsWithParams(argsSeparator)