initial: 基本完成的首个版本, 还需要调整一下.

暂时按照当初的计划实现了一个可用版本出来, 发布与否晚些再确定.
This commit is contained in:
LamGC 2022-01-16 20:21:18 +08:00
parent cbaeb2ce00
commit 37f0d4e6b8
Signed by: LamGC
GPG Key ID: 6C5AE2A913941E1D
28 changed files with 1513 additions and 0 deletions

10
.gitignore vendored
View File

@ -21,3 +21,13 @@
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid* hs_err_pid*
# Gradle output and caches directory
.gradle/
build/
# local test directory
run/*
# Ide files
/.idea/

11
build.gradle.kts Normal file
View File

@ -0,0 +1,11 @@
allprojects {
repositories {
mavenCentral()
}
dependencies {
}
group = "net.lamgc"
version = "0.0.1-SNAPSHOT"
}

1
gradle.properties Normal file
View File

@ -0,0 +1 @@
kotlin.code.style=official

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Normal file
View File

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright ? 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions ?$var?, ?${var}?, ?${var:-default}?, ?${var+SET}?,
# ?${var#prefix}?, ?${var%suffix}?, and ?$( cmd )?;
# * compound commands having a testable exit status, especially ?case?;
# * various built-in commands including ?command?, ?set?, and ?ulimit?.
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

89
gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,42 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.6.10"
application
// id("org.jetbrains.kotlin") version "1.6.10"
}
dependencies {
implementation(project(":scalabot-extension"))
implementation("org.slf4j:slf4j-api:1.7.32")
implementation("io.github.microutils:kotlin-logging:2.1.21")
implementation("ch.qos.logback:logback-classic:1.2.10")
implementation("org.eclipse.aether:aether-api:1.1.0")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0")
implementation("com.google.code.gson:gson:2.8.9")
// implementation("org.dom4j:dom4j:2.1.3")
implementation("org.jdom:jdom2:2.0.6.1")
implementation("org.telegram:telegrambots-abilities:5.6.0")
implementation("org.telegram:telegrambots:5.6.0")
testImplementation(kotlin("test"))
}
tasks.test {
useJUnitPlatform()
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "11"
}
application {
mainClass.set("net.lamgc.scalabot.AppMainKt")
}

View File

@ -0,0 +1,16 @@
package net.lamgc.scalabot.util;
final class ByteUtils {
private ByteUtils() {
}
public static String bytesToHexString(byte[] bytes) {
StringBuilder builder = new StringBuilder();
for (byte aByte : bytes) {
builder.append(Integer.toHexString(aByte));
}
return builder.toString();
}
}

View File

@ -0,0 +1,26 @@
package net.lamgc.scalabot.util;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.filter.AbstractMatcherFilter;
import ch.qos.logback.core.spi.FilterReply;
/**
* 标准输出过滤器.
*
* <p> LogBack 在性能上虽然很好但是自带的 ThresholdFilter 竟然不支持过滤 WARN 以下等级的日志
* 重点是加两个参数就可以实现这个过滤功能了加一个 onMatch onMismatch 就可以了
* 绝了
*
* @author LamGC
*/
public class StdOutFilter extends AbstractMatcherFilter<LoggingEvent> {
private final static int maxLevel = Level.INFO_INT;
@Override
public FilterReply decide(LoggingEvent event) {
int levelInt = event.getLevel().levelInt;
return levelInt <= maxLevel ? FilterReply.ACCEPT : FilterReply.DENY;
}
}

View File

@ -0,0 +1,178 @@
package net.lamgc.scalabot
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import mu.KotlinLogging
import net.lamgc.scalabot.util.ArtifactSerializer
import net.lamgc.scalabot.util.ProxyTypeSerializer
import org.eclipse.aether.artifact.Artifact
import org.telegram.telegrambots.bots.DefaultBotOptions
import java.io.File
import java.nio.charset.StandardCharsets
import java.util.concurrent.atomic.AtomicBoolean
private val log = KotlinLogging.logger { }
/**
* 机器人帐号信息.
* @property name 机器人名称, 建议与实际设定的名称相同.
* @property token 机器人 API Token.
* @property creatorId 机器人创建者, 管理机器人需要使用该信息.
*/
internal data class BotAccount(
val name: String,
val token: String,
val creatorId: Long = -1
)
/**
* 机器人配置.
* @property account 机器人帐号信息, 用于访问 API.
* @property disableBuiltInAbility 是否禁用 AbilityBot 自带命令.
* @property extensions 该机器人启用的扩展.
* @property proxy 为该机器人单独设置的代理配置, 如无设置, 则使用 AppConfig 中的代理配置.
*/
internal data class BotConfig(
val enabled: Boolean = true,
val account: BotAccount,
val disableBuiltInAbility: Boolean = true,
/*
* 使用构件坐标来选择机器人所使用的扩展包.
* 这么做的原因是我暂时没找到一个合适的方法来让开发者方便地设定自己的扩展 Id,
* 而构件坐标(POM Reference 或者叫 GAV 坐标)是开发者创建 Maven/Gradle 项目所一定会设置的,
* 所以就直接用了. :P
*/
val extensions: Set<Artifact>,
val proxy: ProxyConfig? = null,
val baseApiUrl: String? = null
)
/**
* 代理配置.
* @property type 代理类型.
* @property host 代理服务端地址.
* @property port 代理服务端端口.
*/
internal data class ProxyConfig(
val type: DefaultBotOptions.ProxyType = DefaultBotOptions.ProxyType.NO_PROXY,
val host: String = "127.0.0.1",
val port: Int = 1080
)
/**
* ScalaBot App 配置.
*
* App 配置信息与 BotConfig 分开, 分别存储在各自单独的文件中.
* @property proxy Telegram API 代理配置.
*/
internal data class AppConfig(
val proxy: ProxyConfig = ProxyConfig(),
)
/**
* 需要用到的路径.
*/
internal enum class AppPaths(
private val pathSupplier: () -> String,
private val initializer: AppPaths.() -> Unit = AppPaths::defaultInitializer
) {
DEFAULT_CONFIG_APPLICATION({ "./config.json" }, {
if (!file.exists()) {
file.bufferedWriter(StandardCharsets.UTF_8).use {
GsonConst.botConfigGson.toJson(AppConfig(), it)
}
}
}),
DEFAULT_CONFIG_BOT({ "./bot.json" }, {
if (!file.exists()) {
file.bufferedWriter(StandardCharsets.UTF_8).use {
GsonConst.botConfigGson.toJson(
setOf(
BotConfig(
enabled = false,
proxy = ProxyConfig(),
account = BotAccount(
"Bot Username",
"Bot API Token",
-1
), extensions = emptySet()
)
), it
)
}
}
}),
DATA_DB({ "./data/db/" }),
DATA_LOGS({ "./data/logs/" }),
EXTENSIONS({ "./extensions/" }),
DATA_EXTENSIONS({ "./data/extensions/" }),
TEMP({ "./tmp/" })
;
val file: File
get() = File(pathSupplier.invoke())
val path: String
get() = pathSupplier.invoke()
private val initialized = AtomicBoolean(false)
@Synchronized
fun initial() {
if (!initialized.get()) {
initializer(this)
initialized.set(true)
}
}
}
internal object Const {
val config = loadAppConfig()
}
private fun AppPaths.defaultInitializer() {
if (!file.exists()) {
val result = if (path.endsWith("/")) {
file.mkdirs()
} else {
file.createNewFile()
}
if (!result) {
log.warn { "初始化文件(夹)失败: $path" }
}
}
}
internal fun initialFiles() {
for (path in AppPaths.values()) {
path.initial()
}
}
private object GsonConst {
val baseGson: Gson = GsonBuilder()
.setPrettyPrinting()
.serializeNulls()
.create()
val appConfigGson: Gson = baseGson.newBuilder()
.registerTypeAdapter(DefaultBotOptions.ProxyType::class.java, ProxyTypeSerializer)
.create()
val botConfigGson: Gson = baseGson.newBuilder()
.registerTypeAdapter(DefaultBotOptions.ProxyType::class.java, ProxyTypeSerializer)
.registerTypeAdapter(Artifact::class.java, ArtifactSerializer)
.create()
}
internal fun loadAppConfig(configFile: File = AppPaths.DEFAULT_CONFIG_APPLICATION.file): AppConfig {
configFile.bufferedReader(StandardCharsets.UTF_8).use {
return GsonConst.appConfigGson.fromJson(it, AppConfig::class.java)!!
}
}
internal fun loadBotConfig(botConfigFile: File = AppPaths.DEFAULT_CONFIG_BOT.file): Set<BotConfig> {
botConfigFile.bufferedReader(StandardCharsets.UTF_8).use {
return GsonConst.botConfigGson.fromJson(it, object : TypeToken<Set<BotConfig>>() {}.type)!!
}
}

View File

@ -0,0 +1,88 @@
package net.lamgc.scalabot
import kotlinx.coroutines.runBlocking
import mu.KotlinLogging
import org.telegram.telegrambots.bots.DefaultBotOptions
import org.telegram.telegrambots.meta.TelegramBotsApi
import org.telegram.telegrambots.meta.generics.BotSession
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession
import kotlin.system.exitProcess
private val log = KotlinLogging.logger { }
private val launcher = Launcher()
fun main(args: Array<String>): Unit = runBlocking {
log.info { "ScalaBot 正在启动中..." }
log.debug { "启动参数: ${args.joinToString(prefix = "[", postfix = "]")}" }
initialFiles()
if (!launcher.launch()) {
exitProcess(1)
}
}
internal class Launcher {
companion object {
@JvmStatic
private val log = KotlinLogging.logger { }
}
private val botApi = TelegramBotsApi(DefaultBotSession::class.java)
private val botSessionMap = mutableMapOf<ScalaBot, BotSession>()
fun launch(): Boolean {
val botConfigs = loadBotConfig()
if (botConfigs.isEmpty()) {
log.warn { "尚未配置任何机器人, 请先配置机器人后再启动本程序." }
return false
}
for (botConfig in botConfigs) {
launchBot(botConfig)
}
return true
}
private fun launchBot(botConfig: BotConfig) {
if (!botConfig.enabled) {
log.debug { "机器人 `${botConfig.account.name}` 已禁用, 跳过启动." }
return
}
log.info { "正在启动机器人 `${botConfig.account.name}`..." }
val botOption = DefaultBotOptions().apply {
val proxyConfig =
if (botConfig.proxy != null && botConfig.proxy.type != DefaultBotOptions.ProxyType.NO_PROXY) {
botConfig.proxy
} else if (Const.config.proxy.type != DefaultBotOptions.ProxyType.NO_PROXY) {
Const.config.proxy
} else {
null
}
if (proxyConfig != null) {
proxyType = proxyConfig.type
proxyHost = Const.config.proxy.host
proxyPort = Const.config.proxy.port
log.debug { "机器人 `${botConfig.account.name}` 已启用代理配置: $proxyConfig" }
}
if (botConfig.baseApiUrl != null) {
baseUrl = botConfig.baseApiUrl
}
}
val account = botConfig.account
val bot = ScalaBot(
account.name,
account.token,
account.creatorId,
BotDBMaker.getBotMaker(account),
botOption,
botConfig.extensions,
botConfig.disableBuiltInAbility
)
botSessionMap[bot] = botApi.registerBot(bot)
log.info { "机器人 `${bot.botUsername}` 已启动." }
}
}

View File

@ -0,0 +1,25 @@
package net.lamgc.scalabot
import net.lamgc.scalabot.util.toHaxString
import org.mapdb.DBMaker
import org.telegram.abilitybots.api.db.DBContext
import org.telegram.abilitybots.api.db.MapDBContext
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
internal object BotDBMaker {
private val digest: MessageDigest = MessageDigest.getInstance("SHA-256")
fun getBotMaker(botAccount: BotAccount): DBContext {
val digestBytes = digest.digest(botAccount.token.toByteArray(StandardCharsets.UTF_8))
val dbPath = AppPaths.DATA_DB.path + "${digestBytes.toHaxString()}.db"
val db = DBMaker.fileDB(dbPath)
.closeOnJvmShutdownWeakReference()
.checksumStoreEnable()
.fileChannelEnable()
.make()
return MapDBContext(db)
}
}

View File

@ -0,0 +1,367 @@
package net.lamgc.scalabot
import mu.KotlinLogging
import net.lamgc.scalabot.extension.BotExtensionFactory
import net.lamgc.scalabot.util.deepListFiles
import net.lamgc.scalabot.util.equalsArtifact
import org.eclipse.aether.artifact.Artifact
import org.eclipse.aether.artifact.DefaultArtifact
import org.jdom2.Document
import org.jdom2.filter.Filters
import org.jdom2.input.SAXBuilder
import org.jdom2.xpath.XPathFactory
import org.telegram.abilitybots.api.util.AbilityExtension
import java.io.File
import java.io.InputStream
import java.net.URL
import java.net.URLClassLoader
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
import java.util.jar.JarEntry
import java.util.jar.JarInputStream
internal class ExtensionLoader(private val bot: ScalaBot) {
private val log = KotlinLogging.logger { }
private val finders: Set<ExtensionPackageFinder> = setOf(
FileNameFinder,
MavenMetaInformationFinder
)
fun getExtensions(): Set<ExtensionEntry> {
val extensionEntries = mutableSetOf<ExtensionEntry>()
for (extensionArtifact in bot.extensions) {
val extensionFilesMap = findExtensionPackageFile(extensionArtifact)
val extensionFiles = filesMapToSet(extensionFilesMap)
if (extensionFiles.size > 1) {
printExtensionFileConflictError(extensionArtifact, extensionFilesMap)
continue
} else if (extensionFiles.isEmpty()) {
log.warn { "[Bot ${bot.botUsername}] 找不到符合的扩展包文件: $extensionArtifact" }
continue
}
extensionEntries.addAll(getExtensionFactories(extensionArtifact, extensionFiles.first()))
}
return extensionEntries.toSet()
}
private fun getExtensionFactories(extensionArtifact: Artifact, extensionFile: File): Set<ExtensionEntry> {
val extClassLoader =
ExtensionClassLoaderCleaner.getOrCreateExtensionClassLoader(extensionArtifact, extensionFile)
val factories = mutableSetOf<ExtensionEntry>()
for (factory in extClassLoader.serviceLoader) {
val extension =
factory.createExtensionInstance(bot, getExtensionDataFolder(extensionArtifact))
factories.add(ExtensionEntry(extensionArtifact, factory::class.java, extension))
}
return factories.toSet()
}
private fun filesMapToSet(filesMap: Map<ExtensionPackageFinder, Set<File>>): MutableSet<File> {
val result: MutableSet<File> = mutableSetOf()
for (files in filesMap.values) {
result.addAll(files)
}
return result
}
private fun findExtensionPackageFile(
extensionArtifact: Artifact,
extensionsPath: File = AppPaths.EXTENSIONS.file
): Map<ExtensionPackageFinder, Set<File>> {
val result = mutableMapOf<ExtensionPackageFinder, Set<File>>()
for (finder in finders) {
val artifacts = finder.findByArtifact(extensionArtifact, extensionsPath)
if (artifacts.isNotEmpty()) {
result[finder] = artifacts
}
}
return result
}
private fun printExtensionFileConflictError(
extensionArtifact: Artifact,
foundResult: Map<ExtensionPackageFinder, Set<File>>
) {
val errMessage = StringBuilder(
"""
[Bot ${bot.botUsername}] 扩展包 $extensionArtifact 存在多个文件, 为防止安全问题, 已禁止加载该扩展包:
""".trimIndent()
).append('\n')
foundResult.forEach { (finder, files) ->
errMessage.append("\t- 搜索器 `").append(finder::class.simpleName).append("` 找到了以下扩展包: \n")
for (file in files) {
errMessage.append("\t\t* ").append(file.canonicalPath).append('\n')
}
}
log.error { errMessage }
}
private fun getExtensionDataFolder(extensionArtifact: Artifact): File {
val dataFolder =
File(AppPaths.DATA_EXTENSIONS.file, "${extensionArtifact.groupId}/${extensionArtifact.artifactId}")
if (!dataFolder.exists()) {
dataFolder.mkdirs()
}
return dataFolder
}
data class ExtensionEntry(
val extensionArtifact: Artifact,
val factoryClass: Class<out BotExtensionFactory>,
val extension: AbilityExtension
)
}
/**
* 该类为保留措施, 尚未启用.
*/
internal object ExtensionClassLoaderCleaner {
private val artifactMap = mutableMapOf<Artifact, ExtensionClassLoader>()
private val usageCountMap = mutableMapOf<ExtensionClassLoader, AtomicInteger>()
@Synchronized
fun getOrCreateExtensionClassLoader(extensionArtifact: Artifact, extensionFile: File): ExtensionClassLoader {
return if (!artifactMap.containsKey(extensionArtifact)) {
val newClassLoader = ExtensionClassLoader(extensionFile)
artifactMap[extensionArtifact] = newClassLoader
usageCountMap[newClassLoader] = AtomicInteger(1)
newClassLoader
} else {
artifactMap[extensionArtifact]!!
}
}
@Synchronized
fun releaseExtensionClassLoader(extensionArtifacts: Set<Artifact>) {
for (extensionArtifact in extensionArtifacts) {
if (!artifactMap.containsKey(extensionArtifact)) {
throw IllegalStateException("No corresponding classloader exists.")
}
val classLoader = artifactMap[extensionArtifact]!!
val usageCounter = usageCountMap[classLoader]!!
if (usageCounter.decrementAndGet() == 0) {
cleanExtensionClassLoader(extensionArtifact)
}
}
}
private fun cleanExtensionClassLoader(extensionArtifact: Artifact) {
if (!artifactMap.containsKey(extensionArtifact)) {
return
}
val classLoader = artifactMap.remove(extensionArtifact)!!
try {
classLoader.close()
} finally {
usageCountMap.remove(classLoader)
}
}
}
/**
* 扩展包搜索器.
*
* 通过实现该接口, 可添加一种搜索扩展包的方式, 无论其来源.
*/
internal interface ExtensionPackageFinder {
/**
* 在指定目录中搜索指定构件坐标的扩展包文件().
* @param extensionArtifact 欲查找的扩展包构件坐标.
* @param extensionsPath 建议的搜索路径, 如搜索器希望通过网络来获取也可以.
* @return 返回按搜索器的方式可以找到的所有与构件坐标有关的扩展包路径.
*/
fun findByArtifact(extensionArtifact: Artifact, extensionsPath: File): Set<File>
}
/**
* 基于文件名的搜索器.
*
* 将搜索文件名(不带扩展包名)结尾为 `${groupId}-${artifactId}-${version}` 的文件.
*/
internal object FileNameFinder : ExtensionPackageFinder {
override fun findByArtifact(extensionArtifact: Artifact, extensionsPath: File): Set<File> {
val focusName = getExtensionFilename(extensionArtifact)
val files = extensionsPath.listFiles { file ->
file.nameWithoutExtension.endsWith(focusName)
}
return files?.toSet() ?: emptySet()
}
private fun getExtensionFilename(extensionArtifact: Artifact) =
"${extensionArtifact.groupId}_${extensionArtifact.artifactId}_${extensionArtifact.version}"
}
internal object MavenMetaInformationFinder : ExtensionPackageFinder {
private const val MAVEN_META_XML = "pom.xml"
private const val MAVEN_META_PROPERTIES = "pom.properties"
override fun findByArtifact(extensionArtifact: Artifact, extensionsPath: File): Set<File> {
val files = extensionsPath.listFiles() ?: return emptySet()
val result = mutableSetOf<File>()
for (file in files) {
if (file.isFile) {
val foundArtifact = when (file.extension) {
"jar", "zip" -> {
getArtifactCoordinateFromArtifactJar(file)
}
// 尚不清楚 jmod 的具体结构细节, 担心在 Maven 正式支持 jmod 之后会出现变数, 故暂不支持.
"jmod" -> null
else -> null
}
if (foundArtifact != null && extensionArtifact.equalsArtifact(foundArtifact)) {
result.add(file)
}
} else if (file.isDirectory) {
val foundArtifact = getArtifactCoordinateFromArtifactDirectory(file)
if (foundArtifact != null && extensionArtifact.equalsArtifact(foundArtifact)) {
result.add(file)
}
}
}
return if (result.isEmpty()) emptySet() else result
}
private fun getArtifactCoordinateFromArtifactDirectory(dir: File): Artifact? {
if (!dir.isDirectory) {
return null
}
val mavenMetaRoot = File(dir, "META-INF/maven/")
if (!mavenMetaRoot.exists() || !mavenMetaRoot.isDirectory) {
return null
}
val files = mavenMetaRoot.deepListFiles(filenameFilter = { _, name ->
name != null && (name.contentEquals(MAVEN_META_XML) || name.contentEquals(MAVEN_META_PROPERTIES))
})
val metaFile = files?.firstOrNull() ?: return null
return when (metaFile.extension.lowercase()) {
"xml" -> metaFile.inputStream().use { getArtifactFromPomXml(it) }
"properties" -> metaFile.inputStream().use { getArtifactFromPomProperties(it) }
else -> null
}
}
private fun getArtifactCoordinateFromArtifactJar(file: File): Artifact? {
if (!file.isFile) {
return null
}
file.inputStream().use {
val jarInputStream = JarInputStream(it)
var entry: JarEntry?
while (true) {
entry = jarInputStream.nextJarEntry
if (entry == null) {
break
}
if (entry.name.startsWith("META-INF/maven")) {
val artifact = if (entry.name.endsWith(MAVEN_META_XML)) {
getArtifactFromPomXml(jarInputStream)
} else if (entry.name.endsWith(MAVEN_META_PROPERTIES)) {
getArtifactFromPomProperties(jarInputStream)
} else {
continue
}
return artifact
}
}
}
return null
}
// language=XPATH
private const val XPATH_POM_ARTIFACT = "/project/artifactId"
// language=XPATH
private const val XPATH_POM_GROUP = "/project/groupId"
// language=XPATH
private const val XPATH_POM_PARENT_GROUP = "/project/parent/groupId"
// language=XPATH
private const val XPATH_POM_VERSION = "/project/version"
// language=XPATH
private const val XPATH_POM_PARENT_VERSION = "/project/parent/version"
// Packaging 也等同于 Extension(Artifact 里的)
// language=XPATH
private const val XPATH_POM_PACKAGING = "/project/packaging"
private val xmlReader = SAXBuilder()
private val xPathFactory = XPathFactory.instance()
private fun getArtifactFromPomXml(input: InputStream): DefaultArtifact? {
val document = xmlReader.build(input) ?: return null
val artifactName = querySelectorContent(document, XPATH_POM_ARTIFACT) ?: return null
val groupId =
querySelectorContent(document, XPATH_POM_GROUP) ?: querySelectorContent(document, XPATH_POM_PARENT_GROUP)
?: return null
val version = querySelectorContent(document, XPATH_POM_VERSION) ?: querySelectorContent(
document,
XPATH_POM_PARENT_VERSION
) ?: return null
val extensionName = querySelectorContent(document, XPATH_POM_PACKAGING)
return DefaultArtifact(groupId, artifactName, extensionName, version)
}
private fun querySelectorContent(doc: Document, xPath: String): String? =
xPathFactory.compile(xPath, Filters.element()).evaluateFirst(doc).text
private const val PROP_KEY_GROUP = "groupId"
private const val PROP_KEY_ARTIFACT = "artifactId"
private const val PROP_KEY_VERSION = "version"
private fun getArtifactFromPomProperties(input: InputStream): DefaultArtifact? {
val prop = Properties()
prop.load(input)
if (isEmptyOrNull(prop, PROP_KEY_GROUP) || isEmptyOrNull(prop, PROP_KEY_ARTIFACT) || isEmptyOrNull(
prop,
PROP_KEY_VERSION
)
) {
return null
}
return DefaultArtifact(
prop.getProperty(PROP_KEY_GROUP),
prop.getProperty(PROP_KEY_ARTIFACT),
null,
prop.getProperty(PROP_KEY_VERSION)
)
}
private fun isEmptyOrNull(prop: Properties, key: String): Boolean =
!prop.containsKey(key) || prop.getProperty(key).trim().isEmpty()
}
/**
* 扩展包专属的类加载器.
*
* 通过为每个扩展包提供专门的加载器, 可防止意外使用其他扩展的类(希望如此).
*/
internal class ExtensionClassLoader(extensionFile: File) :
URLClassLoader(arrayOf(URL("file:///${extensionFile.canonicalPath}"))) {
val serviceLoader: ServiceLoader<BotExtensionFactory> = ServiceLoader.load(BotExtensionFactory::class.java, this)
}

View File

@ -0,0 +1,41 @@
package net.lamgc.scalabot
import mu.KotlinLogging
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.toggle.BareboneToggle
import org.telegram.abilitybots.api.toggle.DefaultToggle
import org.telegram.telegrambots.bots.DefaultBotOptions
internal class ScalaBot(
name: String,
token: String,
private val creatorId: Long,
db: DBContext,
options: DefaultBotOptions,
val extensions: Set<Artifact>,
disableBuiltInAbility: Boolean
) :
AbilityBot(token, name, db, if (disableBuiltInAbility) DefaultToggle() else BareboneToggle(), options) {
companion object {
@JvmStatic
private val log = KotlinLogging.logger { }
}
private val extensionLoader = ExtensionLoader(this)
init {
val extensionEntries = extensionLoader.getExtensions()
for (entry in extensionEntries) {
addExtension(entry.extension)
log.debug {
"[Bot ${botUsername}] 扩展包 `${entry.extensionArtifact}` 中的扩展 `${entry.extension::class.qualifiedName}` " +
"(由工厂类 `${entry.factoryClass.name}` 创建) 已注册."
}
}
}
override fun creatorId(): Long = creatorId
}

View File

@ -0,0 +1,57 @@
package net.lamgc.scalabot.util
import com.google.gson.*
import org.eclipse.aether.artifact.Artifact
import org.eclipse.aether.artifact.DefaultArtifact
import org.telegram.telegrambots.bots.DefaultBotOptions
import java.lang.reflect.Type
object ProxyTypeSerializer : JsonDeserializer<DefaultBotOptions.ProxyType>,
JsonSerializer<DefaultBotOptions.ProxyType> {
override fun deserialize(
json: JsonElement,
typeOfT: Type?,
context: JsonDeserializationContext?
): DefaultBotOptions.ProxyType {
if (!json.isJsonPrimitive) {
throw JsonParseException("Wrong configuration value type.")
}
val value = json.asString.trim()
try {
return DefaultBotOptions.ProxyType.valueOf(value.uppercase())
} catch (e: IllegalArgumentException) {
throw JsonParseException("Invalid value: $value")
}
}
override fun serialize(
src: DefaultBotOptions.ProxyType,
typeOfSrc: Type?,
context: JsonSerializationContext?
): JsonElement {
return JsonPrimitive(src.toString())
}
}
object ArtifactSerializer : JsonSerializer<Artifact>, JsonDeserializer<Artifact> {
override fun serialize(src: Artifact, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement {
val gavBuilder = StringBuilder("${src.groupId}:${src.artifactId}")
if (!src.extension.equals("jar")) {
gavBuilder.append(':').append(src.extension)
}
if (src.classifier.isNotEmpty()) {
gavBuilder.append(':').append(src.classifier)
}
return JsonPrimitive(gavBuilder.append(':').append(src.version).toString())
}
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): Artifact {
if (!json!!.isJsonPrimitive) {
throw JsonParseException("Wrong configuration value type.")
}
return DefaultArtifact(json.asString.trim())
}
}

View File

@ -0,0 +1,55 @@
package net.lamgc.scalabot.util
import org.eclipse.aether.artifact.Artifact
import java.io.File
import java.io.FileFilter
import java.io.FilenameFilter
internal fun ByteArray.toHaxString(): String = ByteUtils.bytesToHexString(this)
internal fun Artifact.equalsArtifact(that: Artifact): Boolean =
this.groupId.equals(that.groupId) &&
this.artifactId.equals(that.artifactId) &&
this.version.equals(that.version) &&
this.baseVersion.equals(that.baseVersion) &&
this.isSnapshot == that.isSnapshot &&
this.classifier.equals(that.classifier) &&
this.extension.equals(that.extension) &&
(if (this.file == null) that.file == null else this.file.equals(that.file)) &&
this.properties.equals(that.properties)
internal fun File.deepListFiles(
addSelf: Boolean = false,
onlyFile: Boolean = false,
fileFilter: FileFilter? = null,
filenameFilter: FilenameFilter? = null
): Array<File>? {
val files = if (fileFilter != null) {
this.listFiles(fileFilter)
} else if (filenameFilter != null) {
this.listFiles(filenameFilter)
} else {
this.listFiles()
}
if (files == null) {
return null
}
val result = if (addSelf) mutableSetOf(this) else mutableSetOf()
for (file in files) {
if (file.isFile) {
result.add(file)
} else {
if (!onlyFile) {
result.add(file)
}
val subFiles = file.deepListFiles(false, onlyFile, fileFilter, filenameFilter)
if (subFiles != null) {
result.addAll(subFiles)
}
}
}
return result.toTypedArray()
}

View File

@ -0,0 +1,37 @@
<configuration scan="false" debug="false">
<appender name="STD_OUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{HH:mm:ss.SSS} %5level][%logger{36}][%thread]: %msg%n</pattern>
</encoder>
<filter class="net.lamgc.scalabot.util.StdOutFilter">
</filter>
</appender>
<appender name="STD_ERR" class="ch.qos.logback.core.ConsoleAppender">
<target>System.err</target>
<encoder>
<pattern>%red([%d{HH:mm:ss.SSS} %5level][%logger{36}][%thread]: %msg%n)</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>WARN</level>
</filter>
</appender>
<appender name="FILE_OUT" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>data/logs/latest.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>data/logs/%d{yyyy-MM-dd}.log.gz</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>[%d{HH:mm:ss.SSS} %5level][%logger{36}][%thread]: %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="FILE_OUT"/>
<appender-ref ref="STD_ERR" additivity="false"/>
<appender-ref ref="STD_OUT"/>
</root>
</configuration>

View File

@ -0,0 +1,35 @@
@file:Suppress("PackageDirectoryMismatch")
package net.lamgc.scalabot.util
import com.google.gson.JsonObject
import com.google.gson.JsonParseException
import com.google.gson.JsonPrimitive
import org.eclipse.aether.artifact.DefaultArtifact
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
internal class ArtifactSerializerTest {
@Test
fun badJsonType() {
assertFailsWith<JsonParseException> { ArtifactSerializer.deserialize(JsonObject(), null, null) }
}
@Test
fun serialize() {
val gav = "org.example.software:test:1.0.0-SNAPSHOT"
val expectArtifact = DefaultArtifact(gav)
val actualArtifact = DefaultArtifact(ArtifactSerializer.serialize(expectArtifact, null, null).asString)
assertEquals(expectArtifact, actualArtifact)
}
@Test
fun deserialize() {
val gav = "org.example.software:test:1.0.0-SNAPSHOT"
val expectArtifact = DefaultArtifact(gav)
val actualArtifact = ArtifactSerializer.deserialize(JsonPrimitive(gav), null, null)
assertEquals(expectArtifact, actualArtifact)
}
}

View File

@ -0,0 +1,19 @@
package net.lamgc.scalabot.util
import org.eclipse.aether.artifact.DefaultArtifact
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
internal class UtilsKtTest {
@Test
fun `Extension Function - Artifact_equalsArtifact`() {
val equalGAV = "org.example:demo:1.0.0-SNAPSHOT"
assertTrue(DefaultArtifact(equalGAV).equalsArtifact(DefaultArtifact(equalGAV)))
assertFalse(
DefaultArtifact("org.example:demo:1.0.0")
.equalsArtifact(DefaultArtifact("com.example:demo-2:1.0.0-SNAPSHOT"))
)
}
}

View File

@ -0,0 +1,18 @@
plugins {
java
}
repositories {
mavenCentral()
}
dependencies {
compileOnly(project(":scalabot-extension"))
testImplementation("org.junit.jupiter:junit-jupiter-api:5.6.0")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
}
tasks.getByName<Test>("test") {
useJUnitPlatform()
}

View File

@ -0,0 +1,53 @@
package net.lamgc.scalabot.simple;
import org.telegram.abilitybots.api.bot.BaseAbilityBot;
import org.telegram.abilitybots.api.objects.*;
import org.telegram.abilitybots.api.util.AbilityExtension;
public class SayHelloExtension implements AbilityExtension {
/**
* 扩展所属的机器人对象.
*
* <p> 创建 ReplyFlow 时需要使用 Bot DBContext.
*/
private final BaseAbilityBot bot;
public SayHelloExtension(BaseAbilityBot bot) {
this.bot = bot;
}
public Ability sayHello() {
return Ability.builder()
.name("say_hello")
.info("Say hello to you.")
.privacy(Privacy.PUBLIC)
.locality(Locality.ALL)
.action(ctx -> ctx.bot().silent().send("Hello! " + ctx.user().getUserName(), ctx.chatId()))
.build();
}
/**
* 更具特色的 `Say hello`.
*/
public Ability test() {
ReplyFlow botHello = ReplyFlow.builder(bot.db())
.action((bot, upd) -> bot.silent().send("What is u name?", upd.getMessage().getChatId()))
.onlyIf(update -> "hello".equalsIgnoreCase(update.getMessage().getText()))
.next(Reply.of((bot, upd) -> bot.silent()
.send("OK! You name is " + upd.getMessage().getText().substring("my name is ".length()), upd.getMessage().getChatId()),
upd -> upd.getMessage().getText().startsWith("my name is ")))
.build();
return Ability.builder()
.name("hello")
.info("Say hello!")
.locality(Locality.ALL)
.privacy(Privacy.PUBLIC)
.enableStats()
.action(ctx -> ctx.bot().silent().send("Hello!", ctx.chatId()))
.reply(botHello)
.build();
}
}

View File

@ -0,0 +1,16 @@
package net.lamgc.scalabot.simple;
import net.lamgc.scalabot.extension.BotExtensionFactory;
import org.telegram.abilitybots.api.bot.BaseAbilityBot;
import org.telegram.abilitybots.api.util.AbilityExtension;
import java.io.File;
public class SimpleExtensionFactory implements BotExtensionFactory {
@Override
public AbilityExtension createExtensionInstance(BaseAbilityBot bot, File shareDataFolder) {
return new SayHelloExtension(bot);
}
}

View File

@ -0,0 +1 @@
net.lamgc.scalabot.simple.SimpleExtensionFactory

View File

@ -0,0 +1,20 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.6.10"
java
}
dependencies {
api("org.telegram:telegrambots-abilities:5.6.0")
api("org.slf4j:slf4j-api:1.7.32")
testImplementation(kotlin("test"))
}
tasks.test {
useJUnitPlatform()
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "11"
}

View File

@ -0,0 +1,31 @@
package net.lamgc.scalabot.extension;
import org.telegram.abilitybots.api.bot.BaseAbilityBot;
import org.telegram.abilitybots.api.util.AbilityExtension;
import java.io.File;
/**
* 该接口用于为指定的 {@link BaseAbilityBot} 创建扩展.
*
* <p> 由于 AbilityExtension 无法直接获取 {@link BaseAbilityBot} 所属的 {@link org.telegram.abilitybots.api.db.DBContext} 对象,
* 所以将通过该接口工厂来创建扩展对象.
*
* @author LamGC
*/
public interface BotExtensionFactory {
/**
* 为给定的 {@link BaseAbilityBot} 对象创建扩展.
*
* <p> 如扩展无使用 {@link org.telegram.abilitybots.api.db.DBContext} 的话,
* 也可以返回扩展单例, 因为 AbilityBot 本身并不禁止多个机器人共用一个扩展对象
* (因为 AbilityBot 只是调用了扩展中的方法来创建了功能对象).
*
* @param bot 机器人对象.
* @param shareDataFolder ScalaBot App 为扩展提供的数据目录, 建议存储在数据目录中, 便于数据的存储管理.
* @return 返回为该 Bot 对象创建的扩展对象.
*/
AbilityExtension createExtensionInstance(BaseAbilityBot bot, File shareDataFolder);
}

View File

@ -0,0 +1,32 @@
package net.lamgc.scalabot.extension;
import org.telegram.abilitybots.api.bot.BaseAbilityBot;
import org.telegram.abilitybots.api.db.DBContext;
import org.telegram.abilitybots.api.sender.MessageSender;
import org.telegram.abilitybots.api.util.AbilityExtension;
/**
*
*/
public abstract class ScalaBotExtension implements AbilityExtension {
/**
* 扩展所属的机器人对象.
*
* <p> 不要给该属性添加 Getter, 会被当成 Ability 添加, 导致出现异常.
*/
protected final BaseAbilityBot bot;
public ScalaBotExtension(BaseAbilityBot bot) {
this.bot = bot;
}
protected MessageSender getSender() {
return bot.sender();
}
protected DBContext getDBContext() {
return bot.db();
}
}

6
settings.gradle.kts Normal file
View File

@ -0,0 +1,6 @@
rootProject.name = "scalabot"
include(":scalabot-app")
include(":scalabot-extension")
include("scalabot-ext-simple")