65 lines
2.2 KiB
Kotlin
65 lines
2.2 KiB
Kotlin
package net.lamgc.scext.onedrive_transfer
|
|
|
|
import com.google.common.cache.Cache
|
|
import org.telegram.telegrambots.abilitybots.api.bot.BaseAbilityBot
|
|
import org.telegram.telegrambots.meta.api.methods.send.SendMessage
|
|
import org.telegram.telegrambots.meta.api.methods.updatingmessages.DeleteMessage
|
|
import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText
|
|
import org.telegram.telegrambots.meta.api.objects.message.Message
|
|
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException
|
|
import java.net.URL
|
|
import java.net.URLDecoder
|
|
|
|
fun URL.getQueryMap(): Map<String, String> {
|
|
val queryMap = mutableMapOf<String, String>()
|
|
query.split("&").forEach {
|
|
val pair = it.split("=")
|
|
queryMap[pair[0]] = URLDecoder.decode(pair[1], "UTF-8")
|
|
}
|
|
return queryMap
|
|
}
|
|
|
|
// 生成大小写字母加数字的随机字符串
|
|
fun randomString(length: Int): String {
|
|
val charPool = ('a'..'z') + ('A'..'Z') + ('0'..'9')
|
|
return (1..length)
|
|
.map { kotlin.random.Random.nextInt(0, charPool.size) }
|
|
.map(charPool::get)
|
|
.joinToString("")
|
|
}
|
|
|
|
fun Cache<String, String>.putToken(value: String, tokenLength: Int = 16, tokenPrefix: String = ""): String {
|
|
val token = randomString(tokenLength)
|
|
put(token, value)
|
|
return "$tokenPrefix$token"
|
|
}
|
|
|
|
fun EditMessageText.orSendMessage(bot: BaseAbilityBot, replyMessageId: Int, tryRemove: Boolean = true): Message? {
|
|
try {
|
|
bot.telegramClient.execute(this)
|
|
return null
|
|
} catch (e: TelegramApiRequestException) {
|
|
if (e.errorCode != 400 || e.apiResponse != "message can't be edited") {
|
|
throw e
|
|
}
|
|
return bot.telegramClient.execute(
|
|
SendMessage.builder()
|
|
.replyToMessageId(replyMessageId)
|
|
.chatId(chatId.toString())
|
|
.text(text)
|
|
.build()
|
|
)
|
|
} finally {
|
|
if (tryRemove) {
|
|
try {
|
|
bot.telegramClient.execute(
|
|
DeleteMessage.builder()
|
|
.messageId(messageId)
|
|
.build()
|
|
)
|
|
} catch (_: Exception) {
|
|
}
|
|
}
|
|
}
|
|
}
|