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

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;
}
}