Github:https://github.com/rubenlagus/TelegramBots
Telegram-Bot官网:https://core.telegram.org/bots
1、依赖
val telegramBotsVersion = "5.7.1"
implementation("org.telegram:telegrambots:$telegramBotsVersion")
implementation("org.telegram:telegrambots-abilities:$telegramBotsVersion")
2、配置文件YuQ.properties
me.kuku.botToken=
me.kuku.botUsername=
me.kuku.creatorId=
3、注册Module
yu.modules=me.kuku.yuq.TelegramModule
# 如已注册modules
yu.[modules=me.kuku.yuq.TelegramModule
4、编写Module
,新建一个TgBot
实例,并放到YuQ
的容器中
只在配置了TgBot
信息才加载
class TelegramModule @Inject constructor(
private val context: YuContext,
@Config("me.kuku.botToken") private val botToken: String,
@Config("me.kuku.botUsername") private val botUsername: String,
@Config("me.kuku.creatorId") private val creatorId: String
): Module {
override fun onLoad() {
if (botToken.isNotEmpty() && botUsername.isNotEmpty() && creatorId.isNotEmpty()) {
val tgBot = TgBot(botToken, botUsername, creatorId.toLong())
context.putBean(tgBot, "tgBot")
}
}
}
class TgBot(botToken: String, botUsername: String, private val creatorId: Long): AbilityBot(botToken, botUsername) {
override fun creatorId(): Long = creatorId
public override fun addExtension(extension: AbilityExtension) {
super.addExtension(extension)
}
}
5、在AppStartEvent
事件中,注册TgBot
,并且注册实现AbilityExtension
接口的能力扩展
@EventListener
class SystemEvent @Inject constructor(
private val context: YuContext
) {
@Inject
private var tgBot: TgBot? = null
@Event
fun telegramInit(e: AppStartEvent) {
if (tgBot != null) {
val field = context::class.java.getDeclaredField("classContextMap")
field.isAccessible = true
val map = field.get(context) as HashMap<String, ClassContext>
map.forEach{(_,v) ->
v.clazz.interfaces.takeIf { it.contains(AbilityExtension::class.java) }?.let {
context.getBean(v.clazz)
val ob = v.defaultInstance as? AbilityExtension
ob?.apply {
tgBot?.addExtension(this)
}
}
}
val botsApi = TelegramBotsApi(DefaultBotSession::class.java)
botsApi.registerBot(tgBot)
}
}
}
6、编写Bot
文档:https://github.com/rubenlagus/TelegramBots/wiki/Ability-Extensions
一个简单的生成一个随机key
并保存到数据库中,指令为/new
class PushExtension @Inject constructor(
private val tgPushService: TgPushService
): AbilityExtension {
private fun key(): String {
return UUID.randomUUID().toString().replace("-", "")
}
fun newKey(): Ability = Ability
.builder()
.name("new")
.info("create a key")
.input(0)
.locality(Locality.ALL)
.privacy(Privacy.PUBLIC)
.action {
val id = it.user().id
val userEntity = tgPushService.findByUserid(id)
val silent = it.bot().silent()
if (!Objects.isNull(userEntity)) {
silent.sendMd("You have already generated the key, if you need to regenerate it, you can use the /regen command",
it.chatId())
} else {
val key = key()
tgPushService.save(TgPushEntity().also { entity ->
entity.key = key
entity.userid = id
})
silent.sendMd("""
Success!
You key is `${key}`
""".trimIndent(), it.chatId())
}
}
.build()
}