master
pan 4 years ago
commit 6091c574f4
  1. 72
      .gitignore
  2. 4
      Dockerfile
  3. 41
      README.md
  4. 83
      build.gradle.kts
  5. 5
      buildimage
  6. 5
      gradle/wrapper/gradle-wrapper.properties
  7. 172
      gradlew
  8. 84
      gradlew.bat
  9. 1
      qqbot.json
  10. 3
      run
  11. 10
      settings.gradle.kts
  12. 9
      src/main/kotlin/com/pqh/qqbot/JSONResponse.kt
  13. 11
      src/main/kotlin/com/pqh/qqbot/ListAccount.kt
  14. 11
      src/main/kotlin/com/pqh/qqbot/QqbotApplication.kt
  15. 30
      src/main/kotlin/com/pqh/qqbot/TestController.kt
  16. 271
      src/main/kotlin/com/pqh/qqbot/TestQQBot.kt
  17. 13
      src/main/kotlin/com/pqh/qqbot/entity.kt
  18. 10
      src/main/kotlin/com/pqh/qqbot/repository.kt
  19. 16
      src/main/resources/application.yaml
  20. 53
      src/main/resources/logback-spring.xml
  21. 23
      src/test/kotlin/com/pqh/qqbot/AppTest.kt
  22. 94
      src/test/kotlin/com/pqh/qqbot/QqbotApplicationTests.kt

72
.gitignore vendored

@ -0,0 +1,72 @@
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/main/**
!**/src/test/**
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
out/
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
### VS Code ###
.vscode/
### Gradle template
/build/
# Ignore Gradle GUI config
gradle-app.setting
# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored)
!gradle-wrapper.jar
# Cache of project
.gradletasknamecache
# # Work around https://youtrack.jetbrains.com/issue/IDEA-116898
# gradle/wrapper/gradle-wrapper.properties
### Kotlin template
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
/image/

@ -0,0 +1,4 @@
FROM openjdk:8
COPY qqbot-0.0.1-SNAPSHOT.jar /usr/src/myapp
WORKDIR /usr/src/myapp
CMD ["java", "-jar","qqbot-0.0.1-SNAPSHOT.jar"]

@ -0,0 +1,41 @@
QQ BOT
---
此项目基于开源机器人框架Mirai进行开发,以下内容截取自项目的[README.md](https://github.com/mamoe/mirai/blob/master/README.md)
---
## Mirai
**QQ Android** 协议支持库与高效率的机器人框架
纯 Kotlin 实现协议和支持库
mirai 既可以作为项目中的 QQ 协议支持库, 也可以作为单独的应用程序与插件承载 QQ 机器人服务。
**一切开发旨在学习,请勿用于非法用途**
### QQ BOT 功能概述
1. 收集QQ群好友消息,存储到数据库,并进行分析统计,统计结果从web后台进行查看。统计包括以下内容:
* 利用 **[tf-idf](https://zh.wikipedia.org/wiki/Tf-idf)** 算法对消息做词频统计,算出某时间段热门关键词、话题
2. 监听QQ群好友消息,触发由web后台管理定义的**指令集**,按照指令类型进行相应处理。如果是**查询指令**,QQ BOT收到请求后会调用指令集对应的**模块**进行处理,并响应处理结果给群用户。如果是 **订阅指令** ,QQ BOT收到请求后会向**[RSSHub](https://docs.rsshub.app/ "RSSHub")**订阅 **主题**,RSSHub的主题**更新**后**推送**给群用户
* ### 相关概念
指令集:可以和QQ BOT进行交互的所有有效指令构成的指令集合的简称。
查询指令:群用户主动向机器人发送查询消息的请求指令。
订阅指令:群用户向机器人订阅消息的请求指令。
一条合法的指令由 `>>>`+`一级指令`+`二级指令`+`占位符`+`参数`组成,比如查询pid(P站图片id)的指令是`>>>query pixiv -p 80353815`
模块:指令集调用的处理器,应用依赖的核心逻辑单元,称之为模块。模块本身不依赖于QQ BOT运行环境,是可独立运行的应用
目前计划支持`kotlin`和`java`开发的模块。模块内部**封装**了群用户查询消息的**处理逻辑**,这里的处理逻辑实际上是通过`HTTP/HTTPS`协议向服务端爬取消息,进行解析并返回的过程,所以模块暂统称为`爬虫模块`,每个爬虫模块必须提供**输入**和**输出**,输入指解析QQ BOT发送的指令,而响应给QQ BOT的处理结果就是输出。
RSSHub:一个开源、简单易用、易于扩展的 RSS 生成器,可以给任何奇奇怪怪的内容生成 RSS 订阅源。RSSHub 借助于开源社区的力量快速发展中,目前已适配数百家网站的上千项内容
* ### 查询指令速查表:
| 功能 | 一级指令 | 二级指令 | 占位符参数 | 指令示例 |
| :----: | :----: | :----: | :----: | :----: |
| P站id查图 | `query` | `pixiv` | `-p pid` | `>>>query pixiv -p 80353815` |
| 随机获取P站图片 | `query` | `pixiv` | `-r` | `>>>query pixiv -r` |
| 根据tag随机获取P站图片 | `query` | `pixiv` | `-r -t tag` | `>>>query pixiv -r -t R18` |
* ### 订阅指令速查表
| 功能 | 一级指令 | 二级指令 | 占位符参数 | 指令示例 |
| :----: | :----: | :----: | :----: | :----: |
| 维基百科当年今日 | `subscribe` | `wiki` | `-t` | `>>>subscribe wiki -t` |

@ -0,0 +1,83 @@
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import org.springframework.boot.gradle.tasks.bundling.BootJar
import java.net.URI
plugins {
id("org.springframework.boot") version "2.3.1.RELEASE"
id("io.spring.dependency-management") version "1.0.9.RELEASE"
kotlin("jvm") version "1.4.0"
kotlin("plugin.spring") version "1.4.0"
kotlin("plugin.jpa") version "1.4.0"
id("distribution")
}
group = "com.pqh"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_1_8
val taskGraph=gradle.getTaskGraph()
val junitVersion = "5.0.0"
var enabledProcessResources:Boolean? = null
val miraiVersion="1.2.2"
repositories {
maven { url=URI("https://maven.aliyun.com/repository/public/") }
maven { url=URI("https://repo.spring.io/libs-milestone/") }
mavenCentral()
}
dependencies {
implementation("net.mamoe:mirai-core-qqandroid:${miraiVersion}")
implementation("com.alibaba:fastjson:1.2.71")
// implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-data-mongodb")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
testImplementation("org.springframework.boot:spring-boot-starter-test") {
exclude(module = "junit")
exclude(module = "mockito-core")
exclude(module = "junit-vintage-engine")
}
}
tasks.register<Copy>("qqbot") {
dependsOn(tasks.withType<BootJar>())
from("src/main/resources")
into("${buildDir}/libs/config")
doLast{
println("完成任务,buildDir=${buildDir}")
}
}
taskGraph.beforeTask {
if(this.name=="processResources") {
if (taskGraph.hasTask(":bootJar")) {
println("不打包资源文件")
enabled = false
} else {
println("打包资源文件")
enabled = true
}
}
}
tasks.withType<Test> {
useJUnitPlatform()
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "1.8"
}
}

@ -0,0 +1,5 @@
#!/bin/sh
sudo mkdir /sys/fs/cgroup/systemd
sudo mount -t cgroup -o none,name=systemd cgroup /sys/fs/cgroup/systemd
export DOCKER_HOST=tcp://127.0.0.1:2375
pack build kotlinapp --builder cnbs/sample-builder:bionic

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

172
gradlew vendored

@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$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=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# 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
;;
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" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
gradlew.bat vendored

@ -0,0 +1,84 @@
@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 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=
@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 init
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 init
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
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
: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 %CMD_LINE_ARGS%
: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

@ -0,0 +1 @@
{"display":[77,73,82,65,73,46,52,52,49,55,52,51,46,48,48,49],"product":[109,105,114,97,105],"device":[109,105,114,97,105],"board":[109,105,114,97,105],"brand":[109,97,109,111,101],"model":[109,105,114,97,105],"bootloader":[117,110,107,110,111,119,110],"fingerprint":[109,97,109,111,101,47,109,105,114,97,105,47,109,105,114,97,105,58,49,48,47,77,73,82,65,73,46,50,48,48,49,50,50,46,48,48,49,47,54,54,49,52,51,54,48,58,117,115,101,114,47,114,101,108,101,97,115,101,45,107,101,121,115],"bootId":[49,70,56,56,52,52,67,50,45,50,67,55,57,45,65,53,50,68,45,52,69,67,51,45,57,68,48,54,68,65,66,50,50,65,68,50],"procVersion":[76,105,110,117,120,32,118,101,114,115,105,111,110,32,51,46,48,46,51,49,45,71,54,51,68,67,49,103,98,32,40,97,110,100,114,111,105,100,45,98,117,105,108,100,64,120,120,120,46,120,120,120,46,120,120,120,46,120,120,120,46,99,111,109,41],"baseBand":[],"version":{},"simInfo":[84,45,77,111,98,105,108,101],"osType":[97,110,100,114,111,105,100],"macAddress":[48,50,58,48,48,58,48,48,58,48,48,58,48,48,58,48,48],"wifiBSSID":[48,50,58,48,48,58,48,48,58,48,48,58,48,48,58,48,48],"wifiSSID":[60,117,110,107,110,111,119,110,32,115,115,105,100,62],"imsiMd5":[70,-114,-12,-111,92,28,-111,-101,-37,101,-8,83,-28,-110,33,104],"imei":"101828038951354","apn":[119,105,102,105]}

3
run

@ -0,0 +1,3 @@
#!/bin/sh
nohup java -jar qqbot-0.0.1-SNAPSHOT.jar &

@ -0,0 +1,10 @@
rootProject.name = "qqbot"
pluginManagement {
repositories {
maven {
url= java.net.URI("https://maven.aliyun.com/repository/gradle-plugin")
}
gradlePluginPortal()
}
}

@ -0,0 +1,9 @@
package com.pqh.qqbot
enum class Result{
OK,
FAIL
}
data class JSONResponse<T>(val result: Result,val body: T)

@ -0,0 +1,11 @@
package com.pqh.qqbot
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.stereotype.Component
@Component
@ConfigurationProperties(prefix = "qq")
class ListAccount {
val data=ArrayList<TestQQBot.Account>()
}

@ -0,0 +1,11 @@
package com.pqh.qqbot
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class QqbotApplication
fun main(args: Array<String>) {
runApplication<QqbotApplication>(*args)
}

@ -0,0 +1,30 @@
package com.pqh.qqbot
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RestController
@RestController
class TestController {
private val data=ArrayList<TestQQBot.Account>()
private val logger: Logger = LoggerFactory.getLogger(TestController::class.java)
@Autowired
private lateinit var bot:TestQQBot
@PostMapping("runBot")
fun runBot(account:TestQQBot.Account):JSONResponse<TestQQBot.Account>{
if(data.contains(account)){
logger.info("机器人已存在${account.qqId}")
}else {
bot.initBot(account)
}
return JSONResponse(Result.OK,account)
}
}

@ -0,0 +1,271 @@
package com.pqh.qqbot
import io.ktor.util.KtorExperimentalAPI
import io.ktor.util.hex
import kotlinx.coroutines.*
import net.mamoe.mirai.Bot
import net.mamoe.mirai.alsoLogin
import net.mamoe.mirai.closeAndJoin
import net.mamoe.mirai.event.subscribeMessages
import net.mamoe.mirai.message.GroupMessageEvent
import net.mamoe.mirai.message.MessageEvent
import net.mamoe.mirai.message.data.*
import net.mamoe.mirai.message.sourceId
import net.mamoe.mirai.message.sourceTime
import net.mamoe.mirai.utils.*
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.beans.factory.annotation.Value
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Component
import org.springframework.stereotype.Service
import org.springframework.util.ResourceUtils
import java.io.File
import java.net.URL
import java.time.Duration
import java.util.*
import java.util.concurrent.TimeUnit
import javax.annotation.PostConstruct
const val mongoDBName: String = "MongoDB"
class CustomLogger(val logger: Logger,override val identity: String?) :MiraiLoggerPlatformBase(){
override fun debug0(message: String?, e: Throwable?) {
logger.debug(message,e)
}
override fun error0(message: String?, e: Throwable?) {
logger.error(message,e)
}
override fun info0(message: String?, e: Throwable?) {
logger.info(message,e)
}
override fun verbose0(message: String?, e: Throwable?) {
logger.trace(message,e)
}
override fun warning0(message: String?, e: Throwable?) {
logger.warn(message,e)
}
}
@Service
class TestQQBot {
val logger=LoggerFactory.getLogger(TestQQBot::class.java)
/**
* 程序入口
*/
@Autowired
@Qualifier(mongoDBName)
lateinit var db: DB
val maxCount = 3
data class Account(val qqId: Long, val adminQQId: Long, val pwd: String, val forward: Long)
//管理员操作指令
enum class AdminCommand {
//关闭机器人
CLOSE
}
//转发信息卡片标题
class ForwardTitle(val title: String) : ForwardMessage.DisplayStrategy() {
override fun generateTitle(forward: ForwardMessage): String = title
}
/**
* 初始化QQ机器人
*/
@Async
fun initBot(account: Account) {
GlobalScope.launch {
val config = BotConfiguration.Default
config.fileBasedDeviceInfo("qqbot.json")
val bot = Bot(account.qqId, account.pwd, config)
bot.logger.follower=CustomLogger(logger,"Bot ${bot.id}")
bot.logger.info("日志log")
bot.alsoLogin()
val group = bot.getGroup(account.forward)
bot.subscribeMessages {
sentBy(account.adminQQId) {
case(AdminCommand.CLOSE.name) {
bot.logger.info("执行关闭机器人指令")
bot.closeAndJoin()
}
}
always {
if(message.isContentNotEmpty()) {
db.saveToDB(this, account)
if (this is GroupMessageEvent&&sender.group!=group) {
GlobalScope.launch {
var title = sender.group.name
message.forEach {
if (it.isPlain()) {
if (it.content.length > 5) {
title = it.content.substring(0, 5)
}
return@forEach
}
}
var count = 0
while (count++ < maxCount) {
try {
val msg=buildForwardMessage(displayStrategy = ForwardTitle(title)) {
sender.id named senderName at time says message
}
msg.sendTo(group)
break
} catch (e: IllegalStateException) {
bot.logger.error("机器人转发信息发生异常:${e}\n再尝试发送一次")
delay(Duration.ofSeconds(3).toMillis())
}
}
}
}else if(this is GroupMessageEvent&&sender.group==group){
bot.logger.info("不能套娃")
}else{
bot.logger.info("${this.javaClass}类型不转发")
}
}else{
bot.logger.info("信息为空不转发")
}
}
}
}
}
/**
* 保存QQ消息图片
*/
@Component
class SaveImg {
val logger=LoggerFactory.getLogger(SaveImg::class.java)
@Value("\${qq-image}")
lateinit var staticLocations: String
// 截取url作为文件名
val regexFileName = Regex("\\d+-\\d+-[0-9A-Z]+")
//保存图片
@KtorExperimentalAPI
fun saveImage(logger: MiraiLogger, url: String): String? {
val u = URL(url)
val content = u.readBytes()
val dir = File(staticLocations)
val fileName: String?
if (dir.exists() || dir.mkdirs()) {
val f = regexFileName.find(url)?.value
fileName = f ?: UUID.randomUUID().toString()
val filepath = File(dir, fileName).absolutePath.plus(checkFileType(content))
File(filepath).writeBytes(content)
logger.debug("图片保存到本地目录${filepath}")
} else {
fileName = null
logger.debug("图片保存失败")
}
return fileName
}
//获取图片类型
@KtorExperimentalAPI
fun checkFileType(bytes: ByteArray): String {
return when {
"FFD8FF" == hex(bytes.copyOfRange(0, 3)).toUpperCase() -> ".jpg"
"89504E47" == hex(bytes.copyOfRange(0, 4)).toUpperCase() -> ".png"
"47494638" == hex(bytes.copyOfRange(0, 4)).toUpperCase() -> ".gif"
else -> {
logger.info("无法识别文件头:${hex(bytes.copyOfRange(0, 10))}")
""
}
}
}
}
/**
* 存储QQ消息到数据库
*/
interface DB {
suspend fun saveToDB(event: MessageEvent, account: Account)
}
/**
* mongoDB保存QQ消息
*/
@Component(mongoDBName)
class MongoDB : DB {
@Autowired
lateinit var messageRepository: MessageRepository
@Autowired
lateinit var subRepository: MessageSubRepository
@Autowired
lateinit var saveImg: SaveImg
@KtorExperimentalAPI
override suspend fun saveToDB(event: MessageEvent, account: Account) {
val m = messageRepository.save(MySqlMessage(senderId = event.sender.id, time = event.time, botId = event.bot.id))
val logger = event.bot.logger
if (m.id != null) {
event.message.forEach {
val subMessage = when (it) {
is Image -> {
logger.debug("接收图片,查询下载链接")
val imageUrl = it.queryUrl()
logger.debug("图片下载链接:${imageUrl}")
val path = saveImg.saveImage(event.bot.logger, imageUrl)
if (path != null) {
MySqlSubMessage(m.id, path, Image.Key.typeName)
} else {
null
}
}
is PlainText -> {
MySqlSubMessage(m.id, it.content, PlainText.Key.typeName)
}
else -> {
logger.debug("消息类型:${it.javaClass}不处理")
null
}
}
if (subMessage != null) {
subRepository.save(subMessage)
}
}
}
}
}
}

@ -0,0 +1,13 @@
package com.pqh.qqbot
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import java.util.*
@Document("message")
data class MySqlMessage(@Id val id:String?=null,val senderId:Long, val time:Int,val botId:Long)
@Document("sub")
data class MySqlSubMessage(val subId:String,val message:String, val type:String)

@ -0,0 +1,10 @@
package com.pqh.qqbot
import org.springframework.data.mongodb.repository.MongoRepository
import org.springframework.stereotype.Repository
@Repository
interface MessageRepository : MongoRepository<MySqlMessage, String>
@Repository
interface MessageSubRepository : MongoRepository<MySqlSubMessage, Long>

@ -0,0 +1,16 @@
#日志配置
logging:
level:
root: info
spring:
#数据库配置
data:
mongodb:
uri: mongodb://192.168.3.116:27017/fuck
#静态资源目录
mvc:
static-path-pattern: /image/**
qq-image: image

@ -0,0 +1,53 @@
<configuration debug="true">
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<property name="APP_NAME" value="Logback"/>
<property name="LOG_HOME_PATH" value="logs"/>
<property name="DEBUG_LOG_FILE" value="${LOG_HOME_PATH}/debug/${APP_NAME}_debug" />
<property name="log.charset" value="UTF-8" />
<!-- 彩色日志 -->
<!-- 彩色日志依赖的渲染类 -->
<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
<conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
<conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
<!-- 彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } - [%t] %class:%L - %m%n" />
<property name="FILE_LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } - [%t] %class:%L - %m%n" />
<appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder charset="${log.charset}">
<pattern>${FILE_LOG_PATTERN}</pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${DEBUG_LOG_FILE}.%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>60</MaxHistory>
</rollingPolicy>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
</appender>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<!-- <withJansi>true</withJansi>-->
<encoder charset="${log.charset}">
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
</appender>
<root level="DEBUG">
<appender-ref ref="DEBUG_FILE" />
<appender-ref ref="CONSOLE" />
</root>
</configuration>

@ -0,0 +1,23 @@
package com.pqh.qqbot
import org.junit.jupiter.api.Test
class AppTest {
@Test
fun testRegex(){
val s="http://gchat.qpic.cn/gchatpic_new/1029559041/981632964-2949860370-58391EFD3CADE5292A9C9EF98AAFA0A4/0?term=2"
val result= Regex("\\d+-\\d+-[0-9A-Z]+").find(s)
println(result?.value)
}
@Test
fun testFor(){
for((index,value) in listOf("a","b").withIndex()){
println("${index}=${value}")
}
}
}

@ -0,0 +1,94 @@
package com.pqh.qqbot
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Test
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.client.TestRestTemplate
import org.springframework.boot.test.web.client.getForEntity
import org.springframework.http.HttpMethod
import org.springframework.http.MediaType
import org.springframework.http.RequestEntity.get
import org.springframework.http.RequestEntity.post
import org.springframework.http.ResponseEntity.status
import org.springframework.test.context.junit4.SpringRunner
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultHandlers
import org.springframework.util.ResourceUtils
import java.io.File
import java.net.URI
import java.nio.charset.StandardCharsets
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class QqbotApplicationTests(@Autowired val restTemplate: TestRestTemplate) {
private val logger: Logger = LoggerFactory.getLogger(QqbotApplicationTests::class.java)
@Test
fun `Assert blog page title, content and status code`() {
logger.info(">> Assert blog page title, content and status code")
val entity = restTemplate.getForEntity<String>("/fuck")
logger.info(entity.body)
}
@Autowired
lateinit var message: MessageRepository
@Autowired
lateinit var sub: MessageSubRepository
@Autowired
lateinit var testBot:TestQQBot
@Value("#{environment['qq_config']}")
lateinit var sss: String
@Test
fun `mongo test`() {
val m = MySqlMessage(senderId = 1213, time = System.currentTimeMillis().toInt(), botId = 123)
val entity = message.save(m)
logger.info(entity.id)
}
@Test
fun `@value`() = runBlocking {
val file = ResourceUtils.getFile("${ResourceUtils.CLASSPATH_URL_PREFIX}qq.json")
logger.info(file.readText(StandardCharsets.UTF_8))
file.deleteOnExit()
}
@Value("\${qq-image}")
lateinit var staticLocations: String
@Test
fun testPath(){
val filepath = File(staticLocations, "test")
println(filepath.absolutePath)
}
@Test
fun testLog(){
logger.info("日志log")
}
}
@WebMvcTest
class TestMVC(@Autowired val mockMvc: MockMvc) {
@Test
fun testRunBot() {
//val qqId:Long,val adminQQId: Long,val pwd:String,val forward:Long
mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.POST, "/runBot")
.param("qqId","222")
.param("adminQQId","333")
.param("forward","4444")
.param("pwd", "666")).andDo(MockMvcResultHandlers.print())
}
}
Loading…
Cancel
Save