feat: 将 TelegramBots 升级至 8.0.0, 并适配 TelegramBots 的新改动.

将 TelegramBots 升级至新版本, 以支持新的 API.
由于 TelegramBots 发生无法兼容旧版本的重大变更, 因此 ScalaBot 将随着此次更新一同进行重大更改.

BREAKING CHANGE: ScalaBot 所依赖的 TelegramBots 发生重大更改, 所有扩展都需要进行适配.
  有关 TelegramBots 的重大变更说明请参考官方文档.
  ScalaBot 的最低 Java 版本已全部升级至 Java 17 (这是 TelegramBots 的最低兼容性要求), 所有扩展都应该至少迁移至 Java 17 版本.
  ScalaBot 的重大更改:
   - scalabot-extension
     - `net.lamgc.scalabot.extension.util.AbilityBots.getBotAccountId(BaseAbilityBot): long` 已被移除, 由于 BaseAbilityBot 不再允许获取 botToken, 因此该方法被移除. 作为代替, 请通过 `net.lamgc.scalabot.extension.BotExtensionFactory.createExtensionInstance` 所得到的 `BotExtensionCreateOptions` 中获取 botAccountId.

  另外, scalabot-extension 中的 `org.jetbrains.kotlinx.binary-compatibility-validator` 似乎不再对 Java 代码起作用, 因此移除该插件, 并在后续寻找替代品.
  TelegramBots 文档: https://rubenlagus.github.io/TelegramBotsDocumentation/how-to-update-7.html
This commit is contained in:
2024-12-10 23:32:29 +08:00
parent bac7239513
commit e1c87aeae4
23 changed files with 487 additions and 209 deletions

View File

@ -22,6 +22,7 @@ dependencies {
implementation("org.eclipse.aether:aether-transport-http:$aetherVersion")
implementation("org.eclipse.aether:aether-connector-basic:$aetherVersion")
implementation("org.apache.maven:maven-aether-provider:3.3.9")
implementation("org.codehaus.plexus:plexus-utils:3.5.1")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.3")
implementation("org.jetbrains.kotlin:kotlin-reflect:1.9.23")
@ -29,8 +30,9 @@ dependencies {
implementation("org.jdom:jdom2:2.0.6.1")
implementation("org.telegram:telegrambots-abilities:6.9.7.1")
implementation("org.telegram:telegrambots:6.9.7.1")
implementation("org.telegram:telegrambots-abilities:8.0.0")
implementation("org.telegram:telegrambots-longpolling:8.0.0")
implementation("org.telegram:telegrambots-client:8.0.0")
implementation("io.prometheus:simpleclient:0.16.0")
implementation("io.prometheus:simpleclient_httpserver:0.16.0")
@ -46,7 +48,7 @@ tasks.test {
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "11"
kotlinOptions.jvmTarget = "17"
}
application {

View File

@ -13,7 +13,6 @@ import org.eclipse.aether.repository.Proxy
import org.eclipse.aether.repository.RemoteRepository
import org.eclipse.aether.repository.RepositoryPolicy
import org.slf4j.event.Level
import org.telegram.telegrambots.bots.DefaultBotOptions
import java.io.File
import java.net.URL
import java.nio.charset.StandardCharsets
@ -24,13 +23,13 @@ import kotlin.reflect.KProperty
private val log = KotlinLogging.logger { }
internal fun ProxyType.toTelegramBotsType(): DefaultBotOptions.ProxyType {
internal fun ProxyType.toJavaProxyType(): java.net.Proxy.Type? {
return when (this) {
ProxyType.NO_PROXY -> DefaultBotOptions.ProxyType.NO_PROXY
ProxyType.HTTP -> DefaultBotOptions.ProxyType.HTTP
ProxyType.HTTPS -> DefaultBotOptions.ProxyType.HTTP
ProxyType.SOCKS4 -> DefaultBotOptions.ProxyType.SOCKS4
ProxyType.SOCKS5 -> DefaultBotOptions.ProxyType.SOCKS5
ProxyType.NO_PROXY -> null
ProxyType.HTTP -> java.net.Proxy.Type.HTTP
ProxyType.HTTPS -> java.net.Proxy.Type.HTTP
ProxyType.SOCKS4 -> java.net.Proxy.Type.SOCKS
ProxyType.SOCKS5 -> java.net.Proxy.Type.SOCKS
}
}
@ -310,7 +309,7 @@ internal fun initialFiles(): Boolean {
val configFilesNotInitialized = !AppPaths.CONFIG_APPLICATION.file.exists()
&& !AppPaths.CONFIG_BOT.file.exists()
for (path in AppPaths.values()) {
for (path in AppPaths.entries) {
path.initial()
}

View File

@ -6,15 +6,17 @@ import kotlinx.coroutines.runBlocking
import mu.KotlinLogging
import net.lamgc.scalabot.config.*
import net.lamgc.scalabot.util.registerShutdownHook
import okhttp3.OkHttpClient
import org.eclipse.aether.repository.LocalRepository
import org.telegram.telegrambots.bots.DefaultBotOptions
import org.telegram.telegrambots.meta.TelegramBotsApi
import org.telegram.telegrambots.client.okhttp.OkHttpTelegramClient
import org.telegram.telegrambots.longpolling.BotSession
import org.telegram.telegrambots.longpolling.TelegramBotsLongPollingApplication
import org.telegram.telegrambots.meta.api.methods.GetMe
import org.telegram.telegrambots.meta.exceptions.TelegramApiRequestException
import org.telegram.telegrambots.meta.generics.BotSession
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession
import java.io.File
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Proxy
import java.nio.file.attribute.PosixFilePermission
import java.nio.file.attribute.PosixFilePermissions
import kotlin.io.path.createDirectories
@ -74,7 +76,7 @@ internal class Launcher(
private val log = KotlinLogging.logger { }
}
private val botApi = TelegramBotsApi(DefaultBotSession::class.java)
private val botApi = TelegramBotsLongPollingApplication()
private val botSessionMap = mutableMapOf<ScalaBot, BotSession>()
private val mavenLocalRepository = getMavenLocalRepository()
@ -144,6 +146,10 @@ internal class Launcher(
}
}
}
botApi.start()
botApi.registerShutdownHook()
return if (launchedCounts != 0) {
log.info { "已启动 $launchedCounts 个机器人." }
true
@ -171,17 +177,17 @@ internal class Launcher(
ProxyConfig(type = ProxyType.NO_PROXY)
}
val botOption = DefaultBotOptions().apply {
if (proxyConfig.type != ProxyType.NO_PROXY) {
proxyType = proxyConfig.type.toTelegramBotsType()
proxyHost = config.proxy.host
proxyPort = config.proxy.port
log.debug { "机器人 `${botConfig.account.name}` 已启用代理配置: $proxyConfig" }
}
val okhttpClientBuilder = OkHttpClient.Builder()
baseUrl = botConfig.baseApiUrl
if (proxyConfig.type != ProxyType.NO_PROXY) {
val proxyType = proxyConfig.type.toJavaProxyType()
val proxyAddress = InetSocketAddress.createUnresolved(proxyConfig.host, proxyConfig.port)
okhttpClientBuilder.proxy(Proxy(proxyType, proxyAddress))
}
val account = botConfig.account
val telegramClient =
OkHttpTelegramClient(okhttpClientBuilder.build(), account.token, botConfig.getBaseApiTelegramUrl())
val remoteRepositories = config.mavenRepositories
.map { it.toRemoteRepository(proxyConfig) }
@ -203,15 +209,15 @@ internal class Launcher(
val bot = ScalaBot(
BotDBMaker.getBotDbInstance(account),
botOption,
telegramClient,
extensionPackageFinders,
botConfig
)
val botUser = bot.execute(GetMe())
val botUser = bot.telegramClient.execute(GetMe())
log.debug { "已验证 Bot Token 有效性, Bot Username: ${botUser.userName}" }
botSessionMap[bot] = botApi.registerBot(bot)
botSessionMap[bot] = botApi.registerBot(botConfig.account.token, bot)
log.info { "机器人 `${bot.botUsername}` 已启动." }
if (botConfig.autoUpdateCommandList) {

View File

@ -7,8 +7,8 @@ import net.lamgc.scalabot.util.toHexString
import org.mapdb.DB
import org.mapdb.DBException
import org.mapdb.DBMaker
import org.telegram.abilitybots.api.db.DBContext
import org.telegram.abilitybots.api.db.MapDBContext
import org.telegram.telegrambots.abilitybots.api.db.DBContext
import org.telegram.telegrambots.abilitybots.api.db.MapDBContext
import java.io.File
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
@ -157,7 +157,6 @@ private abstract class FileDbAdapter(
val oldFile = oldDbAdapter.getBotDbFile(botAccount)
val newFile = getBotDbFile(botAccount)
try {
@Suppress("UnstableApiUsage")
Files.copy(oldFile, newFile)
} catch (e: Exception) {
if (newFile.exists()) {
@ -190,4 +189,4 @@ private object BotTokenDbAdapter : FileDbAdapter("BotToken_v0.1.0", { botAccount
val digest: MessageDigest = MessageDigest.getInstance("SHA-256")
val digestBytes = digest.digest(botAccount.token.toByteArray(StandardCharsets.UTF_8))
File(AppPaths.DATA_DB.file, "${digestBytes.toHexString()}.db")
})
})

View File

@ -5,7 +5,7 @@ import net.lamgc.scalabot.extension.BotExtensionCreateOptions
import net.lamgc.scalabot.extension.BotExtensionFactory
import net.lamgc.scalabot.util.getPriority
import org.eclipse.aether.artifact.Artifact
import org.telegram.abilitybots.api.util.AbilityExtension
import org.telegram.telegrambots.abilitybots.api.util.AbilityExtension
import java.io.File
import java.io.FileNotFoundException
import java.net.URL
@ -126,6 +126,7 @@ internal class ExtensionLoader(
factory.createExtensionInstance(
bot, getExtensionDataFolder(extensionArtifact),
BotExtensionCreateOptions(
bot.accountId,
bot.botConfig.proxy.copy()
)
)
@ -158,7 +159,7 @@ internal class ExtensionLoader(
* 搜索指定构件坐标的依赖包.
*
* 搜索扩展包将根据搜索器优先级从高到低依次搜索, 当某一个优先级的搜索器搜到扩展包后将停止搜索.
* 可以根据不同优先级的搜索器, 配置扩展包的主用备用文件.
* 可以根据不同优先级的搜索器, 配置扩展包的主用备用文件.
*
* @return 返回各个搜索器返回的搜索结果.
*/

View File

@ -6,43 +6,42 @@ import io.prometheus.client.Summary
import mu.KotlinLogging
import net.lamgc.scalabot.config.BotConfig
import org.eclipse.aether.artifact.Artifact
import org.telegram.abilitybots.api.bot.AbilityBot
import org.telegram.abilitybots.api.db.DBContext
import org.telegram.abilitybots.api.objects.Ability
import org.telegram.abilitybots.api.toggle.BareboneToggle
import org.telegram.abilitybots.api.toggle.DefaultToggle
import org.telegram.telegrambots.bots.DefaultBotOptions
import org.telegram.telegrambots.abilitybots.api.bot.AbilityBot
import org.telegram.telegrambots.abilitybots.api.db.DBContext
import org.telegram.telegrambots.abilitybots.api.objects.Ability
import org.telegram.telegrambots.abilitybots.api.toggle.BareboneToggle
import org.telegram.telegrambots.abilitybots.api.toggle.DefaultToggle
import org.telegram.telegrambots.meta.api.methods.commands.DeleteMyCommands
import org.telegram.telegrambots.meta.api.methods.commands.SetMyCommands
import org.telegram.telegrambots.meta.api.objects.Update
import org.telegram.telegrambots.meta.api.objects.commands.BotCommand
import org.telegram.telegrambots.meta.generics.TelegramClient
/**
* 可扩展 Bot.
* @property creatorId 机器人所有人的 Telegram 用户 Id. 可通过联系部分机器人来获取该信息.
* @property creatorId 机器人所有人的 Telegram 用户 ID. 可通过联系部分机器人来获取该信息.
* (e.g. [@userinfobot](http://t.me/userinfobot))
* @param db 机器人数据库对象. 用于状态机等用途.
* @param options AbilityBot 设置对象.
* @property extensions 扩展坐标集合.
*/
@Suppress("CanBeParameter", "MemberVisibilityCanBePrivate")
internal class ScalaBot(
db: DBContext,
options: DefaultBotOptions,
client: TelegramClient,
extensionFinders: Set<ExtensionPackageFinder>,
val botConfig: BotConfig,
private val creatorId: Long = botConfig.account.creatorId,
val accountId: Long = botConfig.account.id,
private val creatorId: Long = botConfig.account.creatorId,
val extensions: Set<Artifact> = botConfig.extensions
) :
AbilityBot(
botConfig.account.token,
client,
botConfig.account.name,
db,
if (botConfig.disableBuiltInAbility)
BareboneToggle()
else
DefaultToggle(),
options
DefaultToggle()
) {
private val extensionLoader = ExtensionLoader(
@ -67,13 +66,13 @@ internal class ScalaBot(
override fun creatorId(): Long = creatorId
override fun onUpdateReceived(update: Update?) {
override fun consume(update: Update?) {
botUpdateCounter.labels(botUsername, accountIdString).inc()
botUpdateGauge.labels(botUsername, accountIdString).inc()
val timer = updateProcessTime.labels(botUsername, accountIdString).startTimer()
try {
super.onUpdateReceived(update)
super.consume(update)
} catch (e: Exception) {
exceptionHandlingCounter.labels(botUsername, accountIdString).inc()
throw e
@ -92,11 +91,11 @@ internal class ScalaBot(
* @return 更新成功返回 `true`.
*/
fun updateCommandList(): Boolean {
if (abilities() == null) {
if (abilities == null) {
throw IllegalStateException("Abilities has not been initialized.")
}
val botCommands = abilities().values.map {
val botCommands = abilities.values.map {
val abilityInfo = if (it.info() == null || it.info().trim().isEmpty()) {
log.warn { "[Bot $botUsername] Ability `${it.name()}` 没有说明信息." }
"(The command has no description)"
@ -112,9 +111,10 @@ internal class ScalaBot(
return true
}
val setMyCommands = SetMyCommands()
setMyCommands.commands = botCommands
return execute(DeleteMyCommands()) && execute(setMyCommands)
val setMyCommands = SetMyCommands.builder()
.commands(botCommands)
.build()
return telegramClient.execute(DeleteMyCommands()) && telegramClient.execute(setMyCommands)
}
override fun onRegister() {
@ -122,10 +122,6 @@ internal class ScalaBot(
onlineBotGauge.inc()
}
override fun onClosing() {
onlineBotGauge.dec()
}
companion object {
@JvmStatic
private val log = KotlinLogging.logger { }

View File

@ -0,0 +1,29 @@
package net.lamgc.scalabot.util
import java.util.regex.Matcher
import java.util.regex.Pattern
object TelegramBotAccounts {
private val botTokenPattern: Pattern = Pattern.compile("([1-9]\\d+):([A-Za-z\\d_-]{35,})")
/**
* 获取 AbilityBot 的账户 Id.
*
*
* 账户 Id 来自于 botToken 中, token 的格式为 "{AccountId}:{Secret}".
*
* 账户 Id 的真实性与 botToken 的有效性有关, 本方法并不会确保 botToken 的有效性, 一般情况下也无需考虑 Id 的有效性,
* 如果有需要, 可尝试通过调用 [org.telegram.telegrambots.meta.api.methods.GetMe] 来确保 botToken 的有效性.
*
* @param botToken 要获取账户 Id 的 botToken 字符串.
* @return 返回 AbilityBot 的账户 Id.
* @throws IllegalArgumentException 当 AbilityBot 的 botToken 格式错误时抛出该异常.
*/
fun getBotAccountId(botToken: String): Long {
val matcher: Matcher = botTokenPattern.matcher(botToken)
require(matcher.matches()) { "Invalid token format." }
return matcher.group(1).toLong()
}
}

View File

@ -10,9 +10,9 @@ import net.lamgc.scalabot.config.ProxyConfig
import net.lamgc.scalabot.config.ProxyType
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.io.TempDir
import org.telegram.telegrambots.bots.DefaultBotOptions
import java.io.File
import java.io.IOException
import java.net.Proxy
import java.net.URL
import java.nio.file.Files
import java.nio.file.Path
@ -23,7 +23,7 @@ internal class AppPathsTest {
@Test
fun `Consistency check`() {
for (path in AppPaths.values()) {
for (path in AppPaths.entries) {
assertEquals(
File(path.path).canonicalPath,
path.file.canonicalPath,
@ -226,17 +226,17 @@ internal class AppPathsTest {
@Test
fun `ProxyType_toTelegramBotsType test`() {
val expectTypeMapping = mapOf(
ProxyType.NO_PROXY to DefaultBotOptions.ProxyType.NO_PROXY,
ProxyType.SOCKS5 to DefaultBotOptions.ProxyType.SOCKS5,
ProxyType.SOCKS4 to DefaultBotOptions.ProxyType.SOCKS4,
ProxyType.HTTP to DefaultBotOptions.ProxyType.HTTP,
ProxyType.HTTPS to DefaultBotOptions.ProxyType.HTTP
ProxyType.NO_PROXY to null,
ProxyType.SOCKS5 to Proxy.Type.SOCKS,
ProxyType.SOCKS4 to Proxy.Type.SOCKS,
ProxyType.HTTP to Proxy.Type.HTTP,
ProxyType.HTTPS to Proxy.Type.HTTP
)
for (proxyType in ProxyType.values()) {
for (proxyType in ProxyType.entries) {
assertEquals(
expectTypeMapping[proxyType],
proxyType.toTelegramBotsType(),
proxyType.toJavaProxyType(),
"ProxyType 转换失败."
)
}
@ -251,7 +251,7 @@ internal class AppPathsTest {
ProxyType.HTTP,
ProxyType.HTTPS
)
for (proxyType in ProxyType.values()) {
for (proxyType in ProxyType.entries) {
val proxyConfig = ProxyConfig(proxyType, host, port)
val aetherProxy = proxyConfig.toAetherProxy()
if (expectNotNullProxyType.contains(proxyType)) {
@ -337,7 +337,7 @@ internal class AppPathsTest {
assertTrue(initialFiles(), "方法未能提醒用户编辑初始配置文件.")
for (path in AppPaths.values()) {
for (path in AppPaths.entries) {
assertTrue(path.file.exists(), "文件未初始化成功: ${path.path}")
if (path.file.isFile) {
assertNotEquals(0, path.file.length(), "文件未初始化成功(大小为 0): ${path.path}")
@ -347,7 +347,7 @@ internal class AppPathsTest {
assertFalse(initialFiles(), "方法试图在配置已初始化的情况下提醒用户编辑初始配置文件.")
for (path in AppPaths.values()) {
for (path in AppPaths.entries) {
assertTrue(path.file.exists(), "文件未初始化成功: ${path.path}")
if (path.file.isFile) {
assertNotEquals(0, path.file.length(), "文件未初始化成功(大小为 0): ${path.path}")
@ -358,7 +358,7 @@ internal class AppPathsTest {
assertTrue(AppPaths.CONFIG_APPLICATION.file.delete(), "config.json 删除失败.")
assertFalse(initialFiles(), "方法试图在部分配置已初始化的情况下提醒用户编辑初始配置文件.")
for (path in AppPaths.values()) {
for (path in AppPaths.entries) {
assertTrue(path.file.exists(), "文件未初始化成功: ${path.path}")
if (path.file.isFile) {
assertNotEquals(0, path.file.length(), "文件未初始化成功(大小为 0): ${path.path}")
@ -369,7 +369,7 @@ internal class AppPathsTest {
assertTrue(AppPaths.CONFIG_BOT.file.delete(), "bot.json 删除失败.")
assertFalse(initialFiles(), "方法试图在部分配置已初始化的情况下提醒用户编辑初始配置文件.")
for (path in AppPaths.values()) {
for (path in AppPaths.entries) {
assertTrue(path.file.exists(), "文件未初始化成功: ${path.path}")
if (path.file.isFile) {
assertNotEquals(0, path.file.length(), "文件未初始化成功(大小为 0): ${path.path}")
@ -384,7 +384,7 @@ internal class AppPathsTest {
"在主要配置文件(config.json 和 bot.json)不存在的情况下初始化文件后, 方法未能提醒用户编辑初始配置文件."
)
for (path in AppPaths.values()) {
for (path in AppPaths.entries) {
assertTrue(path.file.exists(), "文件未初始化成功: ${path.path}")
if (path.file.isFile) {
assertNotEquals(0, path.file.length(), "文件未初始化成功(大小为 0): ${path.path}")

View File

@ -0,0 +1,27 @@
package util
import net.lamgc.scalabot.util.TelegramBotAccounts
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test
class TelegramBotAccountsTest {
@Test
fun getBotAccountIdTest() {
val expectToken = "1234567890:AAHXcNDBRZTKfyPED5Gi3PZDIKPOM6xhxwo"
val actual: Long = TelegramBotAccounts.getBotAccountId(expectToken)
assertEquals(1234567890, actual)
val badTokenA = "12c34d56a7890:AAHXcNDBRZTKfyPED5Gi3PZDIKPOM6xhxwo"
assertThrows(
IllegalArgumentException::class.java
) { TelegramBotAccounts.getBotAccountId(badTokenA) }
val badTokenB = "12c34d56a7890AAHXcNDBRZTKfyPED5Gi3PZDIKPOM6xhxwo"
assertThrows(
IllegalArgumentException::class.java
) { TelegramBotAccounts.getBotAccountId(badTokenB) }
}
}