This commit is contained in:
Yutousama 2021-12-06 11:19:00 +08:00
commit 06cb246af7
25 changed files with 2846 additions and 0 deletions

33
.gitignore vendored Normal file
View File

@ -0,0 +1,33 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/

BIN
libs/Msc.jar Normal file

Binary file not shown.

BIN
libs/json-jena-1.0.jar Normal file

Binary file not shown.

310
mvnw vendored Normal file
View File

@ -0,0 +1,310 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
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
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
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
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

182
mvnw.cmd vendored Normal file
View File

@ -0,0 +1,182 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. 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,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

170
pom.xml Normal file
View File

@ -0,0 +1,170 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yutou</groupId>
<artifactId>QQBot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>QQBot</name>
<description>QQBot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.mamoe</groupId>
<artifactId>mirai-core-jvm</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-jdk8</artifactId>
<version>1.5.2</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-core-jvm</artifactId>
<version>1.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.6.0-RC1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.4.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
<dependency>
<groupId>com.iflytek</groupId>
<artifactId>msc</artifactId>
<version>4.1</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/Msc.jar</systemPath>
</dependency>
<dependency>
<groupId>com.iflytek</groupId>
<artifactId>json</artifactId>
<version>4.1</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/json-jena-1.0.jar</systemPath>
</dependency>
</dependencies>
<build>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>复制正式文件</echo>
<copy file="src/main/resources/application.properties.release" tofile="${project.build.outputDirectory}/application.properties" overwrite="true"/>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!--使用-Dloader.path需要在打包的时候增加<layout>ZIP</layou
t>,不指定的话-Dloader.path不生效-->
<layout>ZIP</layout>
<!-- 指定该jar包启动时的主类[建议] -->
<mainClass>com.yutou.qqbot.QQBotApplication</mainClass>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>repackage</goal>
</goals>
<configuration>
<outputDirectory>
X:\servier\tools\
</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<groupId>org.apache.maven.plugins</groupId>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,16 @@
package com.yutou.qqbot;
import com.yutou.qqbot.utlis.RedisTools;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class QQBotApplication {
public static final String version="QQBot v.1.0";
public static void main(String[] args) {
SpringApplication.run(QQBotApplication.class, args);
RedisTools.initRedisPoolSub();
QQBotManager.getInstance();
}
}

View File

@ -0,0 +1,373 @@
package com.yutou.qqbot;
import com.yutou.qqbot.interfaces.DownloadInterface;
import com.yutou.qqbot.models.audio.QQAudio;
import com.yutou.qqbot.models.setu.QQSetu;
import com.yutou.qqbot.utlis.*;
import net.mamoe.mirai.Bot;
import net.mamoe.mirai.BotFactory;
import net.mamoe.mirai.event.GlobalEventChannel;
import net.mamoe.mirai.event.events.GroupMessageEvent;
import net.mamoe.mirai.message.data.Image;
import net.mamoe.mirai.message.data.MessageChainBuilder;
import net.mamoe.mirai.utils.BotConfiguration;
import net.mamoe.mirai.utils.ExternalResource;
import java.io.File;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class QQBotManager {
public static class QQCommands {
private final static String QQ_HELP = "!help";
private final static String QQ_SYSTEM_RESTART = "!restart";
private final static String QQ_UPDATE_IP = "!更新ip";
private final static String QQ_GET_IP = "!ip";
private final static String QQ_OPEN_PC = "!开机";
private final static String QQ_GET_VERSION = "!version";
private final static String QQ_CMD = "!cmd";
private final static String QQ_BANGUMI_TODAY = "!今日动画";
private final static String QQ_BANGUMI_LIST = "!新番";
private final static String QQ_BANGUMI_SUB = "!查动画";
private final static String QQ_AUDIO = "!语音";
private final static String QQ_AUDIO_OPEN_LAMP = "!开灯";
private final static String QQ_AUDIO_OPEN_AIR = "!开空调";
private final static String QQ_BT_RELOAD = "!刷bt";
private final static String QQ_TOOLS_IDEA = "!idea";
private final static String QQ_TOOLS_IDEA_FILE = "!idea>";
private final static String QQ_TOOLS_IDEA_URL = "!idea_url";
public final static String QQ_BANGUMI_INFO="!保存动画信息>";
}
private static QQBotManager botManager = null;
private Bot bot;
private static final long qqGroup = 891655174L;
private boolean isLogin = false;
private static boolean isInit = false;
private QQBotManager() {
Object isRun = ConfigTools.load(ConfigTools.CONFIG, "qq_bot");
if (isRun != null && (boolean) isRun) {
isLogin = true;
isInit = true;
init();
}
}
private void init() {
new Thread(new Runnable() {
@Override
public void run() {
long qq = ConfigTools.load(ConfigTools.CONFIG,"qq_number",Long.class);
String password = ConfigTools.load(ConfigTools.CONFIG,"qq_password",String.class);
bot = BotFactory.INSTANCE.newBot(qq, password, new BotConfiguration() {
{
setProtocol(MiraiProtocol.ANDROID_PAD);
fileBasedDeviceInfo("qq_bot_devices_info.json");
if ("nas".equals(ConfigTools.load(ConfigTools.CONFIG, "model"))) {
noBotLog();
noNetworkLog();
}
}
});
//Events.registerEvents(bot, new MessageListener());
GlobalEventChannel.INSTANCE.subscribeAlways(GroupMessageEvent.class, new MessageListener());
bot.login();
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String str = sendMessage("姬妻酱上线拉~☆Daze~ 当前版本:"+QQBotApplication.version);
Log.i(str);
}
}).start();
bot.join();
}
}).start();
}
public static QQBotManager getInstance() {
if (botManager == null && !isInit) {
botManager = new QQBotManager();
}
return botManager;
}
public boolean isLogin() {
return isLogin;
}
private Image getImage(File file) {
if (bot != null) {
return Objects.requireNonNull(bot.getGroup(qqGroup)).uploadImage(ExternalResource.create(file));
}
return null;
}
private String getNotLoginQQ() {
return "没有登录QQ";
}
public void reportToDayBangumi() {
getInstance().sendMessage(BangumiTools.reportToDayBangumi());
}
public String sendMessage(String text) {
if (bot != null&&!StringUtils.isEmpty(text)) {
try {
return Objects.requireNonNull(bot.getGroup(qqGroup)).sendMessage(text).toString();
} catch (Exception e) {
e.printStackTrace();
}
}
return getNotLoginQQ();
}
public String sendMessage(Long group, String text) {
if (bot != null) {
try {
return Objects.requireNonNull(bot.getGroup(group)).sendMessage(text).toString();
} catch (Exception e) {
e.printStackTrace();
}
}
return getNotLoginQQ();
}
public void sendMessage(Long group, MessageChainBuilder builder) {
if (bot != null) {
Objects.requireNonNull(bot.getGroup(group)).sendMessage(builder.asMessageChain());
}
}
public String sendMessage(File imageFile, String text) {
try {
if (bot != null) {
Image image = getImage(imageFile);
MessageChainBuilder builder = new MessageChainBuilder();
if (image != null) {
builder.append(image);
}
builder.append(text);
return Objects.requireNonNull(bot.getGroup(qqGroup)).sendMessage(builder.asMessageChain()).toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return getNotLoginQQ();
}
public String sendMessage(List<File> imgs, String text) {
if (bot != null) {
MessageChainBuilder builder = new MessageChainBuilder();
for (File img : imgs) {
builder.append(Objects.requireNonNull(getImage(img)));
}
builder.append(text);
return Objects.requireNonNull(bot.getGroup(qqGroup)).sendMessage(builder.asMessageChain()).toString();
}
return getNotLoginQQ();
}
public static List<String> getImages(String str) {
List<String> list = new ArrayList<>();
String regex = "<img(.*?)/img>";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
list.add(matcher.group().replace("<img", "")
.replace("/img>", "")
.trim());
}
return list;
}
public static void main(String[] args) {
getInstance();
}
private static class MessageListener implements Consumer<GroupMessageEvent> {
@Override
public void accept(GroupMessageEvent event) {
String msg = event.getMessage().contentToString();
switch (event.getGroup().getId() + "") {
case qqGroup + "":
myGroup(msg);
case "570197155":
new QQSetu().setu(msg, event);
}
}
private void myGroup(String msg) {
StringBuilder builder;
String msgSrc=msg;
msg = msg.replace("", "!").toLowerCase();
Log.i("QQBot","command = "+msg);
switch (msg) {
case QQCommands.QQ_OPEN_PC:
RedisTools.Consumer.system("openPC", null);
String time = new SimpleDateFormat("HH").format(new Date());
if (Integer.parseInt(time) < 18) {
break;
}
case QQCommands.QQ_AUDIO_OPEN_LAMP:
QQAudio.playText("小爱同学,开灯");
break;
case QQCommands.QQ_AUDIO_OPEN_AIR:
QQAudio.playText("小爱同学,开空调");
break;
case QQCommands.QQ_UPDATE_IP:
RedisTools.Consumer.system("updateIP", null);
break;
case QQCommands.QQ_GET_IP:
RedisTools.Consumer.bot("getip");
break;
case QQCommands.QQ_GET_VERSION:
sendVersion();
break;
case QQCommands.QQ_BANGUMI_TODAY:
RedisTools.remove("reportToDayBangumi");
QQBotManager.getInstance().sendMessage(BangumiTools.reportToDayBangumi());
break;
case QQCommands.QQ_BANGUMI_LIST:
getInstance().sendMessage("获取中...");
getInstance().sendMessage(BangumiTools.reportBangumiList());
break;
case QQCommands.QQ_BT_RELOAD:
HttpTools.get("http://192.168.31.88:8000/bt/down.do");
break;
case QQCommands.QQ_SYSTEM_RESTART:
getInstance().sendMessage("正在重启服务");
System.out.println("结束进程");
AppTools.exec("cd /home/yutou/public/servier/tools && ./start.sh",null,true,false);
break;
case QQCommands.QQ_HELP:
builder = new StringBuilder();
for (Field field : QQCommands.class.getDeclaredFields()) {
try {
field.setAccessible(true);
builder.append(field.get(null)).append("\n");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
getInstance().sendMessage(builder.toString());
break;
case QQCommands.QQ_TOOLS_IDEA:
builder = new StringBuilder();
if(StringUtils.isEmpty(RedisTools.get("ideaUrl"))){
builder.append("暂未设置IDEA激活码下载地址");
}else {
for (String name : IdeaTools.getIdeaList(RedisTools.get("ideaUrl"))) {
builder.append(QQCommands.QQ_TOOLS_IDEA_FILE).append(name).append("\n");
}
if(builder.toString().trim().length()==0){
builder.append("激活码文件中未包含txt文件");
}
}
getInstance().sendMessage(builder.toString());
break;
default:
if (msg.startsWith(QQCommands.QQ_CMD)) {
RedisTools.Consumer.system("cmd", msg.replace(QQCommands.QQ_CMD, ""));
} else if (msg.startsWith(QQCommands.QQ_BANGUMI_SUB)) {
List<String> infos = null;
try {
int id = Integer.parseInt(msg.replace(QQCommands.QQ_BANGUMI_SUB, "").trim());
infos = BangumiTools.reportBangumiInfo(id);
} catch (Exception e) {
String key = msg.replace(QQCommands.QQ_BANGUMI_SUB, "").trim();
infos = BangumiTools.reportSearchBangumi(key);
}
for (String info : infos) {
List<String> imgs = new ArrayList<>();
if (info.contains("<img") && info.contains(" /img>")) {
imgs = getImages(info);
for (String img : imgs) {
info = info.replace("<img " + img + " /img>", "");
}
}
sendImagesMsg(imgs, info);
}
} else if (msg.startsWith(QQCommands.QQ_AUDIO)) {
QQAudio.playText(msg.replace(QQCommands.QQ_AUDIO, ""));
}else if(msg.startsWith(QQCommands.QQ_TOOLS_IDEA_FILE)){
getInstance().sendMessage(IdeaTools.getIdea(msgSrc.replace(QQCommands.QQ_TOOLS_IDEA_FILE,"")));
}else if(msg.startsWith(QQCommands.QQ_TOOLS_IDEA_URL)){
RedisTools.set("ideaUrl",msg.replace(QQCommands.QQ_TOOLS_IDEA_URL,"").trim());
getInstance().sendMessage("已设定下载地址:"+RedisTools.get("ideaUrl"));
}
}
}
private List<File> files;
private int index = 0;
private void sendImagesMsg(List<String> imgs, String text) {
files = new ArrayList<>();
index = 0;
if (imgs.size() == 0) {
getInstance().sendMessage(text);
return;
}
for (String img : imgs) {
HttpTools.download(img,null, new DownloadInterface() {
@Override
public void onDownload(File file) {
super.onDownload(file);
files.add(file);
send(imgs.size(), text);
}
@Override
public void onError(Exception e) {
super.onError(e);
index++;
send(imgs.size(), text);
}
});
}
}
private void send(int size, String text) {
if ((files.size() + index) == size) {
String str = getInstance().sendMessage(files, text);
Log.i("str = " + str);
}
}
private void sendVersion() {
String localVersion = QQBotApplication.version;
String serverVersion = HttpTools.get("http://tools.yutou233.cn:8000/public/version.do?token=zIrsh9TUZP2lfRW753PannG49E7VJvor");
String msg = "本地版本:" + localVersion + "\n" + "服务器版本:" + serverVersion;
QQBotManager.getInstance().sendMessage(msg);
AppTools.sendServer("服务版本查询", msg);
}
}
}

View File

@ -0,0 +1,9 @@
package com.yutou.qqbot.interfaces;
import java.io.File;
public abstract class DownloadInterface {
public void onDownloading(double soFarBytes, double totalBytes){};
public void onDownload(File file){};
public void onError(Exception e){};
}

View File

@ -0,0 +1,5 @@
package com.yutou.qqbot.interfaces;
public abstract class ObjectInterface {
public void out(String data){};
}

View File

@ -0,0 +1,10 @@
package com.yutou.qqbot.models.audio;
import com.yutou.qqbot.utlis.AudioTools;
public class QQAudio {
public static void playText(String text){
AudioTools.playText(text);
}
}

View File

@ -0,0 +1,207 @@
package com.yutou.qqbot.models.setu;
import com.alibaba.fastjson.JSONObject;
import com.yutou.qqbot.QQBotManager;
import com.yutou.qqbot.utlis.AppTools;
import com.yutou.qqbot.utlis.Log;
import com.yutou.qqbot.utlis.RedisTools;
import net.mamoe.mirai.event.events.GroupMessageEvent;
import net.mamoe.mirai.message.data.At;
import net.mamoe.mirai.message.data.Image;
import net.mamoe.mirai.message.data.MessageChainBuilder;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
public class QQSetu {
public static void printTodaySetu() {
String redisKey= AppTools.getToDayTime() + "_setu";
Log.i("今日涩图 redisKey = " + redisKey);
String js = RedisTools.get(redisKey, 1);
if (js != null) {
JSONObject json = JSONObject.parseObject(js);
if(json.containsKey("isPrint")&&json.getBoolean("isPrint")){
return;
}
Map<String,Float> groupAverage=new HashMap<>();
Map<String,String> groupImage=new HashMap<>();
JSONObject setu=null;
for (String id : json.keySet()) {
String group=json.getJSONObject(id).getJSONObject("info").getLong("group")+"";
if(groupAverage.containsKey(group)){
if(groupAverage.get(group)<=json.getJSONObject(id).getFloat("average")){
groupAverage.put(group,json.getJSONObject(id).getFloat("average"));
groupImage.put(group,id);
}
}else{
groupAverage.put(group,json.getJSONObject(id).getFloat("average"));
groupImage.put(group,id);
}
}
for (String id : groupImage.keySet()) {
setu=json.getJSONObject(groupImage.get(id));
if(setu!=null){
json.put("isPrint",true);
RedisTools.set(1,redisKey,json.toJSONString());
JSONObject info=setu.getJSONObject("info");
JSONObject score=setu.getJSONObject("score");
MessageChainBuilder builder = new MessageChainBuilder();
builder.append(Image.fromId(info.getString("id")));
builder.append("本日最佳涩图由").append(new At(info.getLong("sourQQ"))).append("提供\n");
builder.append("获得分数 ").append(String.valueOf(setu.getFloat("average"))).append("\n");
builder.append("共有 ").append(String.valueOf(score.getIntValue("userNumber"))).append(" 人参与投票");
QQBotManager.getInstance().sendMessage(info.getLong("group"),builder);
Log.i("今日涩图:"+builder.toString());
}
}
}else {
Log.i("今日没有涩图");
}
}
private boolean isSetu(Image image) {
String url = Image.queryUrl(image);
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
int length = connection.getContentLength();
connection.disconnect();
if (length > 50000) {
return true;
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return false;
}
private void setuBuilder(Image image, GroupMessageEvent event) {
if (!isSetu(image)) {
return;
}
if (RedisTools.get(event.getGroup().getId()+"setu") != null) {
printSetu(event.getGroup().getId());
}
setuScore.clear();
JSONObject json = new JSONObject();
json.put("id", image.getImageId());
json.put("sourName", event.getSenderName());
json.put("sourQQ", event.getSender().getId());
json.put("group", event.getGroup().getId());
RedisTools.set(event.getGroup().getId()+"setu", json.toJSONString(),6*60);
if (timer != null) {
timer.cancel();
timer = null;
}
startTimer(event.getGroup().getId());
}
private void startTimer(long group) {
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
if(!setuScore.isEmpty()){
printSetu(group);
}
timer = null;
}
}, 5 * 60 * 1000);
}
private void printSetu(long group) {
JSONObject jt = JSONObject.parseObject(RedisTools.get(group+"setu"));
String id = jt.getString("id");
float average = 0;
float max = 0;
float min = 10;
float length = 0;
String maxName = "";
String minName = "";
if(setuScore.size()<=1){
return;
}
for (String name : setuScore.keySet()) {
length += setuScore.get(name);
average += setuScore.get(name);
if (setuScore.get(name) > max) {
max = setuScore.get(name);
maxName = name.split("\\|")[0];
}
if (setuScore.get(name) < min) {
min = setuScore.get(name);
minName = name.split("\\|")[0];
}
}
JSONObject score = new JSONObject();
score.put("max", max);
score.put("min", min);
score.put("sum", length);
score.put("maxName", maxName);
score.put("minName", minName);
score.put("userNumber", setuScore.size());
average = average / setuScore.size();
String builder = "涩图评分:" + average +"\n "+
"其中最高分由:" + maxName + " 给与:" + max +"\n "+
"其中最低分由:" + minName + " 给与:" + min;
QQBotManager.getInstance().sendMessage(group, builder);
String st = RedisTools.get(AppTools.getToDayTime() + "_setu", 1);
JSONObject json;
if (st == null) {
json = new JSONObject();
} else {
json = JSONObject.parseObject(st);
}
if (!json.containsKey(id)) {
JSONObject item;
if (json.containsKey("item")) {
item = json.getJSONObject("item");
} else {
item = new JSONObject();
}
item.put("score", score);
item.put("info", jt);
item.put("average", average);
json.put(id, item);
RedisTools.set(1, AppTools.getToDayTime() + "_setu", json.toJSONString());
}
RedisTools.remove(group+"setu",0);
setuScore.clear();
}
public void setu(String msg, GroupMessageEvent event) {
if (msg.trim().equals("[图片]")) {
Image image = (Image) event.getMessage().stream().filter(Image.class::isInstance).findFirst().orElse(null);
if (image != null) {
setuBuilder(image, event);
return;
}
}
try {
if(msg.trim().length()>3){
return;
}
float i = Float.parseFloat(msg.trim());
if (i > 0 && i <= 10) {
String name = event.getSenderName();
String qq=event.getSender().getId()+"";
if (!setuScore.containsKey(name)) {
setuScore.put(name+"|"+qq, i);
}
}
} catch (Exception ignored) {
}
}
private Timer timer;
private static Map<String, Float> setuScore = new HashMap<>();
}

View File

@ -0,0 +1,176 @@
package com.yutou.qqbot.utlis;
import com.yutou.qqbot.QQBotManager;
import com.yutou.qqbot.interfaces.DownloadInterface;
import com.yutou.qqbot.interfaces.ObjectInterface;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.type.filter.TypeFilter;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
public class AppTools {
public static String getToDayNowTimeToString() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}
public static String getToDayTime() {
return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
}
/**
* 异常输出
*
* @param e 异常
* @return
*/
public static String getExceptionString(Exception e) {
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
e.printStackTrace(printWriter);
printWriter.close();
return writer.toString();
}
public static void exec(String exec, ObjectInterface objectInterface, boolean isOutQQBot, boolean isInput) {
try {
Process process;
if (AppTools.isRuntimeSystemOfWindow()) {
process = Runtime.getRuntime().exec(new String[]{
"cmd",
"/c",
exec
}
);
} else {
process = Runtime.getRuntime().exec(new String[]{
"sh",
"-c",
exec
}
);
}
if (isInput) {
processOut(process.getInputStream(), objectInterface, isOutQQBot);
processOut(process.getErrorStream());
} else {
processOut(process.getErrorStream(), objectInterface, isOutQQBot);
processOut(process.getInputStream());
}
process.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean isRuntimeSystemOfWindow() {
return System.getProperty("os.name").contains("Windows");
}
public static List<Class> scanClass(String classPath, Class<? extends Annotation> annotation) {
List<Class> classList = new ArrayList<>();
if (ObjectUtils.isEmpty(classPath)) {
return classList;
}
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
TypeFilter includeFilter = (metadataReader, metadataReaderFactory) -> true;
provider.addIncludeFilter(includeFilter);
Set<BeanDefinition> beanDefinitionSet = new HashSet<>();
// 指定扫描的包名
Set<BeanDefinition> candidateComponents = provider.findCandidateComponents(classPath);
beanDefinitionSet.addAll(candidateComponents);
beanDefinitionSet.forEach(beanDefinition -> {
try {
Class clazz = Class.forName(beanDefinition.getBeanClassName());
if (!ObjectUtils.isEmpty(annotation)) {
if (!ObjectUtils.isEmpty(AnnotationUtils.getAnnotation(clazz, annotation))) {
classList.add(clazz);
}
} else {
classList.add(clazz);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// System.out.println(definition.getBeanClassName());
});
return classList;
}
public static void processOut(InputStream inputStream) {
processOut(inputStream,null,true);
}
public static void processOut(InputStream inputStream, ObjectInterface objectInterface, boolean isOutQQBot){
String tmp;
StringBuilder str = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
while ((tmp = reader.readLine()) != null) {
str.append(tmp).append("\n");
}
reader.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
if(objectInterface!=null){
objectInterface.out(str.toString());
}
// com.yutou.nas.utils.Log.i("cmd > " + str);
if(isOutQQBot) {
QQBotManager.getInstance().sendMessage(str.toString());
}
}
public static void sendServer(String title, String msg) {
try {
Log.i("title=" + title + " msg=" + msg);
HttpTools.post("https://sctapi.ftqq.com/SCT2619Tpqu93OYtQCrK4LOZYEfr2irm.send",
("title="+ URLEncoder.encode(title, "UTF-8") + "&desp=" + URLEncoder.encode(msg, "UTF-8")).getBytes(StandardCharsets.UTF_8));
if (ConfigTools.load(ConfigTools.CONFIG, "model").equals("nas")) {
String img = null;
msg = msg.replace("<br/>", "\n");
if (msg.contains("![logo]")) {
try {
img = msg.split("!\\[logo\\]\\(")[1].split("\\)")[0];
msg = msg.replace("![logo](" + img + ")", "");
} catch (Exception e) {
e.printStackTrace();
}
}
if (img == null) {
QQBotManager.getInstance().sendMessage(title + "\n" + msg);
} else {
String finalMsg = msg;
String finalImg = img;
if (QQBotManager.getInstance().isLogin()) {
HttpTools.download(img,title+".png", new DownloadInterface() {
@Override
public void onDownload(File file) {
super.onDownload(file);
QQBotManager.getInstance().sendMessage(file, title + "\n" + finalMsg);
}
@Override
public void onError(Exception e) {
super.onError(e);
QQBotManager.getInstance().sendMessage(title + "\n" + finalMsg + "\n" + finalImg);
}
});
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,66 @@
package com.yutou.qqbot.utlis;
import com.iflytek.cloud.speech.*;
public class AudioTools {
private static boolean init = false;
synchronized static void init() {
if (init) {
return;
}
SpeechUtility.createUtility(SpeechConstant.APPID + "=601f7f7d");
SpeechUtility.getUtility().setParameter(SpeechConstant.VOLUME,"100");
SpeechUtility.getUtility().setParameter(SpeechConstant.LIB_NAME_64,"/media/yutou/disk_lvm/public/servier/tools/");
SpeechUtility.getUtility().setParameter(SpeechConstant.LIB_NAME_32,"/media/yutou/disk_lvm/public/servier/tools/");
init = true;
Log.i("讯飞语音已初始化");
}
public static void playText(String text) {
SpeechSynthesizer mss = SpeechSynthesizer.createSynthesizer();
mss.startSpeaking(text, new SynthesizerListener() {
@Override
public void onBufferProgress(int progress, int beginPos, int endPos,
String info) {
if (progress == 100) {
mss.destroy();
}
}
@Override
public void onSpeakBegin() {
}
@Override
public void onSpeakProgress(int i, int i1, int i2) {
}
@Override
public void onSpeakPaused() {
}
@Override
public void onSpeakResumed() {
}
@Override
public void onCompleted(SpeechError speechError) {
Log.i(speechError.getErrorDesc() + " code " + speechError.getErrorCode());
}
@Override
public void onEvent(int i, int i1, int i2, int i3, Object o, Object o1) {
}
});
}
public static void main(String[] args) {
init();
playText("小爱同学,开灯");
}
}

View File

@ -0,0 +1,450 @@
package com.yutou.qqbot.utlis;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yutou.qqbot.QQBotManager;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class BangumiTools {
private static final String url = "https://api.bgm.tv/";
private static final String toDayBangumi = url + "calendar";
private static final String BangumiInfo = url + "/subject/%s?responseGroup=large";
private static final String SearchBangumi = url + "/search/subject/%s?responseGroup=large";
/**
* 获取番剧列表
*
* @param day 周几-1为全部,非1~7范围则为当天
* @return 当日数据
*/
public static JSONObject getBangumi(int day) {
String str = HttpTools.get(toDayBangumi);
JSONArray main = JSONArray.parseArray(str);
if (day == -1) {
JSONObject json = new JSONObject();
json.put("bangumi", main);
return json;
}
if (day < 1 || day > 7) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.setTime(new Date());
day = calendar.get(Calendar.DAY_OF_WEEK) - 1;
if (day == 0) {
day = 7;
}
}
if (main != null) {
for (Object o : main) {
JSONObject json = (JSONObject) o;
if (json.getJSONObject("weekday").getInteger("id") == day) {
return json;
}
}
}
return null;
}
/**
* 获取番剧详细信息
*
* @param id 剧集id
* @return 详细信息
*/
public static JSONObject getBangumiInfo(int id) {
String str = HttpTools.get(String.format(BangumiInfo, id + ""));
return JSONObject.parseObject(str);
}
public static JSONArray getPeople(int id) {
/**
* Actor 演员
* Composer 作曲家
* Director 导演
* GuestStar 特邀明星
* Producer 制片人
* Writer 编剧
*/
JSONArray people = new JSONArray();
JSONObject bangumi = getBangumiInfo(id);
JSONArray crt = bangumi.getJSONArray("crt");
if(crt!=null) {
for (Object o : crt) {
JSONObject item = (JSONObject) o;
JSONObject pel = new JSONObject();
pel.put("Name", item.getString("name_cn"));
pel.put("Role", item.getString("role_name"));
pel.put("Type", "Actor");
people.add(pel);
}
}
crt = bangumi.getJSONArray("staff");
if(crt!=null) {
for (Object o : crt) {
JSONObject item = (JSONObject) o;
JSONObject pel = new JSONObject();
pel.put("Name", item.getString("name_cn"));
String jobsName="";
for (Object _jobs : item.getJSONArray("jobs")) {
jobsName+=_jobs+"";
}
jobsName=jobsName.substring(0,jobsName.length()-1);
pel.put("Role", jobsName);
pel.put("Type", "");
if (jobsName.contains("导演")) {
pel.put("Type", "Director");
} else if (jobsName.contains("脚本")) {
pel.put("Type", "DirectorDirector");
}
people.add(pel);
}
}
return people;
}
/**
* 搜索番剧
*
* @param key 关键词
* @return 详细信息
*/
public static JSONObject search(String key) {
String str = HttpTools.get(String.format(SearchBangumi, key));
return JSONObject.parseObject(str);
}
/**
* 获取下一集播放日期
*
* @param id 番剧id
* @return 日期
*/
public static String getPlayNextTime(int id) {
JSONObject info = getBangumiInfo(id);
JSONArray eps = info.getJSONArray("eps");
String toDayTime = AppTools.getToDayTime();
for (Object o : eps) {
JSONObject ep = (JSONObject) o;
String time = ep.getString("airdate");
try {
if (new SimpleDateFormat("yyyy-MM-dd").parse(time).getTime() >=
new SimpleDateFormat("yyyy-MM-dd").parse(toDayTime).getTime()) {
return time;
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
/**
* 格式化字符串输出番剧详细信息
*
* @param id 番剧id
* @return 详细内容
*/
public static List<String> reportBangumiInfo(int id) {
List<String> bangumiList = new ArrayList<>();
JSONObject json = getBangumiInfo(id);
if (json.containsKey("code")) {
bangumiList.add("error = " + json.toJSONString());
return bangumiList;
}
JSONArray eps = json.getJSONArray("eps");
JSONArray crts = json.getJSONArray("crt");
JSONArray staffs = json.getJSONArray("staff");
StringBuilder builder = new StringBuilder();
builder.append("<img ").append(json.getJSONObject("images").getString("large")).append(" /img>").append("\n");
builder.append("标题:").append(json.getString("name_cn")).append("\n");
builder.append("日文标题:").append(json.getString("name")).append("\n");
builder.append("首播时间:").append(json.getString("air_date")).append("\n");
builder.append("每周").append(json.getInteger("air_weekday")).append("放送").append("\n");
builder.append("Bangumi地址:").append(json.getString("url")).append("\n");
builder.append("Bangumi评分:").append(json.getJSONObject("rating").getFloat("score")).append("\n");
builder.append("预计放送集数:").append(json.getInteger("eps_count")).append("\n");
if (eps != null) {
builder.append("已放送集:").append("\n");
for (Object o : eps) {
JSONObject ep = (JSONObject) o;
if (ep.getString("status").equals("Air")) {
builder.append("· 第").append(ep.getInteger("sort")).append("话:");
builder.append(ep.getString("name"));
builder.append("[").append(ep.getString("name_cn")).append("]").append("\n");
builder.append("播放日期:").append(ep.getString("airdate")).append(";\n");
builder.append("播放时长:").append(ep.getString("duration")).append(";\n");
builder.append("单集介绍:").append(ep.getString("desc"));
builder.append("\n\n");
} else {
builder.append("下一话:");
builder.append("").append(ep.getInteger("sort")).append("话:");
builder.append("播放日期:").append(ep.getString("airdate")).append("\n\n");
break;
}
}
}
if (crts != null) {
builder.append("角色介绍:").append("\n");
for (Object o : crts) {
JSONObject crt = (JSONObject) o;
JSONObject info = crt.getJSONObject("info");
builder.append(crt.getString("role_name")).append(":");
builder.append(crt.getString("name"));
builder.append("(").append(crt.getString("name_cn")).append(")").append(" ");
builder.append("CV:").append(crt.getJSONArray("actors").getJSONObject(0).getString("name"));
builder.append("(").append(info.getString("gender")).append(")");
builder.append("\n");
}
}
Map<String, List<JSONObject>> map = new HashMap<>();
for (Object o : staffs) {
JSONObject staff = (JSONObject) o;
for (Object jobs : staff.getJSONArray("jobs")) {
String job = (String) jobs;
List<JSONObject> list;
if (!map.containsKey(job)) {
list = new ArrayList<>();
} else {
list = map.get(job);
}
list.add(staff);
map.put(job, list);
}
}
if (!map.isEmpty()) {
builder.append("staff:").append("\n");
for (String key : map.keySet()) {
builder.append(key).append(":");
for (JSONObject staff : map.get(key)) {
builder.append(staff.getString("name_cn"));
builder.append("(").append(staff.getString("name")).append(")");
builder.append("");
}
builder.append("\n");
}
}
bangumiList.add(builder.toString());
return bangumiList;
}
/**
* 格式化输出新番列表
*
* @return 新番信息
*/
public static String reportBangumiList() {
try {
JSONObject json = getBangumi(-1);
StringBuilder builder = new StringBuilder();
assert json != null;
JSONArray array = json.getJSONArray("bangumi");
for (Object o : array) {
JSONObject data = (JSONObject) o;
JSONObject weekday = data.getJSONObject("weekday");
JSONArray items = data.getJSONArray("items");
builder.append(weekday.getString("cn")).append("(").append(weekday.getString("ja")).append(")");
builder.append(":").append("\n");
reportBangumi(builder, items, false);
builder.append("\n");
}
return builder.toString();
} catch (Exception e) {
e.printStackTrace();
return e.getMessage();
}
}
private static void reportBangumi(StringBuilder builder, JSONArray items, boolean reportEp) {
int epIndex = 0;
String epName = "N/A";
for (Object oj : items) {
JSONObject item = (JSONObject) oj;
builder.append("[").append(item.getInteger("id")).append("]");
builder.append(StringUtils.isEmpty(item.getString("name_cn"))
? item.getString("name") : item.getString("name_cn"));
if (!reportEp) {
builder.append("\n");
continue;
}
JSONObject info = getBangumiInfo(item.getInteger("id"));
if (info.get("eps") == null) {
continue;
}
JSONArray eps = info.getJSONArray("eps");
for (Object oe : eps) {
JSONObject ep = (JSONObject) oe;
if (ep.getString("status").equals("Air")) {
epIndex = ep.getInteger("sort");
epName = ep.getString("name");
} else {
break;
}
}
builder.append("").append(epIndex).append("话:");
builder.append(epName);
builder.append("\n");
}
}
/**
* 格式化字符串输出今日播放番剧列表
*
* @return 番剧列表
*/
public static String reportToDayBangumi() {
String toDayTime = AppTools.getToDayTime();
if (!toDayTime.equals(RedisTools.get("reportToDayBangumi"))) {
RedisTools.set("reportToDayBangumi", toDayTime);
StringBuilder builder = new StringBuilder();
JSONObject toDay = getBangumi(0);
if (toDay == null) {
builder.append("今天没有任何番剧放送~");
} else {
JSONObject weekday = toDay.getJSONObject("weekday");
JSONArray items = toDay.getJSONArray("items");
builder.append("今日 ").append(weekday.get("cn")).append("(").append(weekday.get("ja")).append(")");
builder.append(" 放送列表:").append("\n");
reportBangumi(builder, items, true);
}
RedisTools.set("toDayBangumi", builder.toString());
return builder.toString();
} else {
System.out.println("error ");
return RedisTools.get("toDayBangumi");
}
}
/**
* 格式化字符串输出搜索动画
*
* @param key 关键词
* @return 详细内容
*/
public static List<String> reportSearchBangumi(String key) {
List<String> bangumiList = new ArrayList<>();
JSONObject main = search(key);
if (main.getInteger("results") > 0) {
StringBuilder builder = new StringBuilder();
List<JSONObject> list = main.getJSONArray("list").toJavaList(JSONObject.class);
Collections.reverse(list);
for (Object items : list) {
JSONObject item = (JSONObject) items;
builder = new StringBuilder();
builder.append("标题:").append(item.getString("name_cn")).append("\n");
builder.append("日文标题:").append(item.getString("name")).append("\n");
String type;
switch (item.getInteger("type")) {
case 1:
type = "书籍";
break;
case 2:
type = "动画";
break;
case 3:
type = "音乐";
break;
case 4:
type = "游戏";
break;
case 6:
type = "真人剧(Real)";
break;
default:
type = item.getInteger("type") + "";
}
builder.append("类型:").append(type).append("\n");
builder.append("id:").append(item.getInteger("id")).append("\n");
if (item.containsKey("rating")) {
builder.append("Bangumi评分:").append(item.getJSONObject("rating").getFloat("score")).append("\n");
}
builder.append("首播时间:").append(item.getString("air_date")).append("\n");
builder.append("每周 ").append(item.getInteger("air_weekday")).append(" 放送").append("\n");
builder.append("放送集数:").append(item.getInteger("eps")).append("\n");
builder.append("Bangumi地址:").append(item.getString("url")).append("\n");
builder.append("介绍:").append(item.getString("summary")).append("\n");
builder.append("\n").append("\n");
bangumiList.add(builder.toString());
}
return bangumiList;
} else {
bangumiList.add("搜索不到任何内容:" + key);
return bangumiList;
}
}
public static void saveInfoToJellyfin(String name) {
JSONObject json = search(name);
JSONArray array = json.getJSONArray("list");
int id = 0;
StringBuilder bangumiName = new StringBuilder();
for (Object o : array) {
JSONObject _item = (JSONObject) o;
bangumiName.append(_item.getString("name_cn"))
.append(":")
.append(QQBotManager.QQCommands.QQ_BANGUMI_INFO)
.append(_item.getString("id"))
.append("\n");
if (_item.getString("name_cn").equals(name)) {
id = _item.getInteger("id");
break;
}
}
if (id == 0) {
QQBotManager.getInstance().sendMessage("没有与《" + name + "》完全匹配的信息,请填写。 \n" + bangumiName.toString());
return;
}
json = getBangumiInfo(id);
}
public static void main(String[] args) {
/* JSONObject json = search("小林家的龙女仆S");
System.out.println(json);
json = getBangumiInfo(274234);
System.err.println("------------");
System.out.println(json);*/
byte[] user=new byte[] {
78, 106, 73, 49, 79, 122, 65, 51, 89, 71,
65, 117, 78, 106, 78, 109, 78, 122, 99, 55,
89, 109, 85, 61 };
byte[] password=new byte[] {
89, 87, 66, 108, 79, 109, 90, 110, 78, 106,
65, 117, 79, 109, 74, 109, 78, 122, 65, 120,
79, 50, 89, 61 };
user=Base64.getDecoder().decode(user);
password=Base64.getDecoder().decode(password);
String showUser=new String(a(user));
String showPassword=new String(a(password));
System.out.println("user = "+showUser);
System.out.println("pass = "+showPassword);
String[] t1=showUser.split("-");
int t11=Integer.parseInt(t1[0],16);
int t12=Integer.parseInt(t1[1],16);
System.out.println("t11 = " + t11);
System.out.println("t12 = " + t12);
System.out.println((t11-t12));
int index=0;
for (int i = 0; i <= 13; i++) {
String t=i+"";
if(t.contains("1")){
index++;
System.err.println(t);
}
}
System.out.println(index);
System.out.println(15);
}
public static byte[] a(byte[] tmp){
byte[] data=tmp.clone();
for (byte i = 0; i < data.length; i++) {
data[i]= (byte) (data[i]^3);
}
return data;
}
}

View File

@ -0,0 +1,116 @@
package com.yutou.qqbot.utlis;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
/**
* 配置和参数
*/
public class ConfigTools {
public static final String CONFIG = "config.json";
public static final String DATA = "data.json";
public static final String SQLITE = "sqlite.json";
static {
try {
File file = new File(CONFIG);
if (!file.exists()) {
file.createNewFile();
}
file = new File(DATA);
if (!file.exists()) {
file.createNewFile();
}
file = null;
} catch (Exception e) {
e.printStackTrace();
}
}
public static Object load(String type, String key) {
return load(type, key, Object.class, null);
}
public static <T> T load(String type, String key, Class<T> t) {
return load(type, key, t, null);
}
public static <T> T load(String type, String key, Class<T> t, T def) {
File file = new File(type);
//com.yutou.nas.utils.Log.i(type+"配置文件地址:"+file.getAbsolutePath());
String src = readFile(file);
if (src != null) {
try {
JSONObject json = JSONObject.parseObject(src);
return json.getObject(key, t);
} catch (Exception e) {
}
}
return def;
}
public static String loadIni(File file, String key) {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String tmp, str = null;
while ((tmp = reader.readLine()) != null) {
if(tmp.startsWith(key+"=")){
str=tmp.split("=")[1];
if(StringUtils.isEmpty(str)){
str=null;
}
break;
}
}
return str;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static boolean save(String type, String key, Object data) {
File file = new File(type);
String src = readFile(file);
if (src == null) {
src = "{}";
}
JSONObject json = JSONObject.parseObject(src);
json.put(key, data);
saveFile(file, json.toJSONString());
return false;
}
public static boolean saveFile(File file, String data) {
try {
FileWriter writer = new FileWriter(file);
writer.write(data);
writer.flush();
writer.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static String readFile(File file) {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String tmp;
StringBuilder str = new StringBuilder();
while ((tmp = reader.readLine()) != null) {
str.append(tmp);
}
reader.close();
return str.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

View File

@ -0,0 +1,260 @@
package com.yutou.qqbot.utlis;
import com.alibaba.fastjson.JSONObject;
import com.yutou.qqbot.interfaces.DownloadInterface;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Set;
public class HttpTools {
public static final String serverKey = "zIrsh9TUZP2lfRW753PannG49E7VJvor";
private static final int HttpRequestIndex = 3;
public static String get(String url) {
return https_get(url, null);
}
public static String post(final String url, final byte[] body) {
return http_post(url, body, 0, null);
}
public static File syncDownload(final String url, final String saveName) {
return new HttpTools().http_syncDownload(url, saveName);
}
public static String https_get(String url, Map<String, String> header) {
try {
URLConnection connection;
connection = new URL(url).openConnection();
connection.setRequestProperty("User-Agent", getExtUa());
if (header != null) {
for (String key : header.keySet()) {
connection.addRequestProperty(key, header.get(key));
}
}
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder str = new StringBuilder();
String tmp;
while ((tmp = reader.readLine()) != null) {
str.append(tmp);
}
reader.close();
return str.toString();
} catch (Exception e) {
System.err.println("error url = " + url);
e.printStackTrace();
}
return null;
}
public static String http_post(String url, byte[] body, int index, Map<String, String> headers) {
String tmp;
StringBuilder str = new StringBuilder();
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
if (headers != null) {
for (String key : headers.keySet()) {
connection.addRequestProperty(key, headers.get(key));
}
}
connection.setDoOutput(true);
connection.setDoInput(true);
connection.addRequestProperty("User-Agent", getExtUa());
connection.setConnectTimeout(5 * 1000);
connection.setReadTimeout(10 * 1000);
//connection.addRequestProperty("Connection", "keep-alive");
//connection.addRequestProperty("User-Agent", getExtUa());
//connection.addRequestProperty("content-type", "application/json");
connection.addRequestProperty("charset", "UTF-8");
OutputStream outputStream = connection.getOutputStream();
//System.out.println(new String(body));
outputStream.write(body);
outputStream.flush();
outputStream.close();
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((tmp = reader.readLine()) != null) {
str.append(tmp);
}
String finalStr = str.toString();
connection.disconnect();
reader.close();
return finalStr;
} catch (Exception e) {
if (index < HttpRequestIndex) {
return http_post(url, body, index + 1, headers);
} else {
e.printStackTrace();
return null;
}
}
}
private static String getExtUa() {
return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36";
}
private static String getKuKuUA() {
return "/KUKU_APP(Android/#/cn.kuku.sdk/ttsdk17228/29401/A-2.9.4.01.KUSDK/868139039134314/fcddf839c8c135fa/F4:60:E2:AB:25:1A/460019406520644/+8618569400341/#/9/Redmi 6 Pro/xiaomi/1736/76fda4d6-cd6b-485f-987b-8d347b007f24/#/KUKU/Native/92972ea9651fbd2e)";
}
public String toUrlParams(JSONObject json) {
StringBuilder string = new StringBuilder();
Set<String> keys = json.keySet();
for (String key : keys) {
try {
string.append("&").append(key).append("=").append(URLEncoder.encode(json.getString(key), "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
try {
string.append("&").append(URLEncoder.encode(key, "UTF-8")).append("=");
// string += "&" + key + "=";
} catch (Exception e1) {
string.append("&").append(key).append("=");
}
}
}
string = new StringBuilder(string.substring(1, string.length()).replaceAll(" ", ""));
return string.toString();
}
public static void main(String[] args) {
JSONObject json = new JSONObject();
json.put("pid", "102");
json.put("gid", "100584");
json.put("gameKey", "0gha58u1c9FjZkeAsEmYIzTvp");
json.put("access_token", "659c-S1gV0DwMXdYjPDlSrSLNYOvA8qUoCSvmdFEHvZugKgNX4Z2BCwF18A7W2gRdG7WiWfKsbZgF6YssZHhaozksI9RBn2QQFTXzmAHtbMd4ginEEtwdKmPCM4JbJGg1ollqoNE0PcGENpa4F3e7EdSOa_JFyE6XyUQN1iurJU3F8MZfLlTIcTR9USYoHX15vsAkCht_0mrapZblkeY1_8HFrmK8rlenbZLxccy7PrMz5eZ9uPPDJL5OYiEahyrtLENB8SVmlGofJfQw8wUjN8_XVZSfLMujdwz24");
String url = "http://192.168.1.156:9020/Faxing/reg?" +
"&tpyeCode=dimai" +
"&regParamJson=" + json.toJSONString();
/* ExecutorService service= Executors.newCachedThreadPool();
for (int i = 0; i < 3000; i++) {
service.submit(new Runnable() {
@Override
public void run() {
get(url);
}
});
}*/
Log.i(url);
//String str=get(url);
}
private static String donwloadPath = "tmp" + File.separator;
public synchronized static void download(final String url, final String saveName, final DownloadInterface downloadInterface) {
new Thread(new Runnable() {
@Override
public void run() {
File jar = null;
try {
File savePath = new File(donwloadPath);
if (!savePath.exists()) {
savePath.mkdirs();
}
Log.i("DOWNLOAD", "下载文件:" + url + " 保存文件:" + saveName);
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.addRequestProperty("User-Agent", getExtUa());
// Log.i(TAG,"获取到网络请求:"+connection.getResponseCode());
InputStream inputStream = connection.getInputStream();
jar = new File(donwloadPath + saveName + "_tmp.tmp");
jar.createNewFile();
Log.i("DOWNLOAD", "临时保存文件:" + jar.getAbsolutePath());
OutputStream outputStream = new FileOutputStream(jar);
byte[] bytes = new byte[1024];
double size = connection.getContentLength();
double downSize = 0;
int len;
while ((len = inputStream.read(bytes)) > 0) {
outputStream.write(bytes, 0, len);
downSize += len;
if (downloadInterface != null) {
downloadInterface.onDownloading(downSize, size);
}
}
outputStream.close();
inputStream.close();
File oldJar = new File(donwloadPath + saveName);
if (oldJar.exists()) {
oldJar.delete();
}
jar.renameTo(oldJar);
Log.i("DOWNLOAD", "实际保存:" + oldJar.getAbsolutePath() + " " + oldJar.getName());
if (downloadInterface != null) {
downloadInterface.onDownload(oldJar);
}
} catch (Exception e) {
e.printStackTrace();
if (jar != null) {
jar.delete();
}
if (downloadInterface != null) {
downloadInterface.onError(e);
}
}
}
}).start();
}
public synchronized File http_syncDownload(final String url, final String saveName) {
if (StringUtils.isEmpty(url)) {
return null;
}
File jar = null;
try {
File savePath = new File(donwloadPath);
if (!savePath.exists()) {
savePath.mkdirs();
}
Log.i("DOWNLOAD", "下载文件:" + url + " 保存文件:" + saveName);
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.addRequestProperty("User-Agent", getExtUa());
// Log.i(TAG,"获取到网络请求:"+connection.getResponseCode());
InputStream inputStream = connection.getInputStream();
jar = new File(donwloadPath + saveName + "_tmp.tmp");
jar.createNewFile();
Log.i("DOWNLOAD", "临时保存文件:" + jar.getAbsolutePath());
OutputStream outputStream = new FileOutputStream(jar);
byte[] bytes = new byte[1024];
double size = connection.getContentLength();
double downSize = 0;
int len;
while ((len = inputStream.read(bytes)) > 0) {
outputStream.write(bytes, 0, len);
downSize += len;
}
outputStream.close();
inputStream.close();
File oldJar = new File(donwloadPath + saveName);
if (oldJar.exists()) {
oldJar.delete();
}
connection.disconnect();
jar.renameTo(oldJar);
Log.i("DOWNLOAD", "实际保存:" + oldJar.getAbsolutePath() + " " + oldJar.getName());
return oldJar;
} catch (Exception e) {
e.printStackTrace();
if (jar != null) {
jar.delete();
}
return null;
}
}
}

View File

@ -0,0 +1,51 @@
package com.yutou.qqbot.utlis;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class IdeaTools {
public static String getIdea(String name) {
if(StringUtils.isEmpty(name)){
return "";
}
File file = new File("tmp" + File.separator + "idea.zip");
try {
ZipFile zipFile = new ZipFile(file, Charset.forName("gbk"));
String data = "";
if (file.exists()&&zipFile.getEntry(name)!=null) {
data = StreamTools.streamReadLine(zipFile.getInputStream(zipFile.getEntry(name)));
}
zipFile.close();
return data;
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public static List<String> getIdeaList(String url) {
File file = HttpTools.syncDownload(url, "idea.zip");
List<String> list = new ArrayList<>();
try {
ZipFile zip = new ZipFile(file, Charset.forName("gbk"));
Enumeration<? extends ZipEntry> ez = zip.entries();
while (ez.hasMoreElements()) {
ZipEntry entry = ez.nextElement();
if (entry.getName().endsWith(".txt")) {
list.add(entry.getName());
}
}
zip.close();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
}

View File

@ -0,0 +1,24 @@
package com.yutou.qqbot.utlis;
public class Log {
public static void i(String tag, Object log) {
i('[' + tag + ']' + log);
}
public static void i(Object log) {
if (ConfigTools.load(ConfigTools.CONFIG, "logout",boolean.class,false)) {
System.out.printf("[%s]%s%n",
AppTools.getToDayNowTimeToString(),
log
);
}
}
public static void e(String tag,Exception e){
System.err.printf("[%s]%s - %s%n",
AppTools.getToDayNowTimeToString(),
tag,
AppTools.getExceptionString(e)
);
}
}

View File

@ -0,0 +1,309 @@
package com.yutou.qqbot.utlis;
import com.alibaba.fastjson.JSONObject;
import com.yutou.qqbot.QQBotManager;
import com.yutou.qqbot.interfaces.ObjectInterface;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisPubSub;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.Set;
public class RedisTools {
private static boolean isNotInstallRedis = false;
private static String host;
private static int port;
public static int TOKEN_TIMEOUT_DEFAULT = 360;
public final static int DATABASES_ALI_OSS=4;
private RedisTools() {
}
// 写成静态代码块形式只加载一次节省资源
static {
//Properties properties = PropertyUtil.loadProperties("jedis.properties");
//host = properties.getProperty("redis.host");
//port = Integer.valueOf(properties.getProperty("redis.port"));
host = "127.0.0.1";
port = 6379;
}
public static boolean set(int dbIndex, String key, String value) {
try {
if (isNotInstallRedis) {
return false;
}
Jedis jedis = getRedis();
jedis.select(dbIndex);
String ret = jedis.set(key, value);
Log.i("Redis set =" + ret);
jedis.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return false;
}
return true;
}
public static boolean set(String key, String value) {
return set(0, key, value);
}
public static boolean set(String key, String value, int timeout) {
try {
if (isNotInstallRedis) {
return false;
}
Jedis jedis = getRedis();
if (timeout == -1) {
jedis.set(key, value);
} else {
jedis.setex(key, timeout, value);
}
jedis.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return false;
}
return true;
}
public static String get(String key, int dbIndex) {
String value = "-999";
if (isNotInstallRedis) {
return value;
}
try (Jedis jedis = getRedis()) {
jedis.select(dbIndex);
value = jedis.get(key);
jedis.close();
} catch (Exception e) {
// TODO: handle exception
// e.printStackTrace();
}
return value;
}
public static String get(String key) {
return get(key, 0);
}
public static boolean remove(String key) {
return remove(key,0);
}
public static void removeLoginState(String uid) {
Jedis jedis = getRedis();
Set<String> keys = jedis.keys("*");
for (String string : keys) {
if (string.equals(uid)) {
jedis.del(string);
}
}
}
public static String ping() {
Jedis jedis = getRedis();
String tmp = jedis.ping();
jedis.close();
return tmp;
}
public static boolean exists(String key, String value) {
if (isNotInstallRedis) {
return false;
}
Jedis jedis = getRedis();
boolean flag = value.equals(jedis.get(key));
jedis.close();
return flag;
}
public static Jedis getRedis() {
return new Jedis(host, port);
}
public static boolean remove(String key, int index) {
if (isNotInstallRedis) {
return false;
}
Jedis jedis = getRedis();
jedis.select(index);
Long i = jedis.del(key);
jedis.close();
if (i > 0) {
return true;
} else {
return false;
}
}
private static class PropertyUtil {
// 加载property文件到io流里面
public static Properties loadProperties(String propertyFile) {
Properties properties = new Properties();
try {
InputStream is = PropertyUtil.class.getClassLoader().getResourceAsStream(propertyFile);
if (is == null) {
is = PropertyUtil.class.getClassLoader().getResourceAsStream(propertyFile);
}
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
return properties;
}
}
private static Jedis getPoolRedis() {
if (isNotInstallRedis) {
return null;
}
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(0);
poolConfig.setMaxWaitMillis(1000);
JedisPool pool = new JedisPool(poolConfig, host);
return pool.getResource();
}
public static void pullMsg(String channel, String msg) {
Log.i("1");
Jedis jedis = getPoolRedis();
Log.i("2");
jedis.publish(channel, msg);
Log.i("3");
jedis.close();
Log.i("4");
}
private static boolean init = false;
public static void initRedisPoolSub() {
if (init) {
return;
}
init = true;
Log.i("初始化订阅");
new Thread(new Runnable() {
@Override
public void run() {
Jedis jedis = getPoolRedis();
if (jedis != null) {
jedis.psubscribe(new Consumer(), "*");
}
}
}).start();
}
public static class Consumer extends JedisPubSub {
@Override
public void onPMessage(String pattern, String channel, String message) {
super.onPMessage(pattern, channel, message);
Log.i("onPMessage: channel=" + channel + " msg=" + message + " pattern=" + pattern);
switch (channel) {
case "system":
switch (message) {
case "openPC":
system("openPC", null);
break;
case "updateIP":
system("updateIP", null);
break;
}
break;
case "bot":
bot(message);
break;
case "cmd":
system("cmd", message);
break;
case "msg":
AppTools.sendServer("来自服务姬的通知~",message);
break;
}
}
@Override
public void onMessage(String channel, String message) {
super.onMessage(channel, message);
Log.i("onMessage: channel=" + channel + " msg=" + message);
}
public static void system(String type, String value) {
try {
String exec = null;
switch (type) {
case "openPC":
exec = "wakeonlan 00:D8:61:6F:02:2F";
break;
case "cmd":
exec = value;
break;
case "updateIP":
exec = "python3 /media/yutou/disk_lvm/public/Python/tools/ip.py";
break;
}
if (exec != null) {
Process process = Runtime.getRuntime().exec(exec);
processOut(process.getInputStream());
processOut(process.getErrorStream());
process.destroy();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void bot(String value) {
switch (value) {
case "getip":
JSONObject json = JSONObject.parseObject(HttpTools.get("https://api.asilu.com/ip/"));
String ip = json.getString("ip");
QQBotManager.getInstance().sendMessage("服务器IP:\n" + ip);
break;
}
}
}
public static void processOut(InputStream inputStream) {
processOut(inputStream,null,true);
}
public static void processOut(InputStream inputStream, ObjectInterface objectInterface, boolean isOutQQBot){
String tmp;
StringBuilder str = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
while ((tmp = reader.readLine()) != null) {
str.append(tmp).append("\n");
}
reader.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
if(objectInterface!=null){
objectInterface.out(str.toString());
}
// Log.i("cmd > " + str);
if(isOutQQBot) {
QQBotManager.getInstance().sendMessage(str.toString());
}
}
public static void main(String[] args) {
RedisTools.pullMsg("msg", "abc");
}
}

View File

@ -0,0 +1,57 @@
package com.yutou.qqbot.utlis;
import java.io.*;
public class StreamTools {
public static String streamReadLine(InputStream stream) {
StringBuilder builder = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String tmp;
while ((tmp = reader.readLine()) != null) {
builder.append(tmp);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return builder.toString();
}
public static File streamSave(InputStream stream) {
try {
if (stream != null) {
File file = new File("tmp" + File.separator + System.currentTimeMillis());
FileOutputStream outputStream = new FileOutputStream(file);
byte[] bytes = new byte[2048];
int len;
while ((len = stream.read(bytes)) > -1) {
outputStream.write(bytes, 0, len);
}
outputStream.flush();
stream.close();
outputStream.close();
return file;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static byte[] fileToByte(File file){
byte[] buffer = new byte[1024];
ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
int len;
try {
FileInputStream in = new FileInputStream(file);
while ((len = in.read(buffer, 0, 1024)) != -1) {
outputStream.write(buffer,0,len);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return outputStream.toByteArray();
}
}

View File

@ -0,0 +1,7 @@
package com.yutou.qqbot.utlis;
public class StringUtils {
public static boolean isEmpty(String str){
return str == null || str.trim().length() == 0;
}
}

View File

@ -0,0 +1 @@
server.port=8002

View File

@ -0,0 +1 @@
server.port=8002

View File

@ -0,0 +1,13 @@
package com.yutou.qqbot;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class QqBotApplicationTests {
@Test
void contextLoads() {
}
}