mirror of
https://github.com/jie65535/mirai-console-jnr-plugin.git
synced 2025-06-09 17:56:34 +08:00
Compare commits
10 Commits
Author | SHA1 | Date | |
---|---|---|---|
f8be57e359 | |||
3b232189d1 | |||
![]() |
a201911817 | ||
21e2cc9166 | |||
f60cb05eb5 | |||
![]() |
ac6633de90 | ||
![]() |
0909b9d0d5 | ||
c2ef779a72 | |||
22e8624f0b | |||
f20fd9b807 |
16
README.md
16
README.md
@ -8,7 +8,7 @@ MiraiConsolePlugin 自定义戳一戳回复消息
|
||||
/jnr add [weight] # 添加回复消息(权重默认为1)
|
||||
/jnr add <message> [weight] # 添加简单回复消息(权重默认为1)
|
||||
/jnr clear # 清空回复消息列表
|
||||
/jnr list # 列出当前回复消息列表
|
||||
/jnr list [page] [pageSize] # 列出当前回复消息列表,参数可翻页
|
||||
/jnr remove <index> # 删除指定索引的回复消息
|
||||
/jnr reload # 重载配置
|
||||
```
|
||||
@ -18,8 +18,20 @@ MiraiConsolePlugin 自定义戳一戳回复消息
|
||||
设置回复消息为以下内容,代表特殊含义
|
||||
|
||||
- `#nudge` 戳回去
|
||||
- `#nudge:戳我干嘛!` 戳回去,并且回复一条消息
|
||||
- `#group.mute:30` 禁言30s, 可以自定义禁言时间, 单位秒
|
||||
- `#ignore` 忽略
|
||||
- `#group.mute:60:生气了!禁言你1分钟` 同上,并且回复一条消息
|
||||
- `#ignore` 忽略本次戳一戳
|
||||
- `#audio:XXX.amr` 回复音频,参数通常为 XXX.amr,服务器要求文件名后缀必须为 ".amr",但其编码方式也有可能是非
|
||||
AudioCodec.AMR。
|
||||
音频文件保存在 `data/me.jie65535.mirai-console-jnr-plugin/` 目录下,理论上你也可以手工设置音频文件。
|
||||
|
||||
## 占位符
|
||||
|
||||
- `{name}` 会被替换为群名片或昵称
|
||||
- `{botName}` 会被替换为机器人群名片或昵称
|
||||
- `{groupName}` 会被替换为群名称
|
||||
- 更多欢迎 ISSUE 或者 PR 补充...
|
||||
|
||||
## 配置文件
|
||||
|
||||
|
@ -1,16 +1,23 @@
|
||||
plugins {
|
||||
val kotlinVersion = "1.6.0"
|
||||
val kotlinVersion = "1.7.10"
|
||||
kotlin("jvm") version kotlinVersion
|
||||
kotlin("plugin.serialization") version kotlinVersion
|
||||
|
||||
id("net.mamoe.mirai-console") version "2.12.2"
|
||||
id("net.mamoe.mirai-console") version "2.16.0"
|
||||
}
|
||||
|
||||
group = "top.jie65535"
|
||||
version = "1.2.0"
|
||||
version = "1.5.0"
|
||||
|
||||
repositories {
|
||||
mavenLocal()
|
||||
maven("https://maven.aliyun.com/repository/public")
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
val ktorVersion = "2.2.3"
|
||||
|
||||
dependencies {
|
||||
implementation("io.ktor:ktor-client-core-jvm:$ktorVersion")
|
||||
implementation("io.ktor:ktor-client-okhttp:$ktorVersion")
|
||||
}
|
17
src/main/kotlin/top/jie65535/jnr/HttpUtil.kt
Normal file
17
src/main/kotlin/top/jie65535/jnr/HttpUtil.kt
Normal file
@ -0,0 +1,17 @@
|
||||
package top.jie65535.jnr
|
||||
|
||||
import io.ktor.client.*
|
||||
import io.ktor.client.call.*
|
||||
import io.ktor.client.engine.okhttp.*
|
||||
import io.ktor.client.request.*
|
||||
import java.io.File
|
||||
|
||||
object HttpUtil {
|
||||
private val httpClient = HttpClient(OkHttp)
|
||||
|
||||
suspend fun download(url: String, file: File): ByteArray {
|
||||
val data = httpClient.get(url).body<ByteArray>()
|
||||
file.writeBytes(data)
|
||||
return data
|
||||
}
|
||||
}
|
@ -11,10 +11,10 @@ import net.mamoe.mirai.event.events.MessageEvent
|
||||
import net.mamoe.mirai.event.globalEventChannel
|
||||
import net.mamoe.mirai.event.nextEvent
|
||||
import net.mamoe.mirai.message.code.MiraiCode.deserializeMiraiCode
|
||||
import net.mamoe.mirai.message.data.PlainText
|
||||
import net.mamoe.mirai.message.data.buildForwardMessage
|
||||
import net.mamoe.mirai.message.data.isContentBlank
|
||||
import net.mamoe.mirai.message.data.*
|
||||
import net.mamoe.mirai.message.data.Image.Key.queryUrl
|
||||
import top.jie65535.jnr.JNudgeReply.reload
|
||||
import kotlin.math.min
|
||||
|
||||
object JNRCommand : CompositeCommand(
|
||||
JNudgeReply, "jnr",
|
||||
@ -47,13 +47,32 @@ object JNRCommand : CompositeCommand(
|
||||
if (isUser()) {
|
||||
try {
|
||||
sendMessage("请在${WAIT_REPLY_TIMEOUT_MS / 1000}秒内发送要添加的消息内容,你可以发送空白消息来取消。")
|
||||
val msg = withTimeout(WAIT_REPLY_TIMEOUT_MS) {
|
||||
val nextEvent = withTimeout(WAIT_REPLY_TIMEOUT_MS) {
|
||||
subject.globalEventChannel().nextEvent<MessageEvent>(EventPriority.MONITOR) { it.sender == user }
|
||||
}
|
||||
if (msg.message.isContentBlank()) {
|
||||
if (nextEvent.message.isContentBlank()) {
|
||||
sendMessage("已取消")
|
||||
} else {
|
||||
JNRPluginConfig.replyMessageList.add(ReplyMessage(msg.message.serializeToMiraiCode(), weight))
|
||||
// 保存资源
|
||||
saveResources(nextEvent.message)
|
||||
|
||||
// 保存音频文件名
|
||||
val audio = nextEvent.message.findIsInstance<OnlineAudio>()
|
||||
if (audio != null) {
|
||||
JNRPluginConfig.replyMessageList.add(
|
||||
ReplyMessage(
|
||||
PlainText("#audio:${audio.filename}").serializeToMiraiCode(),
|
||||
weight
|
||||
)
|
||||
)
|
||||
} else {
|
||||
JNRPluginConfig.replyMessageList.add(
|
||||
ReplyMessage(
|
||||
nextEvent.message.serializeToMiraiCode(),
|
||||
weight
|
||||
)
|
||||
)
|
||||
}
|
||||
sendMessage("已添加一条消息,权重为$weight")
|
||||
}
|
||||
} catch (e: TimeoutCancellationException) {
|
||||
@ -64,6 +83,35 @@ object JNRCommand : CompositeCommand(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存消息中的图片和音频
|
||||
*/
|
||||
private suspend fun saveResources(message: MessageChain) {
|
||||
for (it in message) {
|
||||
if (it is Image) {
|
||||
val imgDir = JNudgeReply.resolveDataFile("images")
|
||||
if (!imgDir.exists()) {
|
||||
imgDir.mkdir()
|
||||
}
|
||||
val imgFile = imgDir.resolve(it.imageId)
|
||||
if (!imgFile.exists()) {
|
||||
JNudgeReply.logger.info("下载图片 ${it.imageId}")
|
||||
HttpUtil.download(it.queryUrl(), imgFile)
|
||||
}
|
||||
} else if (it is OnlineAudio) {
|
||||
val audioDir = JNudgeReply.resolveDataFile("audios")
|
||||
if (!audioDir.exists()) {
|
||||
audioDir.mkdir()
|
||||
}
|
||||
val audioFile = audioDir.resolve(it.filename)
|
||||
if (!audioFile.exists()) {
|
||||
JNudgeReply.logger.info("下载语音 ${it.filename}")
|
||||
HttpUtil.download(it.urlForDownload, audioFile)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SubCommand
|
||||
@Description("删除指定索引的回复消息")
|
||||
suspend fun CommandSender.remove(index: Int) {
|
||||
@ -84,7 +132,7 @@ object JNRCommand : CompositeCommand(
|
||||
|
||||
@SubCommand
|
||||
@Description("列出当前回复消息列表")
|
||||
suspend fun CommandSender.list() {
|
||||
suspend fun CommandSender.list(page: Int = 0, pageSize: Int = 50) {
|
||||
val list = JNRPluginConfig.replyMessageList
|
||||
if (list.isEmpty()) {
|
||||
sendMessage("当前列表为空")
|
||||
@ -97,11 +145,20 @@ object JNRCommand : CompositeCommand(
|
||||
sendMessage(sb.toString())
|
||||
}, {
|
||||
if (list.size > 1) {
|
||||
sendMessage(buildForwardMessage(subject) {
|
||||
for (i in list.indices) {
|
||||
bot named "[$i] (${list[i].weight})" says list[i].message.deserializeMiraiCode()
|
||||
}
|
||||
})
|
||||
val begin = page * pageSize
|
||||
val end = min(list.size, (page + 1) * pageSize)
|
||||
if (begin < 0 || end <= begin) {
|
||||
sendMessage("翻页参数错误")
|
||||
} else {
|
||||
sendMessage(buildForwardMessage(subject) {
|
||||
for (i in begin until end) {
|
||||
bot named "[$i] (${list[i].weight})" says list[i].message.deserializeMiraiCode()
|
||||
}
|
||||
if (end < list.size) {
|
||||
bot says "当前显示 $begin~$end 共 ${list.size}"
|
||||
}
|
||||
})
|
||||
}
|
||||
} else {
|
||||
sendMessage(list[0].message.deserializeMiraiCode())
|
||||
}
|
||||
|
@ -47,4 +47,9 @@ object JNRPluginConfig : AutoSavePluginConfig("jnr") {
|
||||
*/
|
||||
@ValueDescription("用户私聊回复间隔(秒),0表示无限制")
|
||||
var userInterval: Long by value(0L)
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否在间隔期间依然拦截事件,与 [isIntercept] 有关
|
||||
*/
|
||||
var interceptAtInterval: Boolean by value(true)
|
||||
}
|
||||
|
@ -3,6 +3,7 @@ package top.jie65535.jnr
|
||||
import net.mamoe.mirai.console.command.CommandManager.INSTANCE.register
|
||||
import net.mamoe.mirai.console.plugin.jvm.JvmPluginDescription
|
||||
import net.mamoe.mirai.console.plugin.jvm.KotlinPlugin
|
||||
import net.mamoe.mirai.contact.AudioSupported
|
||||
import net.mamoe.mirai.contact.Group
|
||||
import net.mamoe.mirai.contact.Member
|
||||
import net.mamoe.mirai.contact.nameCardOrNick
|
||||
@ -10,15 +11,20 @@ import net.mamoe.mirai.event.EventPriority
|
||||
import net.mamoe.mirai.event.events.NudgeEvent
|
||||
import net.mamoe.mirai.event.globalEventChannel
|
||||
import net.mamoe.mirai.message.code.MiraiCode.deserializeMiraiCode
|
||||
import net.mamoe.mirai.message.data.*
|
||||
import net.mamoe.mirai.utils.ExternalResource.Companion.toExternalResource
|
||||
import net.mamoe.mirai.utils.ExternalResource.Companion.uploadAsImage
|
||||
import net.mamoe.mirai.utils.info
|
||||
import java.time.LocalDateTime
|
||||
import kotlin.random.Random
|
||||
import kotlin.time.DurationUnit
|
||||
import kotlin.time.toDuration
|
||||
|
||||
object JNudgeReply : KotlinPlugin(
|
||||
JvmPluginDescription(
|
||||
id = "me.jie65535.mirai-console-jnr-plugin",
|
||||
name = "J Nudge Reply",
|
||||
version = "1.2.0",
|
||||
version = "1.5.0",
|
||||
) {
|
||||
author("jie65535")
|
||||
info("""自定义戳一戳回复插件""")
|
||||
@ -56,12 +62,12 @@ object JNudgeReply : KotlinPlugin(
|
||||
}
|
||||
}
|
||||
if ((from as Member).permission.level >= (subject as Group).botPermission.level) {
|
||||
replyList = replyList.filter { !it.message.startsWith("#group.mute:") }
|
||||
replyList = replyList.filter { !it.message.startsWith("#group.mute\\:") }
|
||||
}
|
||||
}
|
||||
|
||||
// 判断间隔
|
||||
if (isReply) {
|
||||
val isIgnored = if (isReply) {
|
||||
val totalWeight = replyList.sumOf { it.weight }
|
||||
var w = Random.nextInt(totalWeight)
|
||||
for (msg in replyList) {
|
||||
@ -72,39 +78,60 @@ object JNudgeReply : KotlinPlugin(
|
||||
w -= msg.weight
|
||||
}
|
||||
}
|
||||
false
|
||||
} else {
|
||||
logger.info("正在CD中,本次已忽略")
|
||||
true
|
||||
}
|
||||
|
||||
// 拦截事件
|
||||
if (JNRPluginConfig.priority != EventPriority.MONITOR && JNRPluginConfig.isIntercept) {
|
||||
intercept()
|
||||
if (JNRPluginConfig.priority != EventPriority.MONITOR && JNRPluginConfig.isIntercept
|
||||
) {
|
||||
// 在被忽略的情况下判断是否拦截
|
||||
if (!isIgnored || JNRPluginConfig.interceptAtInterval)
|
||||
intercept()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.info { "Plugin loaded" }
|
||||
logger.info { "Plugin loaded. https://github.com/jie65535/mirai-console-jnr-plugin" }
|
||||
}
|
||||
|
||||
private suspend fun doReply(message: ReplyMessage, event: NudgeEvent) {
|
||||
if (message.message.startsWith("#")) {
|
||||
private suspend fun doReply(reply: ReplyMessage, event: NudgeEvent) {
|
||||
val replyMessageChain = reply.message.deserializeMiraiCode()
|
||||
val replyMessage = replyMessageChain.content
|
||||
if (replyMessage.startsWith("#")) {
|
||||
when {
|
||||
// 戳回去
|
||||
message.message == "#nudge" -> {
|
||||
replyMessage.startsWith("#nudge") -> {
|
||||
event.from.nudge().sendTo(event.subject)
|
||||
logger.info("已尝试戳回发送者")
|
||||
val replyMsg = replyMessage.substring("#nudge".length).removePrefix(":")
|
||||
if (replyMsg.isNotBlank()) {
|
||||
sendRecordMessage(event, messageChainOf(PlainText(replyMsg.trim())))
|
||||
logger.info("已尝试戳回发送者并回复消息")
|
||||
} else {
|
||||
logger.info("已尝试戳回发送者")
|
||||
}
|
||||
}
|
||||
|
||||
// 禁言
|
||||
message.message.startsWith("#group.mute:") -> {
|
||||
val duration = message.message.substringAfter(':').toIntOrNull()
|
||||
if (duration == null) {
|
||||
logger.warning("戳一戳禁言失败:\"${message.message}\" 格式不正确")
|
||||
replyMessage.startsWith("#group.mute:") -> {
|
||||
val args = replyMessage.substring("#group.mute:".length).split(':')
|
||||
val durationS = if (args.isNotEmpty()) args[0].toIntOrNull() else 0
|
||||
if (durationS == null || durationS < 1) {
|
||||
logger.warning("戳一戳禁言失败:\"${replyMessage}\" 格式不正确")
|
||||
} else {
|
||||
val member: Member = event.from as Member
|
||||
try {
|
||||
member.mute(duration)
|
||||
logger.info("戳一戳禁言目标 ${member.nameCardOrNick}(${member.id}) $duration 秒")
|
||||
member.mute(durationS)
|
||||
val duration = durationS.toDuration(DurationUnit.SECONDS)
|
||||
if (args.size > 1 && args[1].isNotBlank()) {
|
||||
val replyMsg = args[1].trim()
|
||||
// .replace("{duration}", duration.toString())
|
||||
// 如果禁言时间是在消息中设置的,那么用户也可以同时设置回复的内容里带时间,因此无需添加格式化,除非支持随机禁言时间,可以再考虑
|
||||
sendRecordMessage(event, messageChainOf(PlainText(replyMsg)))
|
||||
}
|
||||
logger.info("戳一戳禁言目标 ${member.nameCardOrNick}(${member.id}) $duration")
|
||||
} catch (e: Throwable) {
|
||||
logger.warning("戳一戳禁言失败", e)
|
||||
}
|
||||
@ -112,15 +139,69 @@ object JNudgeReply : KotlinPlugin(
|
||||
}
|
||||
|
||||
// 忽略
|
||||
message.message == "#ignore" -> {
|
||||
replyMessage == "#ignore" -> {
|
||||
logger.info("已忽略本次戳一戳回复")
|
||||
}
|
||||
|
||||
// 音频回复
|
||||
replyMessage.startsWith("#audio:") -> {
|
||||
val filename = replyMessage.substring("#audio:".length)
|
||||
val audioFile = resolveDataFile("audios/$filename").toExternalResource()
|
||||
if (event.subject is AudioSupported) {
|
||||
logger.info("上传并回复语音 $filename")
|
||||
val messageTemp = (event.subject as AudioSupported).uploadAudio(audioFile)
|
||||
sendRecordMessage(event, messageTemp.toMessageChain())
|
||||
} else {
|
||||
logger.warning("当前上下文不支持回复语音")
|
||||
sendRecordMessage(event, messageChainOf(PlainText("[语音消息] 当前上下文不支持")))
|
||||
}
|
||||
}
|
||||
|
||||
// 其它
|
||||
else -> event.subject.sendMessage(message.message.deserializeMiraiCode())
|
||||
else -> sendRecordMessage(event, replyMessageChain)
|
||||
}
|
||||
} else {
|
||||
event.subject.sendMessage(message.message.deserializeMiraiCode())
|
||||
sendRecordMessage(event, replyMessageChain)
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun sendRecordMessage(event: NudgeEvent, message: MessageChain) {
|
||||
val modifiedChain = MessageChainBuilder()
|
||||
for (it in message) {
|
||||
var innerMessage = it
|
||||
if (it is Image) {
|
||||
val imgFile = resolveDataFile("images/" + it.imageId)
|
||||
if (imgFile.exists()) {
|
||||
innerMessage = imgFile.uploadAsImage(event.subject)
|
||||
} else {
|
||||
logger.warning(
|
||||
"图片的本地缓存已丢失,请重新设置该消息内的图片!" +
|
||||
"消息内容:" + message.serializeToMiraiCode()
|
||||
)
|
||||
}
|
||||
} else if (it is PlainText) {
|
||||
/**
|
||||
* 占位符
|
||||
* - `{name}` 会被替换为群名片或昵称
|
||||
* - `{botName}` 会被替换为机器人群名片或昵称
|
||||
* - `{groupName}` 会被替换为群名称
|
||||
*/
|
||||
val content = it.content
|
||||
.replace("{name}", event.from.nameCardOrNick)
|
||||
.replace("{botName}", event.target.nameCardOrNick)
|
||||
.replace(
|
||||
"{groupName}",
|
||||
if (event.subject is Group) {
|
||||
(event.subject as Group).name
|
||||
} else {
|
||||
event.from.nick
|
||||
}
|
||||
)
|
||||
|
||||
innerMessage = PlainText(content)
|
||||
}
|
||||
modifiedChain.append(innerMessage)
|
||||
}
|
||||
event.subject.sendMessage(modifiedChain.build())
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user