Compare commits
13 Commits
master
...
7637aa2fec
| Author | SHA1 | Date | |
|---|---|---|---|
| 7637aa2fec | |||
| 9347eb9cde | |||
| bc483e50b5 | |||
| b55991798f | |||
| 12f224b8f3 | |||
| 068964145f | |||
| 864d5960a7 | |||
| 94890f001c | |||
| 73566a41e5 | |||
| 56774792c1 | |||
| e7fae929a1 | |||
| 09305ae824 | |||
| 1041dfa909 |
38
pom.xml
38
pom.xml
@@ -164,6 +164,44 @@
|
||||
<artifactId>jsoup</artifactId>
|
||||
<version>1.17.2</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.baidubce</groupId>
|
||||
<artifactId>qianfan</artifactId>
|
||||
<version>0.1.3</version>
|
||||
</dependency>
|
||||
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-core</artifactId>
|
||||
<version>2.24.1</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-bom</artifactId>
|
||||
<version>2.24.1</version>
|
||||
<scope>import</scope>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.logging.log4j</groupId>
|
||||
<artifactId>log4j-api</artifactId>
|
||||
<version>2.24.1</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-logging</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-log4j2</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
@@ -10,6 +10,7 @@ import com.yutou.napcat.http.NapCatApi;
|
||||
import com.yutou.qqbot.QQBotManager;
|
||||
import com.yutou.qqbot.utlis.Base64Tools;
|
||||
import lombok.val;
|
||||
import okhttp3.Headers;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
@@ -42,7 +43,7 @@ public class NapCatQQ {
|
||||
.build()
|
||||
).enqueue(new HttpCallback<SendMessageResponse>() {
|
||||
@Override
|
||||
public void onResponse(int code, String status, SendMessageResponse response, String rawResponse) {
|
||||
public void onResponse(Headers headers, int code, String status, SendMessageResponse response, String rawResponse) {
|
||||
System.out.println("code = " + code + ", status = " + status + ", response = " + response + ", rawResponse = " + rawResponse);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.yutou.napcat.handle;
|
||||
import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.yutou.okhttp.BaseBean;
|
||||
import com.yutou.qqbot.utlis.StringUtils;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -13,6 +14,7 @@ public class MessageHandleBuild {
|
||||
private long qq;
|
||||
private boolean autoEscape;
|
||||
private boolean isGroup;
|
||||
private String messageId;
|
||||
|
||||
public static MessageHandleBuild create() {
|
||||
return new MessageHandleBuild();
|
||||
@@ -41,7 +43,10 @@ public class MessageHandleBuild {
|
||||
isGroup = group;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MessageHandleBuild setMessageId(String messageId) {
|
||||
this.messageId = messageId;
|
||||
return this;
|
||||
}
|
||||
public JSONObject build() {
|
||||
JSONObject json=new JSONObject();
|
||||
if(isGroup){
|
||||
@@ -51,6 +56,9 @@ public class MessageHandleBuild {
|
||||
}
|
||||
json.put("auto_escape", autoEscape);
|
||||
json.put("message", msgList);
|
||||
if(!StringUtils.isEmpty(messageId)){
|
||||
json.put("message_id",messageId);
|
||||
}
|
||||
return json;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,9 +6,7 @@ import com.yutou.napcat.model.GroupUserBean;
|
||||
import com.yutou.okhttp.BaseBean;
|
||||
import com.yutou.okhttp.HttpBody;
|
||||
import retrofit2.Call;
|
||||
import retrofit2.http.Field;
|
||||
import retrofit2.http.FormUrlEncoded;
|
||||
import retrofit2.http.POST;
|
||||
import retrofit2.http.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -20,12 +18,11 @@ public interface GroupApi {
|
||||
* @param user 用户
|
||||
* @param duration 禁言时长,单位秒
|
||||
*/
|
||||
@FormUrlEncoded
|
||||
@POST("/set_group_ban")
|
||||
@GET("/set_group_ban")
|
||||
Call<HttpBody<BaseBean>> groupBan(
|
||||
@Field("group_id") long group,
|
||||
@Field("user_id") long user,
|
||||
@Field("duration") long duration
|
||||
@Query("group_id") long group,
|
||||
@Query("user_id") long user,
|
||||
@Query("duration") long duration
|
||||
);
|
||||
|
||||
/**
|
||||
|
||||
@@ -44,9 +44,9 @@ public interface MessageAPI {
|
||||
@Field("message_id") long messageId
|
||||
);
|
||||
|
||||
@FormUrlEncoded
|
||||
@POST("/get_msg")
|
||||
Call<HttpBody<MessageBean>> getMessage(
|
||||
@Field("message_id") long messageId
|
||||
@Body
|
||||
JSONObject message
|
||||
);
|
||||
}
|
||||
|
||||
11
src/main/java/com/yutou/okhttp/FileBody.java
Normal file
11
src/main/java/com/yutou/okhttp/FileBody.java
Normal file
@@ -0,0 +1,11 @@
|
||||
package com.yutou.okhttp;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.InputStream;
|
||||
|
||||
@Data
|
||||
public class FileBody<T> {
|
||||
InputStream inputStream;
|
||||
T t;
|
||||
}
|
||||
112
src/main/java/com/yutou/okhttp/FileCallback.java
Normal file
112
src/main/java/com/yutou/okhttp/FileCallback.java
Normal file
@@ -0,0 +1,112 @@
|
||||
package com.yutou.okhttp;
|
||||
|
||||
import com.yutou.qqbot.utlis.Log;
|
||||
import okhttp3.Headers;
|
||||
import okhttp3.HttpUrl;
|
||||
import retrofit2.Call;
|
||||
import retrofit2.Callback;
|
||||
import retrofit2.Response;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public abstract class FileCallback<T> implements Callback<FileBody<T>> {
|
||||
|
||||
private static ThreadPoolExecutor executor;
|
||||
private final T bean;
|
||||
private String savePath;
|
||||
|
||||
public FileCallback(T bean, String savePath) {
|
||||
this.bean = bean;
|
||||
this.savePath = savePath;
|
||||
if (executor == null) {
|
||||
executor = new ThreadPoolExecutor(2, 4, Long.MAX_VALUE, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(100));
|
||||
}
|
||||
}
|
||||
|
||||
private class DownloadTask implements Runnable {
|
||||
private T bean;
|
||||
private Headers headers;
|
||||
private HttpUrl url;
|
||||
private InputStream inputStream;
|
||||
|
||||
public DownloadTask(T bean, Headers headers, HttpUrl url, InputStream inputStream) {
|
||||
this.bean = bean;
|
||||
|
||||
this.headers = headers;
|
||||
this.url = url;
|
||||
this.inputStream = inputStream;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Log.i("开始下载");
|
||||
File file = new File(savePath);
|
||||
onStart(bean);
|
||||
if (!file.exists()) {
|
||||
boolean mkdirs = file.getParentFile().mkdirs();
|
||||
Log.i("mkdirs = " + mkdirs);
|
||||
}
|
||||
FileOutputStream outputStream = new FileOutputStream(file);
|
||||
int len;
|
||||
long total = 0;
|
||||
byte[] bytes = new byte[4096];
|
||||
boolean isDownload = true;
|
||||
long available = inputStream.available();
|
||||
while ((len = inputStream.read(bytes)) != -1 && isDownload) {
|
||||
total += len;
|
||||
outputStream.write(bytes, 0, len);
|
||||
outputStream.flush();
|
||||
isDownload = onDownload(headers, bean, total, available);
|
||||
}
|
||||
Log.i("下载完成");
|
||||
outputStream.close();
|
||||
} catch (Exception e) {
|
||||
Log.e(e);
|
||||
onFailure(bean,e);
|
||||
} finally {
|
||||
onFinish(bean);
|
||||
try {
|
||||
inputStream.close();
|
||||
} catch (IOException e) {
|
||||
Log.e(e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public abstract void onStart(T bean);
|
||||
|
||||
public abstract boolean onDownload(Headers headers, T bean, long len, long total);
|
||||
|
||||
public abstract void onFinish(T bean);
|
||||
|
||||
public abstract void onFailure(T bean, Throwable throwable);
|
||||
|
||||
@Override
|
||||
public void onResponse(Call<FileBody<T>> call, Response<FileBody<T>> response) {
|
||||
try {
|
||||
executor.execute(new DownloadTask(bean, response.headers(), call.request().url(), response.body().getInputStream()));
|
||||
} catch (Exception e) {
|
||||
Log.e(e);
|
||||
onFailure(bean,e);
|
||||
call.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Call<FileBody<T>> call, Throwable throwable) {
|
||||
onFailure(bean, throwable);
|
||||
call.cancel();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.yutou.okhttp;
|
||||
|
||||
|
||||
import okhttp3.Headers;
|
||||
import okhttp3.HttpUrl;
|
||||
import okhttp3.Request;
|
||||
|
||||
@@ -14,12 +15,18 @@ public class GetRequestParams implements IRequestParam {
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public Request getRequest(HashMap<String, String> map, Request request) {
|
||||
public Request getRequest(HashMap<String, String> headerMap, HashMap<String, String> map, Request request) {
|
||||
Headers.Builder headerBuild = request.headers().newBuilder();
|
||||
if (!headerMap.isEmpty()) {
|
||||
for (String key : headerMap.keySet()) {
|
||||
headerBuild.add(key, headerMap.get(key));
|
||||
}
|
||||
}
|
||||
//添加公共参数
|
||||
HttpUrl.Builder builder = request.url().newBuilder();
|
||||
for (String key : map.keySet()) {
|
||||
builder.addQueryParameter(key, String.valueOf(map.get(key)));
|
||||
}
|
||||
return request.newBuilder().url(builder.build()).build();
|
||||
return request.newBuilder().url(builder.build()).headers(headerBuild.build()).build();
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
package com.yutou.okhttp;
|
||||
|
||||
import okhttp3.Headers;
|
||||
import retrofit2.Call;
|
||||
import retrofit2.Callback;
|
||||
import retrofit2.Response;
|
||||
|
||||
public abstract class HttpCallback<T> implements Callback<HttpBody<T>> {
|
||||
|
||||
public abstract void onResponse(int code, String status, T response, String rawResponse);
|
||||
public abstract void onResponse(Headers headers,int code, String status, T response, String rawResponse);
|
||||
|
||||
public abstract void onFailure(Throwable throwable);
|
||||
|
||||
@@ -14,6 +15,7 @@ public abstract class HttpCallback<T> implements Callback<HttpBody<T>> {
|
||||
public void onResponse(Call<HttpBody<T>> call, Response<HttpBody<T>> response) {
|
||||
if (response.body() != null) {
|
||||
onResponse(
|
||||
response.headers(),
|
||||
response.body().getRetcode(),
|
||||
response.body().getStatus(),
|
||||
response.body().getData(),
|
||||
@@ -22,10 +24,12 @@ public abstract class HttpCallback<T> implements Callback<HttpBody<T>> {
|
||||
} else {
|
||||
onFailure(new NullPointerException("response body is null"));
|
||||
}
|
||||
call.cancel();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(Call<HttpBody<T>> call, Throwable throwable) {
|
||||
onFailure(throwable);
|
||||
call.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
145
src/main/java/com/yutou/okhttp/HttpDownloadUtils.java
Normal file
145
src/main/java/com/yutou/okhttp/HttpDownloadUtils.java
Normal file
@@ -0,0 +1,145 @@
|
||||
package com.yutou.okhttp;
|
||||
|
||||
import com.yutou.qqbot.interfaces.DownloadInterface;
|
||||
import com.yutou.qqbot.utlis.ConfigTools;
|
||||
import com.yutou.qqbot.utlis.Log;
|
||||
import lombok.Data;
|
||||
import okhttp3.*;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class HttpDownloadUtils {
|
||||
public static void download(Builder builder) {
|
||||
createHttpClient(builder).enqueue(new Callback() {
|
||||
@Override
|
||||
public void onFailure(@NotNull Call call, @NotNull IOException e) {
|
||||
if (builder.downloadInterface != null) {
|
||||
builder.downloadInterface.onError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
|
||||
InputStream inputStream = Objects.requireNonNull(response.body()).byteStream();
|
||||
File target;
|
||||
if (StringUtils.hasText(builder.fileName)) {
|
||||
target = new File(builder.path, builder.fileName);
|
||||
} else {
|
||||
target = new File(builder.path);
|
||||
}
|
||||
FileOutputStream fileOutputStream = new FileOutputStream(target);
|
||||
if (builder.downloadInterface != null) {
|
||||
builder.downloadInterface.onDownloadStart();
|
||||
}
|
||||
try {
|
||||
byte[] buffer = new byte[2048];
|
||||
int len;
|
||||
long soFarBytes = 0;
|
||||
long totalBytes = inputStream.available();
|
||||
while ((len = inputStream.read(buffer)) != -1) {
|
||||
fileOutputStream.write(buffer, 0, len);
|
||||
soFarBytes += len;
|
||||
if (builder.downloadInterface != null) {
|
||||
if (!builder.downloadInterface.onDownloading(soFarBytes, totalBytes)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
fileOutputStream.flush();
|
||||
} catch (IOException e) {
|
||||
Log.e(e,"download error:", builder.url);
|
||||
} finally {
|
||||
if (builder.downloadInterface != null) {
|
||||
builder.downloadInterface.onDownload(target);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static File downloadSync(Builder builder) {
|
||||
try {
|
||||
Response response = createHttpClient(builder).execute();
|
||||
InputStream inputStream = Objects.requireNonNull(response.body()).byteStream();
|
||||
File target;
|
||||
if (StringUtils.hasText(builder.fileName)) {
|
||||
target = new File(builder.path, builder.fileName);
|
||||
} else {
|
||||
target = new File(builder.path);
|
||||
}
|
||||
try (FileOutputStream fileOutputStream = new FileOutputStream(target)) {
|
||||
byte[] buffer = new byte[2048];
|
||||
int len;
|
||||
while ((len = inputStream.read(buffer)) != -1) {
|
||||
fileOutputStream.write(buffer, 0, len);
|
||||
}
|
||||
fileOutputStream.flush();
|
||||
return target;
|
||||
} catch (IOException e) {
|
||||
Log.e(e,"download error:" , builder.url);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Call createHttpClient(Builder builder) {
|
||||
OkHttpClient okHttpClient = new OkHttpClient.Builder()
|
||||
.connectTimeout(2, TimeUnit.MINUTES)
|
||||
.readTimeout(2, TimeUnit.MINUTES)
|
||||
.build();
|
||||
Request.Builder rb = new Request.Builder()
|
||||
.get()
|
||||
.addHeader("User-Agent", ConfigTools.getUserAgent())
|
||||
.url(builder.url);
|
||||
if (StringUtils.hasText(builder.cookie)) {
|
||||
rb.addHeader("Set-Cookie", builder.cookie);
|
||||
rb.addHeader("Cookie", builder.cookie);
|
||||
}
|
||||
Request request = rb.build();
|
||||
return okHttpClient.newCall(request);
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Builder {
|
||||
String url;
|
||||
String path;
|
||||
String fileName;
|
||||
DownloadInterface downloadInterface;
|
||||
String cookie;
|
||||
|
||||
public Builder setUrl(String url) {
|
||||
this.url = url;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setPath(String path) {
|
||||
this.path = path;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setFileName(String fileName) {
|
||||
this.fileName = fileName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setDownloadInterface(DownloadInterface downloadInterface) {
|
||||
this.downloadInterface = downloadInterface;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder setCookie(String cookie) {
|
||||
this.cookie = cookie;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,34 +1,25 @@
|
||||
package com.yutou.okhttp;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import com.yutou.qqbot.utlis.Log;
|
||||
import okhttp3.Connection;
|
||||
import okhttp3.Headers;
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.MediaType;
|
||||
import okhttp3.Protocol;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.RequestBody;
|
||||
import okhttp3.Response;
|
||||
import okhttp3.ResponseBody;
|
||||
import lombok.val;
|
||||
import okhttp3.*;
|
||||
import okhttp3.internal.http.HttpHeaders;
|
||||
import okio.Buffer;
|
||||
import okio.BufferedSource;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class HttpLoggingInterceptor implements Interceptor {
|
||||
private static final String TAG = "HttpLogging";
|
||||
|
||||
private static final Charset UTF8 = Charset.forName("UTF-8");
|
||||
private static final Charset UTF8 = StandardCharsets.UTF_8;
|
||||
|
||||
private volatile Level printLevel = Level.NONE;
|
||||
private volatile Level printLevel = Level.BODY;
|
||||
private java.util.logging.Level colorLevel;
|
||||
private Logger logger;
|
||||
|
||||
@@ -63,7 +54,7 @@ public class HttpLoggingInterceptor implements Interceptor {
|
||||
private void log(String message) {
|
||||
//logger.log(colorLevel, message);
|
||||
if (prLog) {
|
||||
Log.i(TAG, message);
|
||||
Log.getDynamicLogger(TAG).info(message);
|
||||
}
|
||||
//Log.e(TAG,message);
|
||||
}
|
||||
@@ -71,8 +62,11 @@ public class HttpLoggingInterceptor implements Interceptor {
|
||||
@Override
|
||||
public Response intercept(Chain chain) throws IOException {
|
||||
Request request = chain.request();
|
||||
if (request.body().contentLength() == 0) {
|
||||
request = chain.call().request();
|
||||
if (request.body() != null && request.body().contentLength() == 0) {
|
||||
val headers = request.headers();
|
||||
request = chain.call().request().newBuilder()
|
||||
.headers(headers)
|
||||
.build();
|
||||
}
|
||||
if (printLevel == Level.NONE) {
|
||||
return chain.proceed(request);
|
||||
@@ -109,8 +103,6 @@ public class HttpLoggingInterceptor implements Interceptor {
|
||||
|
||||
if (logHeaders) {
|
||||
if (hasRequestBody) {
|
||||
// Request body headers are only present when installed as a network interceptor. Force
|
||||
// them to be included (when available) so there values are known.
|
||||
if (requestBody.contentType() != null) {
|
||||
log("\tContent-Type: " + requestBody.contentType());
|
||||
}
|
||||
@@ -121,7 +113,6 @@ public class HttpLoggingInterceptor implements Interceptor {
|
||||
Headers headers = request.headers();
|
||||
for (int i = 0, count = headers.size(); i < count; i++) {
|
||||
String name = headers.name(i);
|
||||
// Skip headers from the request body as they are explicitly logged above.
|
||||
if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
|
||||
log("\t" + name + ": " + headers.value(i));
|
||||
}
|
||||
@@ -151,7 +142,7 @@ public class HttpLoggingInterceptor implements Interceptor {
|
||||
boolean logHeaders = (printLevel == Level.BODY || printLevel == Level.HEADERS);
|
||||
|
||||
try {
|
||||
log("<-- " + clone.code() + ' ' + clone.message() + ' ' + clone.request().url() + " (" + tookMs + "ms)");
|
||||
log("<-- " + clone.code() + ' ' + clone.message() + ' ' + clone.request().url() + " (" + tookMs + "ms)");
|
||||
if (logHeaders) {
|
||||
Headers headers = clone.headers();
|
||||
for (int i = 0, count = headers.size(); i < count; i++) {
|
||||
@@ -162,12 +153,13 @@ public class HttpLoggingInterceptor implements Interceptor {
|
||||
if (responseBody == null) return response;
|
||||
|
||||
if (isPlaintext(responseBody.contentType())) {
|
||||
byte[] bytes = responseBody.byteStream().readAllBytes();
|
||||
MediaType contentType = responseBody.contentType();
|
||||
String body = new String(bytes, getCharset(contentType));
|
||||
BufferedSource source = responseBody.source();
|
||||
source.request(Long.MAX_VALUE); // 请求整个流
|
||||
Buffer buffer = source.buffer();
|
||||
|
||||
Charset charset = getCharset(responseBody.contentType());
|
||||
String body = buffer.clone().readString(charset);
|
||||
log("\tbody:" + body);
|
||||
responseBody = ResponseBody.create(responseBody.contentType(), bytes);
|
||||
return response.newBuilder().body(responseBody).build();
|
||||
} else {
|
||||
log("\tbody: maybe [binary body], omitted!");
|
||||
}
|
||||
@@ -214,6 +206,8 @@ public class HttpLoggingInterceptor implements Interceptor {
|
||||
body.writeTo(buffer);
|
||||
Charset charset = getCharset(body.contentType());
|
||||
log("\tbody:" + buffer.readString(charset));
|
||||
// 重置请求体以确保后续处理不受影响
|
||||
buffer.clear();
|
||||
} catch (Exception e) {
|
||||
logger.log(java.util.logging.Level.WARNING, e.getMessage(), e);
|
||||
}
|
||||
|
||||
@@ -5,5 +5,5 @@ import okhttp3.Request;
|
||||
import java.util.HashMap;
|
||||
|
||||
public interface IRequestParam {
|
||||
Request getRequest(HashMap<String,String> map, Request request);
|
||||
Request getRequest(HashMap<String,String> header, HashMap<String,String> map, Request request);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.yutou.okhttp;
|
||||
|
||||
import com.yutou.qqbot.utlis.ConfigTools;
|
||||
import okhttp3.Request;
|
||||
|
||||
import java.util.HashMap;
|
||||
@@ -7,14 +8,25 @@ import java.util.HashMap;
|
||||
public class ParamsContext {
|
||||
private IRequestParam iRequestParam;
|
||||
private Request request;
|
||||
private HashMap<String,String> map;
|
||||
private HashMap<String, String> map;
|
||||
private HashMap<String, String> headerMap;
|
||||
|
||||
public ParamsContext(HashMap<String,String> map,Request request) {
|
||||
if(map==null){
|
||||
map=new HashMap<>();
|
||||
public ParamsContext(HashMap<String, String> map, Request request) {
|
||||
if (map == null) {
|
||||
map = new HashMap<>();
|
||||
}
|
||||
this.map=map;
|
||||
this.map = map;
|
||||
this.request = request;
|
||||
this.headerMap = new HashMap<>();
|
||||
}
|
||||
|
||||
public ParamsContext(HashMap<String, String> headerMap, HashMap<String, String> map, Request request) {
|
||||
if (map == null) {
|
||||
map = new HashMap<>();
|
||||
}
|
||||
this.map = map;
|
||||
this.request = request;
|
||||
this.headerMap = headerMap;
|
||||
}
|
||||
|
||||
public Request getInRequest() {
|
||||
@@ -26,6 +38,7 @@ public class ParamsContext {
|
||||
iRequestParam = new PostRequestParams();
|
||||
break;
|
||||
}
|
||||
return iRequestParam.getRequest(map,request);
|
||||
headerMap.put("User-Agent", ConfigTools.getUserAgent());
|
||||
return iRequestParam.getRequest(headerMap, map, request);
|
||||
}
|
||||
}
|
||||
@@ -2,22 +2,26 @@ package com.yutou.okhttp;
|
||||
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
|
||||
import com.yutou.qqbot.utlis.Log;
|
||||
import okhttp3.*;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
public class PostRequestParams implements IRequestParam {
|
||||
@Override
|
||||
public Request getRequest(HashMap<String, String> map, Request request) {
|
||||
public Request getRequest(HashMap<String, String> headerMap, HashMap<String, String> map, Request request) {
|
||||
Headers.Builder headerBuilder = request.headers().newBuilder();
|
||||
if (!headerMap.isEmpty()) {
|
||||
for (String key : headerMap.keySet()) {
|
||||
headerBuilder.add(key, headerMap.get(key));
|
||||
}
|
||||
}
|
||||
if (request.body() instanceof FormBody) {
|
||||
FormBody.Builder bodyBuilder = new FormBody.Builder();
|
||||
FormBody formBody = (FormBody) request.body();
|
||||
|
||||
for (int i = 0; i < formBody.size(); i++) {
|
||||
bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));
|
||||
}
|
||||
@@ -25,10 +29,12 @@ public class PostRequestParams implements IRequestParam {
|
||||
bodyBuilder.addEncoded(key, String.valueOf(map.get(key)));
|
||||
}
|
||||
formBody = bodyBuilder.build();
|
||||
request = request.newBuilder().post(formBody).build();
|
||||
request = request.newBuilder().headers(headerBuilder.build()).post(formBody).build();
|
||||
} else if (request.body() != null) {
|
||||
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),toUrlParams(map));
|
||||
request = request.newBuilder().post(request.body())
|
||||
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), toUrlParams(map));
|
||||
request = request.newBuilder()
|
||||
.headers(headerBuilder.build())
|
||||
.post(request.body())
|
||||
.post(requestBody).build();
|
||||
}
|
||||
return request;
|
||||
@@ -41,9 +47,9 @@ public class PostRequestParams implements IRequestParam {
|
||||
try {
|
||||
string.append("&").append(key).append("=").append(URLEncoder.encode(json.getString(key), "UTF-8"));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
Log.e(e);
|
||||
try {
|
||||
string.append("&").append(URLEncoder.encode(key,"UTF-8")).append("=");
|
||||
string.append("&").append(URLEncoder.encode(key, "UTF-8")).append("=");
|
||||
// string += "&" + key + "=";
|
||||
} catch (Exception e1) {
|
||||
string.append("&").append(key).append("=");
|
||||
@@ -56,7 +62,7 @@ public class PostRequestParams implements IRequestParam {
|
||||
}
|
||||
|
||||
public static String toUrlParams(Map<String, String> map) {
|
||||
if(map.isEmpty()){
|
||||
if (map.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder builder = new StringBuilder();
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
package com.yutou.okhttp.api;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.internal.bind.DateTypeAdapter;
|
||||
import com.yutou.okhttp.HttpBody;
|
||||
import com.yutou.okhttp.HttpLoggingInterceptor;
|
||||
import com.yutou.okhttp.ParamsContext;
|
||||
import com.yutou.okhttp.converter.JsonCallAdapter;
|
||||
import com.yutou.okhttp.converter.JsonConverterFactory;
|
||||
import okhttp3.Interceptor;
|
||||
import okhttp3.OkHttpClient;
|
||||
import okhttp3.Request;
|
||||
import okhttp3.Response;
|
||||
import lombok.val;
|
||||
import okhttp3.*;
|
||||
import retrofit2.CallAdapter;
|
||||
import retrofit2.Converter;
|
||||
import retrofit2.Retrofit;
|
||||
@@ -18,31 +18,55 @@ import retrofit2.Retrofit;
|
||||
import java.io.IOException;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.logging.Level;
|
||||
|
||||
public class BaseApi {
|
||||
private String URL;
|
||||
private HashMap<String, String> params;
|
||||
private HashMap<String, String> params = new HashMap<>();
|
||||
private HashMap<String, String> headers = new HashMap<>();
|
||||
|
||||
|
||||
public BaseApi setURL(String URL) {
|
||||
this.URL = URL;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BaseApi setHeaders(HashMap<String, String> headers) {
|
||||
this.headers = headers;
|
||||
return this;
|
||||
}
|
||||
|
||||
public void addHeader(HashMap<String, String> headers) {
|
||||
this.headers.putAll(headers);
|
||||
}
|
||||
|
||||
|
||||
public BaseApi setParams(HashMap<String, String> params) {
|
||||
this.params = params;
|
||||
return this;
|
||||
}
|
||||
|
||||
public void useCookie(JSONObject json) {
|
||||
StringBuilder ck = new StringBuilder();
|
||||
json.remove("sql_time");
|
||||
json.remove("gourl");
|
||||
for (String key : json.keySet()) {
|
||||
ck.append(key).append("=").append(json.getString(key)).append(";");
|
||||
}
|
||||
headers.put("Cookie", ck.toString());
|
||||
setHeaders(headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建一个接口方法
|
||||
*
|
||||
* @param okHttpClient okhttp客户端
|
||||
* @param converterFactory 处理工厂类
|
||||
* @param okHttpClient okhttp客户端
|
||||
* @param converterFactory 处理工厂类
|
||||
* @param callAdapterFactory 请求适配器工厂
|
||||
* @param baseUrl 基础地质
|
||||
* @param service 接口
|
||||
* @param <T> 接口泛型
|
||||
* @param baseUrl 基础地质
|
||||
* @param service 接口
|
||||
* @param <T> 接口泛型
|
||||
* @return 接口
|
||||
*/
|
||||
public <T> T create(OkHttpClient okHttpClient, Converter.Factory converterFactory, CallAdapter.Factory callAdapterFactory, String baseUrl, Class<T> service) {
|
||||
@@ -74,7 +98,10 @@ public class BaseApi {
|
||||
loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
|
||||
OkHttpClient.Builder builder = new OkHttpClient()
|
||||
.newBuilder()
|
||||
|
||||
.callTimeout(2, TimeUnit.MINUTES)
|
||||
.readTimeout(2, TimeUnit.MINUTES)
|
||||
.connectTimeout(2, TimeUnit.MINUTES)
|
||||
.writeTimeout(2, TimeUnit.MINUTES)
|
||||
.addInterceptor(initQuery())
|
||||
.addInterceptor(loggingInterceptor);
|
||||
return create(builder.build(),
|
||||
@@ -83,14 +110,30 @@ public class BaseApi {
|
||||
URL,
|
||||
apiClass);
|
||||
}
|
||||
|
||||
public Interceptor initQuery() {
|
||||
Interceptor addQueryParameterInterceptor = new Interceptor() {
|
||||
@Override
|
||||
public Response intercept(Chain chain) throws IOException {
|
||||
Request request = chain.request();
|
||||
//配置公共参数
|
||||
request = new ParamsContext(params,request).getInRequest();
|
||||
return chain.proceed(request);
|
||||
request = new ParamsContext(headers, params, request).getInRequest();
|
||||
val proceed = chain.proceed(request);
|
||||
if (!proceed.isSuccessful()) {
|
||||
HttpBody<?> httpBody = new HttpBody<>();
|
||||
httpBody.setCode(200);
|
||||
val parse = JSONObject.parse(proceed.body().string());
|
||||
httpBody.setRetcode(parse.getInteger("code"));
|
||||
httpBody.setMsg(parse.getString("message"));
|
||||
ResponseBody errorResponseBody = ResponseBody.create(
|
||||
JSONObject.toJSONString(httpBody),
|
||||
MediaType.get("application/json; charset=utf-8"));
|
||||
val newResponse=proceed.newBuilder()
|
||||
.code(200)
|
||||
.body(errorResponseBody).build();
|
||||
return newResponse;
|
||||
}
|
||||
return proceed;
|
||||
}
|
||||
};
|
||||
return addQueryParameterInterceptor;
|
||||
|
||||
@@ -31,12 +31,26 @@ public class JsonResponseBodyConverter<T> implements Converter<ResponseBody, T>
|
||||
HttpBody<T> body;
|
||||
try {
|
||||
body = JSONObject.parseObject(string, type);
|
||||
if(body.getData()==null){
|
||||
JSONObject jt=JSONObject.parseObject(JSONObject.toJSONString(new HttpBody<>()));
|
||||
jt.put("data",JSONObject.parseObject(string));
|
||||
HttpBody<T> bt=JSONObject.parseObject(jt.toJSONString(),type);
|
||||
body.setData(bt.getData());
|
||||
}
|
||||
body.setSrc(string);
|
||||
return (T) body;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
body = new HttpBody();
|
||||
body.setSrc(string);
|
||||
try {
|
||||
body = new HttpBody<>();
|
||||
body.setData(JSONObject.parseObject(string, type));
|
||||
body.setSrc(string);
|
||||
} catch (Exception e2) {
|
||||
e2.printStackTrace();
|
||||
body = new HttpBody<>();
|
||||
body.setSrc(string);
|
||||
}
|
||||
|
||||
}
|
||||
return (T) body;
|
||||
|
||||
|
||||
@@ -10,17 +10,15 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class QQBotApplication {
|
||||
public static final String version = "QQBot v.1.7.8";
|
||||
public static final String version = "QQBot v.1.7.11.5";
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("version = " + version);
|
||||
SpringApplication.run(QQBotApplication.class, args);
|
||||
NapCatApi.setLog(true);
|
||||
RedisTools.initRedisPoolSub();
|
||||
QQBotManager.getInstance();
|
||||
val log = ConfigTools.load(ConfigTools.CONFIG, ConfigTools.QQ_LOG, Boolean.class);
|
||||
val log = ConfigTools.load(ConfigTools.CONFIG, ConfigTools.QQ_LOG, Boolean.class,true);
|
||||
NapCatApi.setLog(log);
|
||||
//1
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import com.yutou.okhttp.HttpCallback;
|
||||
import com.yutou.qqbot.data.MessageChainBuilder;
|
||||
import com.yutou.qqbot.interfaces.ObjectInterface;
|
||||
import com.yutou.qqbot.utlis.*;
|
||||
import okhttp3.Headers;
|
||||
import retrofit2.Response;
|
||||
|
||||
|
||||
@@ -47,7 +48,7 @@ public class QQBotManager {
|
||||
sendMessage(true, 583819556L, "姬妻酱上线拉~☆Daze~ 当前版本:" + QQBotApplication.version);
|
||||
NapCatApi.getGroupApi().getGroupList().enqueue(new HttpCallback<List<GroupBean>>() {
|
||||
@Override
|
||||
public void onResponse(int code, String status, List<GroupBean> response, String rawResponse) {
|
||||
public void onResponse(Headers headers, int code, String status, List<GroupBean> response, String rawResponse) {
|
||||
for (GroupBean groupBean : response) {
|
||||
QQDatabase.addGroup(groupBean.getGroupId(), groupBean);
|
||||
QQNumberManager.getManager().addNumber(groupBean.getGroupId(), true);
|
||||
@@ -61,7 +62,7 @@ public class QQBotManager {
|
||||
});
|
||||
NapCatApi.getFriendApi().getFriendList().enqueue(new HttpCallback<List<FriendBean>>() {
|
||||
@Override
|
||||
public void onResponse(int code, String status, List<FriendBean> response, String rawResponse) {
|
||||
public void onResponse(Headers headers, int code, String status, List<FriendBean> response, String rawResponse) {
|
||||
for (FriendBean friendBean : response) {
|
||||
QQDatabase.addUser(friendBean.getUserId(), friendBean);
|
||||
QQNumberManager.getManager().addNumber(friendBean.getUserId(), false);
|
||||
@@ -75,7 +76,7 @@ public class QQBotManager {
|
||||
});
|
||||
NapCatApi.getUtilsApi().getLoginInfo().enqueue(new HttpCallback<FriendBean>() {
|
||||
@Override
|
||||
public void onResponse(int code, String status, FriendBean response, String rawResponse) {
|
||||
public void onResponse(Headers headers,int code, String status, FriendBean response, String rawResponse) {
|
||||
QQDatabase.setMe(response);
|
||||
}
|
||||
|
||||
@@ -214,7 +215,7 @@ public class QQBotManager {
|
||||
public void groupBan(long qqGroup, long user, int timer, ObjectInterface objectInterface) {
|
||||
NapCatApi.getGroupApi().groupBan(qqGroup, user, timer).enqueue(new HttpCallback<BaseBean>() {
|
||||
@Override
|
||||
public void onResponse(int code, String status, BaseBean response, String rawResponse) {
|
||||
public void onResponse(Headers headers,int code, String status, BaseBean response, String rawResponse) {
|
||||
if (objectInterface != null) {
|
||||
objectInterface.out("1");
|
||||
}
|
||||
@@ -240,7 +241,7 @@ public class QQBotManager {
|
||||
NapCatApi.getGroupApi().setGroupSpecialTitle(group, user, title, duration).enqueue(new HttpCallback<BaseBean>() {
|
||||
|
||||
@Override
|
||||
public void onResponse(int code, String status, BaseBean response, String rawResponse) {
|
||||
public void onResponse(Headers headers,int code, String status, BaseBean response, String rawResponse) {
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -22,9 +22,7 @@ public class Message {
|
||||
public static Message create(String message, boolean isGTP) {
|
||||
Message msg = new Message();
|
||||
msg.content = message;
|
||||
if (isGTP) {
|
||||
msg.role = "assistant";
|
||||
}
|
||||
msg.role = isGTP ? "assistant" : "user";
|
||||
return msg;
|
||||
}
|
||||
}
|
||||
|
||||
90
src/main/java/com/yutou/qqbot/data/gpt/OpenAiBean.java
Normal file
90
src/main/java/com/yutou/qqbot/data/gpt/OpenAiBean.java
Normal file
@@ -0,0 +1,90 @@
|
||||
package com.yutou.qqbot.data.gpt;
|
||||
|
||||
import com.alibaba.fastjson2.annotation.JSONField;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class OpenAiBean {
|
||||
@JSONField(name = "id")
|
||||
private String id;
|
||||
|
||||
@JSONField(name = "choices")
|
||||
private List<Choice> choices;
|
||||
|
||||
@JSONField(name = "tool_calls")
|
||||
private List<ToolCall> toolCalls;
|
||||
|
||||
@JSONField(name = "usage")
|
||||
private Usage usage;
|
||||
|
||||
@JSONField(name = "created")
|
||||
private long created;
|
||||
|
||||
@JSONField(name = "model")
|
||||
private String model;
|
||||
|
||||
@JSONField(name = "object")
|
||||
private String object;
|
||||
|
||||
@JSONField(name = "system_fingerprint")
|
||||
private String systemFingerprint;
|
||||
|
||||
@Data
|
||||
public static class Choice {
|
||||
@JSONField(name = "index")
|
||||
private int index;
|
||||
|
||||
@JSONField(name = "message")
|
||||
private Message message;
|
||||
|
||||
@JSONField(name = "finish_reason")
|
||||
private String finishReason;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Message {
|
||||
@JSONField(name = "role")
|
||||
private String role;
|
||||
|
||||
@JSONField(name = "content")
|
||||
private String content;
|
||||
|
||||
@JSONField(name = "reasoning_content")
|
||||
private String reasoningContent;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class ToolCall {
|
||||
@JSONField(name = "id")
|
||||
private String id;
|
||||
|
||||
@JSONField(name = "type")
|
||||
private String type;
|
||||
|
||||
@JSONField(name = "function")
|
||||
private Function function;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Function {
|
||||
@JSONField(name = "name")
|
||||
private String name;
|
||||
|
||||
@JSONField(name = "arguments")
|
||||
private String arguments;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Usage {
|
||||
@JSONField(name = "prompt_tokens")
|
||||
private int promptTokens;
|
||||
|
||||
@JSONField(name = "completion_tokens")
|
||||
private int completionTokens;
|
||||
|
||||
@JSONField(name = "total_tokens")
|
||||
private int totalTokens;
|
||||
}
|
||||
}
|
||||
138
src/main/java/com/yutou/qqbot/gpt/AbsGPTManager.java
Normal file
138
src/main/java/com/yutou/qqbot/gpt/AbsGPTManager.java
Normal file
@@ -0,0 +1,138 @@
|
||||
package com.yutou.qqbot.gpt;
|
||||
|
||||
import com.yutou.qqbot.data.baidu.Message;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public abstract class AbsGPTManager {
|
||||
protected static final AtomicInteger MAX_MESSAGE = new AtomicInteger(20);
|
||||
protected final ConcurrentHashMap<String, List<Message>> msgMap= new ConcurrentHashMap<>();
|
||||
// 新增锁映射表
|
||||
protected final ConcurrentHashMap<String, AtomicBoolean> userLocks = new ConcurrentHashMap<>();
|
||||
protected String model ;
|
||||
|
||||
|
||||
/**
|
||||
* 清除与GPT管理器相关的所有缓存或状态信息。
|
||||
*/
|
||||
/**
|
||||
* 这里确实是需要清空所有数据
|
||||
*/
|
||||
public synchronized void clear() { // 添加同步
|
||||
msgMap.clear();
|
||||
for (AtomicBoolean value : userLocks.values()) {
|
||||
value.set(false);
|
||||
}
|
||||
userLocks.forEachValue(1, atomicBoolean -> atomicBoolean.set(false));
|
||||
userLocks.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息到指定用户。
|
||||
*
|
||||
* @param user 接收消息的用户标识符。
|
||||
* @param message 要发送的消息内容。
|
||||
* @return 包含消息发送结果的Message对象。
|
||||
*/
|
||||
public abstract Message sendMessage(String user, String message);
|
||||
|
||||
/**
|
||||
* 将文本转换为图像。
|
||||
*
|
||||
* @param user 用户标识符。
|
||||
* @param text 要转换为图像的文本内容。
|
||||
* @return 包含生成图像的File对象。
|
||||
*/
|
||||
public abstract File textToImage(String user, String text);
|
||||
|
||||
/**
|
||||
* 将图像转换为文本。
|
||||
*
|
||||
* @param user 用户标识符。
|
||||
* @param file 包含要转换为文本的图像文件。
|
||||
* @return 提取的文本内容。
|
||||
*/
|
||||
public abstract String imageToText(String user, File file);
|
||||
|
||||
/**
|
||||
* 获取当前使用的GPT版本信息。
|
||||
*
|
||||
* @return GPT版本字符串。
|
||||
*/
|
||||
public abstract String getGPTVersion();
|
||||
|
||||
/**
|
||||
* 设置最大消息数量。
|
||||
*
|
||||
* @param count 最大消息数量。
|
||||
* @return 设置后的最大消息数量。
|
||||
*/
|
||||
public abstract int setMaxMessageCount(int count);
|
||||
|
||||
public List<Message> getMessageList(String user){
|
||||
List<Message> list = msgMap.computeIfAbsent(user, k -> Collections.synchronizedList(new ArrayList<>()));
|
||||
// 限制历史消息的最大数量
|
||||
synchronized (list) {
|
||||
if (list.size() >= MAX_MESSAGE.get()) {
|
||||
int removeCount = list.size() - MAX_MESSAGE.get() + 1; // 腾出空间给新消息
|
||||
list.subList(0, removeCount).clear();
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
/**
|
||||
* 根据指定的类获取相应的GPT管理器实例。
|
||||
*
|
||||
* @param tClass GPT管理器的具体实现类。
|
||||
* @return GPT管理器实例。
|
||||
*/
|
||||
public static <T extends AbsGPTManager> AbsGPTManager getManager(Class<?> tClass) {
|
||||
if (tClass == BaiduGPTManager.class) {
|
||||
return BaiduGPTManager.getManager();
|
||||
}else if(tClass== SiliconGPTManager.class){
|
||||
return SiliconGPTManager.getInstance();
|
||||
}
|
||||
return new AbsGPTManager() {
|
||||
@Override
|
||||
public void clear() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Message sendMessage(String user, String message) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public File textToImage(String user, String text) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String imageToText(String user, File file) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getGPTVersion() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public int setMaxMessageCount(int count) {
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public AbsGPTManager setModel(String model) {
|
||||
this.model=model;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
205
src/main/java/com/yutou/qqbot/gpt/BaiduGPTManager.java
Normal file
205
src/main/java/com/yutou/qqbot/gpt/BaiduGPTManager.java
Normal file
@@ -0,0 +1,205 @@
|
||||
package com.yutou.qqbot.gpt;
|
||||
|
||||
import com.baidubce.qianfan.Qianfan;
|
||||
import com.baidubce.qianfan.model.chat.ChatResponse;
|
||||
import com.baidubce.qianfan.model.image.Image2TextResponse;
|
||||
import com.baidubce.qianfan.model.image.Text2ImageResponse;
|
||||
import com.yutou.qqbot.data.baidu.Message;
|
||||
import com.yutou.qqbot.utlis.ConfigTools;
|
||||
import com.yutou.qqbot.utlis.Log;
|
||||
import com.yutou.qqbot.utlis.StringUtils;
|
||||
import lombok.val;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class BaiduGPTManager extends AbsGPTManager {
|
||||
|
||||
private static final String AppID = ConfigTools.load(ConfigTools.CONFIG, ConfigTools.BAIDU_GPT_APPID, String.class);
|
||||
private static final String ApiKey = ConfigTools.load(ConfigTools.CONFIG, ConfigTools.BAIDU_GPT_API_KEY, String.class);
|
||||
//ConfigTools.load操作可以确保获取到相关参数,所以无需关心
|
||||
private static final String AccessKey = ConfigTools.load(ConfigTools.CONFIG, ConfigTools.BAIDU_GPT_ACCESS_KEY, String.class);
|
||||
private static final String SecretKey = ConfigTools.load(ConfigTools.CONFIG, ConfigTools.BAIDU_GPT_SECRET_KEY, String.class);
|
||||
private final static String modelFor40 = "ERNIE-4.0-8K";
|
||||
private final static String modelFor35 = "ERNIE-Speed-128K";
|
||||
|
||||
private final Qianfan qianfan;
|
||||
|
||||
private BaiduGPTManager() {
|
||||
qianfan = new Qianfan(AccessKey, SecretKey);
|
||||
String savedVersion = ConfigTools.load(ConfigTools.CONFIG, ConfigTools.BAIDU_GPT_VERSION, String.class);
|
||||
if (StringUtils.isEmpty(savedVersion) || (!"3.5".equals(savedVersion) && !"4.0".equals(savedVersion))) {
|
||||
savedVersion = "3.5";
|
||||
ConfigTools.save(ConfigTools.CONFIG, ConfigTools.BAIDU_GPT_VERSION, savedVersion);
|
||||
}
|
||||
model = "3.5".equals(savedVersion) ? modelFor35 : modelFor40;
|
||||
}
|
||||
|
||||
private static volatile BaiduGPTManager manager;
|
||||
|
||||
public static BaiduGPTManager getManager() {
|
||||
if (manager == null) {
|
||||
synchronized (BaiduGPTManager.class) {
|
||||
if (manager == null) {
|
||||
manager = new BaiduGPTManager();
|
||||
}
|
||||
}
|
||||
}
|
||||
return manager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int setMaxMessageCount(int count) {
|
||||
MAX_MESSAGE.set(count);
|
||||
return count;
|
||||
}
|
||||
|
||||
public synchronized void setModelFor40() {
|
||||
model = modelFor40;
|
||||
ConfigTools.save(ConfigTools.CONFIG, ConfigTools.BAIDU_GPT_VERSION, "4.0");
|
||||
}
|
||||
|
||||
public synchronized void setModelFor35() {
|
||||
model = modelFor35;
|
||||
ConfigTools.save(ConfigTools.CONFIG, ConfigTools.BAIDU_GPT_VERSION, "3.5");
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 这个是官方的示例代码,表示连续对话
|
||||
private static void exampleChat() {
|
||||
Qianfan qianfan = new Qianfan();
|
||||
ChatResponse response = qianfan.chatCompletion()
|
||||
// 设置需要使用的模型,与endpoint同时只能设置一种
|
||||
.model("ERNIE-Bot")
|
||||
// 通过传入历史对话记录来实现多轮对话
|
||||
.addMessage("user", "你好!你叫什么名字?")
|
||||
.addMessage("assistant", "你好!我是文心一言,英文名是ERNIE Bot。")
|
||||
// 传入本轮对话的用户输入
|
||||
.addMessage("user", "刚刚我的问题是什么?")
|
||||
.execute();
|
||||
System.out.println("输出内容:" + response.getResult());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Message sendMessage(String user, String message) {
|
||||
// 获取或创建用户锁
|
||||
AtomicBoolean lock = userLocks.computeIfAbsent(user, k -> new AtomicBoolean(false));
|
||||
// 尝试加锁(如果已被锁定则立即返回提示)
|
||||
if (!lock.compareAndSet(false, true)) {
|
||||
return Message.create("您有请求正在处理中,请稍后再试", true);
|
||||
}
|
||||
try {
|
||||
List<Message> list = getMessageList(user);
|
||||
list.add(Message.create(message));
|
||||
val builder = qianfan.chatCompletion()
|
||||
.model(model);
|
||||
for (Message msg : list) {
|
||||
builder.addMessage(msg.getRole(), msg.getContent());
|
||||
}
|
||||
ChatResponse chatResponse = builder.execute();
|
||||
Message response = Message.create(chatResponse.getResult(), true);
|
||||
synchronized (list) {
|
||||
list.add(response);
|
||||
if (list.size() > MAX_MESSAGE.get()) {
|
||||
int overflow = list.size() - MAX_MESSAGE.get();
|
||||
list.subList(0, overflow).clear();
|
||||
}
|
||||
}
|
||||
// msgMap.put(user, list);
|
||||
return response;
|
||||
} catch (Exception e) {
|
||||
Log.e(e, message);
|
||||
return Message.create("请求失败,请重试", true);
|
||||
} finally {
|
||||
lock.set(false);
|
||||
userLocks.remove(user, lock);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 将文本转换为图像文件
|
||||
* 该方法使用预训练的AI模型将给定的文本转换为图像,并将其保存为文件
|
||||
*
|
||||
* @param user 用户标识符,用于为生成的图像文件命名
|
||||
* @param text 要转换为图像的文本
|
||||
* @return 返回生成的图像文件对象,如果转换过程中发生错误,则返回null
|
||||
*/
|
||||
@Override
|
||||
public File textToImage(String user, String text) {
|
||||
// 使用QianFan的text2Image方法将文本转换为图像数据
|
||||
Text2ImageResponse response = qianfan.text2Image()
|
||||
.prompt(text)
|
||||
.execute();
|
||||
// 获取转换后的图像数据,以Base64编码的图像字符串形式
|
||||
val b64Image = response.getData().get(0).getB64Image();
|
||||
// 将Base64编码的图像数据转换为图像文件
|
||||
// 创建一个临时目录下的图像文件,文件名包含用户标识符和当前时间戳,以确保唯一性
|
||||
val imageFile = new File("tmp" + File.separator + user + "_" + System.currentTimeMillis() + ".png");
|
||||
try (val inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(b64Image))) {
|
||||
// 将解码后的图像数据复制到图像文件中,替换现有文件
|
||||
Files.copy(inputStream, imageFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
return imageFile;
|
||||
} catch (Exception e) {
|
||||
// 如果在图像文件生成过程中发生错误,记录错误信息
|
||||
Log.e(e);
|
||||
}
|
||||
// 如果发生错误,返回null
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将图片转换为文本描述
|
||||
*
|
||||
* @param user 使用该功能的用户标识
|
||||
* @param file 要转换的图片文件
|
||||
* @return 转换后的文本描述,如果转换失败则返回null
|
||||
*/
|
||||
@Override
|
||||
public String imageToText(String user, File file) {
|
||||
// 将file文件转换成base64的代码
|
||||
try {
|
||||
// 读取文件内容并转换为Base64编码
|
||||
val base64 = Base64.getEncoder().encodeToString(Files.readAllBytes(file.toPath()));
|
||||
|
||||
// 调用图像转文本的API
|
||||
Image2TextResponse response = qianfan.image2Text()
|
||||
.image(base64)
|
||||
.prompt("请描述这张图片中的主要内容和细节,以及它们之间的关系\n")
|
||||
.execute();
|
||||
String translationPrompt = "将以下英文内容严格翻译为简体中文,不要解释、不要添加额外内容,保留专业术语和名称(如Star Wars保持英文):\n" + response.getResult();
|
||||
// 获取API返回的结果
|
||||
return sendMessage("bot", translationPrompt).getContent();
|
||||
} catch (Exception e) {
|
||||
// 异常处理:记录错误日志
|
||||
Log.e(e);
|
||||
}
|
||||
// 如果发生异常,返回null
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getGPTVersion() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// BaiduGPTManager.getManager().textToImage("user","画一个猫娘,用二次元动画画风,她是粉色头发,坐在地上");
|
||||
// BaiduGPTManager.getManager().imageToText("user",new File("test.png"));
|
||||
// Message message = BaiduGPTManager.getManager().sendMessage("user", "现在假设小猪等于1,小猴等于2");
|
||||
// System.out.println(message.getContent());
|
||||
// message = BaiduGPTManager.getManager().sendMessage("user", "那么小猪加上小猴等于多少?");
|
||||
// System.out.println(message.getContent());
|
||||
System.out.println(BaiduGPTManager.getManager().sendMessage("user", "分析这个网页链接的页面内容,而非链接本身:https://www.bilibili.com/video/BV1TTf5YrESz/").getContent());
|
||||
}
|
||||
}
|
||||
117
src/main/java/com/yutou/qqbot/gpt/SiliconGPTManager.java
Normal file
117
src/main/java/com/yutou/qqbot/gpt/SiliconGPTManager.java
Normal file
@@ -0,0 +1,117 @@
|
||||
package com.yutou.qqbot.gpt;
|
||||
|
||||
import com.yutou.okhttp.HttpLoggingInterceptor;
|
||||
import com.yutou.qqbot.data.baidu.Message;
|
||||
import com.yutou.qqbot.data.gpt.OpenAiBean;
|
||||
import com.yutou.qqbot.http.GPTApi;
|
||||
import com.yutou.qqbot.http.GPTBuilder;
|
||||
import lombok.val;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
public class SiliconGPTManager extends AbsGPTManager {
|
||||
//生成单例模式
|
||||
private volatile static SiliconGPTManager instance = new SiliconGPTManager();
|
||||
|
||||
private SiliconGPTManager() {
|
||||
setModel("deepseek-ai/DeepSeek-R1-Distill-Qwen-7B");
|
||||
}
|
||||
|
||||
public static SiliconGPTManager getInstance() {
|
||||
if (instance == null) {
|
||||
synchronized (SiliconGPTManager.class) {
|
||||
if (instance == null) {
|
||||
instance = new SiliconGPTManager();
|
||||
}
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized Message sendMessage(String user, String message) {
|
||||
// 获取或创建用户锁
|
||||
AtomicBoolean lock = userLocks.computeIfAbsent(user, k -> new AtomicBoolean(false));
|
||||
try {
|
||||
// 尝试加锁(如果已被锁定则立即返回提示)
|
||||
if (!lock.compareAndSet(false, true)) {
|
||||
return Message.create("您有请求正在处理中,请稍后再试", true);
|
||||
}
|
||||
|
||||
val builder = GPTBuilder.create(model);
|
||||
List<Message> list=getMessageList(user);
|
||||
list.add(Message.create(message));
|
||||
for (Message msg : list) {
|
||||
builder.addMessage(msg.getRole(),msg.getContent());
|
||||
}
|
||||
val response = GPTApi.getApi().completions(builder.build()).execute();
|
||||
|
||||
if (!response.isSuccessful()) {
|
||||
return Message.create("API请求失败", true);
|
||||
}
|
||||
|
||||
val body = response.body();
|
||||
if (body == null || body.getData() == null) {
|
||||
return Message.create("API请求为空", true);
|
||||
}
|
||||
if (body.getRetcode() != 0) {
|
||||
return Message.create(body.getMsg(), true);
|
||||
}
|
||||
val choices = body.getData().getChoices();
|
||||
if (choices == null || choices.isEmpty()) {
|
||||
return Message.create("没有对话信息", true);
|
||||
}
|
||||
|
||||
val choice = choices.get(choices.size() - 1);
|
||||
val bot = Message.create(choice.getMessage().getContent(), true);
|
||||
|
||||
list.add(bot);
|
||||
return bot;
|
||||
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
} finally {
|
||||
lock.set(false);
|
||||
userLocks.remove(user, lock);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public File textToImage(String user, String text) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String imageToText(String user, File file) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getGPTVersion() {
|
||||
return model;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int setMaxMessageCount(int count) {
|
||||
MAX_MESSAGE.set(count);
|
||||
return count;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String model="THUDM/glm-4-9b-chat";
|
||||
val message = AbsGPTManager.getManager(SiliconGPTManager.class)
|
||||
.setModel(model)
|
||||
.sendMessage("user", "宫廷玉液酒的下一句是什么?");
|
||||
System.out.println(message);
|
||||
System.out.println(AbsGPTManager.getManager(SiliconGPTManager.class)
|
||||
.setModel(model)
|
||||
.sendMessage("user", "宫廷玉液酒减去大锤等于多少")
|
||||
);
|
||||
}
|
||||
}
|
||||
26
src/main/java/com/yutou/qqbot/http/GPTApi.java
Normal file
26
src/main/java/com/yutou/qqbot/http/GPTApi.java
Normal file
@@ -0,0 +1,26 @@
|
||||
package com.yutou.qqbot.http;
|
||||
|
||||
import com.yutou.okhttp.HttpLoggingInterceptor;
|
||||
import com.yutou.okhttp.api.BaseApi;
|
||||
import com.yutou.qqbot.utlis.ConfigTools;
|
||||
import lombok.val;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
public class GPTApi extends BaseApi {
|
||||
|
||||
public static void setLog(boolean log) {
|
||||
HttpLoggingInterceptor.setLog(log);
|
||||
}
|
||||
|
||||
public static SiliconGPTApi getApi() {
|
||||
val api = new GPTApi();
|
||||
api.setURL("https://api.siliconflow.cn/v1/");
|
||||
// api.setURL("http://127.0.0.1:8080/");
|
||||
HashMap<String, String> header = new HashMap<>();
|
||||
header.put("Authorization", "Bearer sk-dcmhlbhyitcdnjbjfgflhwimahdmygfrcaopzjjcpgsfzmzo");
|
||||
header.put("Content-Type", "application/json");
|
||||
api.addHeader(header);
|
||||
return api.createApi(SiliconGPTApi.class);
|
||||
}
|
||||
}
|
||||
127
src/main/java/com/yutou/qqbot/http/GPTBuilder.java
Normal file
127
src/main/java/com/yutou/qqbot/http/GPTBuilder.java
Normal file
@@ -0,0 +1,127 @@
|
||||
package com.yutou.qqbot.http;
|
||||
|
||||
|
||||
import com.alibaba.fastjson2.JSON;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.alibaba.fastjson2.annotation.JSONField;
|
||||
import lombok.Data;
|
||||
import lombok.val;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
class Message {
|
||||
@JSONField(name = "role")
|
||||
String role;
|
||||
|
||||
@JSONField(name = "content")
|
||||
String content;
|
||||
|
||||
public Message(String role, String content) {
|
||||
this.role = role;
|
||||
this.content = content;
|
||||
}
|
||||
}
|
||||
|
||||
@Data
|
||||
class GPTRequest {
|
||||
@JSONField(name = "model")
|
||||
String model;
|
||||
|
||||
@JSONField(name = "messages")
|
||||
List<Message> messages = new ArrayList<>();
|
||||
|
||||
@JSONField(name = "stream")
|
||||
boolean stream = false;
|
||||
|
||||
@JSONField(name = "max_tokens")
|
||||
int maxTokens;
|
||||
|
||||
@JSONField(name = "stop")
|
||||
List<String> stop = new ArrayList<>(List.of("null"));
|
||||
|
||||
@JSONField(name = "temperature")
|
||||
float temperature ;
|
||||
|
||||
@JSONField(name = "top_p")
|
||||
float topP ;
|
||||
|
||||
@JSONField(name = "top_k")
|
||||
int topK ;
|
||||
|
||||
@JSONField(name = "frequency_penalty")
|
||||
float frequencyPenalty;
|
||||
}
|
||||
|
||||
public class GPTBuilder {
|
||||
private final GPTRequest request;
|
||||
|
||||
private GPTBuilder(String model) {
|
||||
request = new GPTRequest();
|
||||
request.model = model;
|
||||
}
|
||||
|
||||
public static GPTBuilder create(String model) {
|
||||
return new GPTBuilder(model);
|
||||
}
|
||||
|
||||
public GPTBuilder addMessage(String content,boolean isGPT) {
|
||||
request.messages.add(new Message(isGPT ? "assistant" : "user", content));
|
||||
return this;
|
||||
}
|
||||
|
||||
public GPTBuilder addMessage(String role, String content) {
|
||||
request.messages.add(new Message(role, content));
|
||||
return this;
|
||||
}
|
||||
|
||||
public GPTBuilder setMaxTokens(int maxTokens) {
|
||||
request.maxTokens = maxTokens;
|
||||
return this;
|
||||
}
|
||||
|
||||
public GPTBuilder setStream(boolean stream) {
|
||||
request.stream = stream;
|
||||
return this;
|
||||
}
|
||||
|
||||
public GPTBuilder setTemperature(float temperature) {
|
||||
request.temperature = temperature;
|
||||
return this;
|
||||
}
|
||||
|
||||
public GPTBuilder setTopP(float topP) {
|
||||
request.topP = topP;
|
||||
return this;
|
||||
}
|
||||
|
||||
public GPTBuilder setTopK(int topK) {
|
||||
request.topK = topK;
|
||||
return this;
|
||||
}
|
||||
|
||||
public GPTBuilder setFrequencyPenalty(float frequencyPenalty) {
|
||||
request.frequencyPenalty = frequencyPenalty;
|
||||
return this;
|
||||
}
|
||||
|
||||
// 可以根据需要添加更多配置方法
|
||||
|
||||
public JSONObject build() {
|
||||
val json = JSONObject.parse(JSONObject.toJSONString(request));
|
||||
// 创建一个迭代器来遍历JSON对象的键
|
||||
Iterator<String> keys = json.keySet().iterator();
|
||||
while (keys.hasNext()) {
|
||||
String key = keys.next();
|
||||
Object value = json.get(key);
|
||||
|
||||
// 检查值是否为0或为空字符串
|
||||
if (value == null || value.equals(0) || (value instanceof String && ((String) value).isEmpty())) {
|
||||
keys.remove(); // 移除键值对
|
||||
}
|
||||
}
|
||||
return json;
|
||||
}
|
||||
}
|
||||
17
src/main/java/com/yutou/qqbot/http/SiliconGPTApi.java
Normal file
17
src/main/java/com/yutou/qqbot/http/SiliconGPTApi.java
Normal file
@@ -0,0 +1,17 @@
|
||||
package com.yutou.qqbot.http;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.yutou.napcat.model.MessageBean;
|
||||
import com.yutou.okhttp.HttpBody;
|
||||
import com.yutou.qqbot.data.gpt.OpenAiBean;
|
||||
import retrofit2.Call;
|
||||
import retrofit2.http.Body;
|
||||
import retrofit2.http.POST;
|
||||
|
||||
public interface SiliconGPTApi {
|
||||
@POST("/chat/completions")
|
||||
Call<HttpBody<OpenAiBean>> completions(
|
||||
@Body
|
||||
JSONObject message
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,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){};
|
||||
public void onDownloadStart(){}
|
||||
public boolean onDownloading(double soFarBytes, double totalBytes){return true;}
|
||||
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.alibaba.fastjson2.JSONArray;
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.yutou.napcat.enums.MessageEnum;
|
||||
import com.yutou.napcat.event.MessageEvent;
|
||||
import com.yutou.napcat.handle.MessageHandleBuild;
|
||||
import com.yutou.napcat.handle.OtherHandle;
|
||||
import com.yutou.napcat.handle.Reply;
|
||||
import com.yutou.napcat.http.NapCatApi;
|
||||
@@ -78,7 +79,7 @@ public class BiliVideo extends Model {
|
||||
|
||||
private String onAIVideo(long id) {
|
||||
try {
|
||||
Response<HttpBody<MessageBean>> execute = NapCatApi.getMessageApi().getMessage(id).execute();
|
||||
Response<HttpBody<MessageBean>> execute = NapCatApi.getMessageApi().getMessage(MessageHandleBuild.create().setMessageId(String.valueOf(id)).build()).execute();
|
||||
if(execute.body()==null){
|
||||
return "省流失败";
|
||||
}
|
||||
|
||||
@@ -1,25 +1,27 @@
|
||||
package com.yutou.qqbot.models.Commands;
|
||||
|
||||
import com.yutou.napcat.QQDatabase;
|
||||
import com.yutou.napcat.handle.At;
|
||||
import com.yutou.napcat.handle.BaseHandle;
|
||||
import com.yutou.napcat.handle.Text;
|
||||
import com.yutou.napcat.handle.*;
|
||||
import com.yutou.qqbot.Annotations.UseModel;
|
||||
import com.yutou.qqbot.QQBotManager;
|
||||
import com.yutou.qqbot.data.baidu.ResponseMessage;
|
||||
import com.yutou.qqbot.data.baidu.Message;
|
||||
import com.yutou.qqbot.gpt.AbsGPTManager;
|
||||
import com.yutou.qqbot.gpt.SiliconGPTManager;
|
||||
import com.yutou.qqbot.interfaces.DownloadInterface;
|
||||
import com.yutou.qqbot.models.Model;
|
||||
import com.yutou.qqbot.utlis.BaiduGPTManager;
|
||||
import com.yutou.qqbot.gpt.BaiduGPTManager;
|
||||
import com.yutou.napcat.event.MessageEvent;
|
||||
import com.yutou.qqbot.utlis.ConfigTools;
|
||||
import com.yutou.qqbot.utlis.StringUtils;
|
||||
import com.yutou.qqbot.utlis.HttpTools;
|
||||
import lombok.val;
|
||||
import org.apache.catalina.valves.JsonErrorReportValve;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@UseModel
|
||||
public class BaiduGPT extends Model {
|
||||
private Class<?> gptManager = SiliconGPTManager.class;
|
||||
|
||||
@Override
|
||||
public boolean isUserPublic() {
|
||||
@@ -42,30 +44,29 @@ public class BaiduGPT extends Model {
|
||||
@Override
|
||||
public void onMessage(Long qq, MessageEvent event, boolean isGroup) {
|
||||
super.onMessage(qq, event, isGroup);
|
||||
String version = ConfigTools.load(ConfigTools.CONFIG, ConfigTools.BAIDU_GPT_VERSION, String.class);
|
||||
if (StringUtils.isEmpty(version)) {
|
||||
version = "3.5";
|
||||
BaiduGPTManager.getManager().setModelFor35();
|
||||
}
|
||||
if ("3.5".equals(version)) {
|
||||
BaiduGPTManager.getManager().setModelFor35();
|
||||
} else if ("4.0".equals(version)) {
|
||||
BaiduGPTManager.getManager().setModelFor40();
|
||||
}
|
||||
if (event.getTextMessage().equals(QQGroupCommands.GPT_CLEAR)) {
|
||||
BaiduGPTManager.getManager().clear();
|
||||
AbsGPTManager.getManager(gptManager).clear();
|
||||
QQBotManager.getInstance().sendMessage(event.isUser(), qq, new Text("已经失忆捏"));
|
||||
} else if (event.isAtMe()) {
|
||||
if (event.getTextMessage().contains("省流") || event.getTextMessage().contains("总结")) {
|
||||
return;
|
||||
}
|
||||
if ("GPT切换到4.0".equals(event.getTextMessage())) {
|
||||
if (event.getTextMessage().contains("画画")) {
|
||||
val file = BaiduGPTManager.getManager().textToImage(String.valueOf(qq), event.getTextMessage().replace("@" + QQDatabase.getMe().getUserId(), "").replace("画画", "").trim());
|
||||
if (file == null) {
|
||||
QQBotManager.getInstance().sendMessage(event.isUser(), qq, new Text("画不出"));
|
||||
} else {
|
||||
QQBotManager.getInstance().sendMessage(file, qq, event.getMessageId().toString(), "好嘞");
|
||||
}
|
||||
return;
|
||||
} else if (event.getTextMessage().contains("GPT切换到")) {
|
||||
val text = event.getTextMessage().replace("@" + QQDatabase.getMe().getUserId(), "").replace("GPT切换到", "").trim();
|
||||
List<BaseHandle<?>> list = new ArrayList<>();
|
||||
if (isAdmin()) {
|
||||
list.add(new At(user));
|
||||
list.add(new Text("切换为4.0了"));
|
||||
BaiduGPTManager.getManager().clear();
|
||||
BaiduGPTManager.getManager().setModelFor40();
|
||||
list.add(new Text("切换为" + text));
|
||||
AbsGPTManager.getManager(gptManager).clear();
|
||||
AbsGPTManager.getManager(gptManager).setModel(text);
|
||||
QQBotManager.getInstance().sendMessage(event.isUser(), qq, list);
|
||||
} else {
|
||||
list.add(new At(user));
|
||||
@@ -73,32 +74,62 @@ public class BaiduGPT extends Model {
|
||||
QQBotManager.getInstance().sendMessage(event.isUser(), qq, list);
|
||||
}
|
||||
return;
|
||||
} else if ("GPT切换到3.5".equals(event.getTextMessage())) {
|
||||
}else if(event.getTextMessage().contains("大模型切换到")){
|
||||
List<BaseHandle<?>> list = new ArrayList<>();
|
||||
if (isAdmin()) {
|
||||
list.add(new At(user));
|
||||
list.add(new Text("切换为3.5了"));
|
||||
BaiduGPTManager.getManager().clear();
|
||||
BaiduGPTManager.getManager().setModelFor35();
|
||||
QQBotManager.getInstance().sendMessage(event.isUser(), qq, list);
|
||||
}else {
|
||||
list.add(new At(user));
|
||||
list.add(new Text("你没有权限"));
|
||||
QQBotManager.getInstance().sendMessage(event.isUser(), qq, list);
|
||||
val text = event.getTextMessage().replace("@" + QQDatabase.getMe().getUserId(), "").replace("大模型切换到", "").trim();
|
||||
if(text.contains("baidu")|| text.contains("百度")){
|
||||
gptManager= BaiduGPTManager.class;
|
||||
}else if(text.contains("silicon")||text.contains("硅基")){
|
||||
gptManager= SiliconGPTManager.class;
|
||||
}
|
||||
list.add(new At(user));
|
||||
list.add(new Text("切换为" + gptManager.getSimpleName()));
|
||||
AbsGPTManager.getManager(gptManager).clear();
|
||||
QQBotManager.getInstance().sendMessage(event.isUser(), qq, list);
|
||||
return;
|
||||
}
|
||||
ResponseMessage message = BaiduGPTManager.getManager().sendMessage(
|
||||
if (checkImage()) {
|
||||
parseImage(event, qq);
|
||||
return;
|
||||
|
||||
}
|
||||
Message message = AbsGPTManager.getManager(gptManager).sendMessage(
|
||||
String.valueOf(qq),
|
||||
event.getTextMessage().replace("@" + QQDatabase.getMe().getUserId(), "").trim());
|
||||
String sb = "调用版本:" +
|
||||
BaiduGPTManager.getManager().getGPTVersion() +
|
||||
gptManager.getSimpleName()+
|
||||
"\n" +
|
||||
message.getResult();
|
||||
"使用模型:"+
|
||||
AbsGPTManager.getManager(gptManager).getGPTVersion() +
|
||||
"\n"+
|
||||
message.getContent();
|
||||
QQBotManager.getInstance().sendMessage(event.isUser(), qq, new Text(sb));
|
||||
}
|
||||
}
|
||||
|
||||
private void parseImage(MessageEvent event, Long qq) {
|
||||
Image imageHandle = event.findType(Image.class);
|
||||
val replyHandle = event.findType(Reply.class);
|
||||
if (replyHandle != null && imageHandle == null) {
|
||||
imageHandle = getReply(replyHandle.getData().getId()).findType(Image.class);
|
||||
}
|
||||
if (imageHandle == null) {
|
||||
return;
|
||||
}
|
||||
HttpTools.download(imageHandle.getData().getUrl(), "gpt_parse_image.png", new DownloadInterface() {
|
||||
@Override
|
||||
public void onDownload(File file) {
|
||||
super.onDownload(file);
|
||||
if (file == null) {
|
||||
return;
|
||||
}
|
||||
val text = BaiduGPTManager.getManager().imageToText(String.valueOf(qq), file);
|
||||
QQBotManager.getInstance().sendMessage(event.isUser(), qq, new Reply(event.getMessageId()), new Text(text));
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(ConfigTools.load(ConfigTools.CONFIG, ConfigTools.BAIDU_GPT_VERSION));
|
||||
val messageEvent = new MessageEvent();
|
||||
|
||||
@@ -12,6 +12,7 @@ import com.yutou.qqbot.QQBotManager;
|
||||
import com.yutou.qqbot.interfaces.ObjectInterface;
|
||||
import com.yutou.qqbot.models.Model;
|
||||
import com.yutou.qqbot.utlis.RedisTools;
|
||||
import okhttp3.Headers;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
@@ -103,7 +104,7 @@ public class QQBean extends Model {
|
||||
void releaseAll(long qq, boolean isRelease) {
|
||||
QQBotManager.getInstance().getShutUpList(qq, new HttpCallback<List<GroupUserBean>>() {
|
||||
@Override
|
||||
public void onResponse(int code, String status, List<GroupUserBean> response, String rawResponse) {
|
||||
public void onResponse(Headers headers, int code, String status, List<GroupUserBean> response, String rawResponse) {
|
||||
List<GroupUserBean> shutList = new ArrayList<>();
|
||||
for (GroupUserBean bean : response) {
|
||||
if (bean.getShutUpTimestamp() > 60) {
|
||||
@@ -124,7 +125,7 @@ public class QQBean extends Model {
|
||||
for (GroupUserBean bean : shutList) {
|
||||
NapCatApi.getGroupApi().groupBan(qq, bean.getUserId(), 0).enqueue(new HttpCallback<BaseBean>() {
|
||||
@Override
|
||||
public void onResponse(int code, String status, BaseBean response, String rawResponse) {
|
||||
public void onResponse(Headers headers, int code, String status, BaseBean response, String rawResponse) {
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -2,12 +2,18 @@ package com.yutou.qqbot.models;
|
||||
|
||||
import com.yutou.napcat.event.GroupMessageEvent;
|
||||
import com.yutou.napcat.event.MessageEvent;
|
||||
import com.yutou.napcat.handle.At;
|
||||
import com.yutou.napcat.handle.*;
|
||||
import com.yutou.napcat.http.NapCatApi;
|
||||
import com.yutou.napcat.model.MessageBean;
|
||||
import com.yutou.okhttp.HttpBody;
|
||||
import com.yutou.qqbot.QQNumberManager;
|
||||
import com.yutou.qqbot.interfaces.ModelInterface;
|
||||
import com.yutou.qqbot.utlis.ConfigTools;
|
||||
import com.yutou.qqbot.utlis.Log;
|
||||
import lombok.val;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
@@ -129,6 +135,34 @@ public abstract class Model implements ModelInterface {
|
||||
public boolean isAt() {
|
||||
return msg.contains("@" + ConfigTools.load(ConfigTools.CONFIG, ConfigTools.QQ_NUMBER, String.class));
|
||||
}
|
||||
public boolean checkImage(){
|
||||
val image = event.findType(Image.class);
|
||||
if(image!=null){
|
||||
return true;
|
||||
}
|
||||
val reply = event.findType(Reply.class);
|
||||
if(reply!=null){
|
||||
val replyEvent = getReply(reply.getData().getId());
|
||||
if(replyEvent!=null){
|
||||
return replyEvent.findType(Image.class)!=null;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public MessageEvent getReply(long replyId){
|
||||
HttpBody<MessageBean> body = null;
|
||||
try {
|
||||
body = NapCatApi.getMessageApi().getMessage(MessageHandleBuild.create().setMessageId(String.valueOf(replyId)).build()).execute().body();
|
||||
if (body == null) {
|
||||
return null;
|
||||
}
|
||||
return MessageEvent.parseHandleHttp(body.getSrc());
|
||||
} catch (IOException e) {
|
||||
Log.e(e);
|
||||
}
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
public boolean isAdmin() {
|
||||
return user == 583819556L;
|
||||
|
||||
@@ -7,10 +7,7 @@ import com.alibaba.fastjson2.JSONObject;
|
||||
import com.yutou.napcat.QQDatabase;
|
||||
import com.yutou.napcat.enums.MessageEnum;
|
||||
import com.yutou.napcat.event.GroupMessageEvent;
|
||||
import com.yutou.napcat.handle.At;
|
||||
import com.yutou.napcat.handle.BaseHandle;
|
||||
import com.yutou.napcat.handle.Image;
|
||||
import com.yutou.napcat.handle.Text;
|
||||
import com.yutou.napcat.handle.*;
|
||||
import com.yutou.napcat.http.NapCatApi;
|
||||
import com.yutou.napcat.model.MessageBean;
|
||||
import com.yutou.okhttp.HttpBody;
|
||||
@@ -70,7 +67,9 @@ public class QQSetu extends Model {
|
||||
RedisTools.set(db_print, redisKey, json.toJSONString());
|
||||
JSONObject info = setu.getJSONObject("info");
|
||||
JSONObject score = setu.getJSONObject("score");
|
||||
HttpBody<MessageBean> body = NapCatApi.getMessageApi().getMessage(info.getLong("id")).execute().body();
|
||||
HttpBody<MessageBean> body = NapCatApi.getMessageApi().getMessage(
|
||||
MessageHandleBuild.create().setMessageId(String.valueOf(info.getLong("id"))).build()
|
||||
).execute().body();
|
||||
List<BaseHandle<?>> sendList = new ArrayList<>();
|
||||
if (body == null) {
|
||||
sendList.add(new Text("[图片获取失败]"));
|
||||
|
||||
@@ -3,10 +3,9 @@ package com.yutou.qqbot.utlis;
|
||||
import com.yutou.napcat.QQDatabase;
|
||||
import com.yutou.napcat.model.GroupBean;
|
||||
import com.yutou.qqbot.Annotations.UseModel;
|
||||
import com.yutou.qqbot.QQBotManager;
|
||||
import com.yutou.qqbot.QQNumberManager;
|
||||
import com.yutou.qqbot.gpt.BaiduGPTManager;
|
||||
import com.yutou.qqbot.models.Model;
|
||||
import lombok.val;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
package com.yutou.qqbot.utlis;
|
||||
|
||||
import com.alibaba.fastjson2.JSONObject;
|
||||
import com.yutou.qqbot.data.baidu.Message;
|
||||
import com.yutou.qqbot.data.baidu.ResponseMessage;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class BaiduGPTManager {
|
||||
private static int MAX_MESSAGE = 5;
|
||||
private static BaiduGPTManager manager;
|
||||
private static final String url_3_5 = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions";
|
||||
//4.0
|
||||
private static final String url_4_0 = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro";
|
||||
private static String url = url_3_5;
|
||||
private static final String AppID = ConfigTools.load(ConfigTools.CONFIG, ConfigTools.BAIDU_GPT_APPID, String.class);
|
||||
private static final String ApiKey = ConfigTools.load(ConfigTools.CONFIG, ConfigTools.BAIDU_GPT_API_KEY, String.class);
|
||||
private static final String SecretKey = ConfigTools.load(ConfigTools.CONFIG, ConfigTools.BAIDU_GPT_SECRET_KEY, String.class);
|
||||
private static Map<String, List<Message>> msgMap;
|
||||
|
||||
private BaiduGPTManager() {
|
||||
msgMap = new HashMap<>();
|
||||
}
|
||||
|
||||
public static BaiduGPTManager getManager() {
|
||||
if (manager == null) {
|
||||
manager = new BaiduGPTManager();
|
||||
}
|
||||
return manager;
|
||||
}
|
||||
|
||||
public int setMaxMessageCount(int count) {
|
||||
MAX_MESSAGE = count;
|
||||
return MAX_MESSAGE;
|
||||
}
|
||||
|
||||
public void setModelFor40() {
|
||||
url = url_4_0;
|
||||
ConfigTools.save(ConfigTools.CONFIG, ConfigTools.BAIDU_GPT_VERSION, "4.0");
|
||||
}
|
||||
|
||||
public void setModelFor35() {
|
||||
url = url_3_5;
|
||||
ConfigTools.save(ConfigTools.CONFIG, ConfigTools.BAIDU_GPT_VERSION, "3.5");
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
msgMap.clear();
|
||||
}
|
||||
|
||||
private String getToken() {
|
||||
String _url = String.format("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s"
|
||||
, ApiKey
|
||||
, SecretKey
|
||||
);
|
||||
String get = HttpTools.get(_url);
|
||||
JSONObject response = JSONObject.parseObject(get);
|
||||
return response.getString("access_token");
|
||||
}
|
||||
|
||||
public ResponseMessage sendMessage(String user, String message) {
|
||||
List<Message> messages = msgMap.getOrDefault(user, new ArrayList<>());
|
||||
if (messages.size() > MAX_MESSAGE * 2) {
|
||||
messages.remove(0);
|
||||
messages.remove(1);
|
||||
}
|
||||
messages.add(Message.create(message));
|
||||
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("messages", messages);
|
||||
System.out.println("json = " + json);
|
||||
|
||||
Map<String, String> map = new HashMap<>();
|
||||
map.put("Content-Type", "application/json");
|
||||
map.put("Content-Length", String.valueOf(json.toJSONString().getBytes(StandardCharsets.UTF_8).length));
|
||||
String post = HttpTools.http_post(url + "?access_token=" + getToken()
|
||||
, json.toJSONString().getBytes(StandardCharsets.UTF_8), 0, map);
|
||||
System.out.println("post = " + post);
|
||||
if (StringUtils.isEmpty(post)) {
|
||||
clear();
|
||||
return sendMessage(user, message);
|
||||
}
|
||||
ResponseMessage response = JSONObject.parseObject(post, ResponseMessage.class);
|
||||
messages.add(Message.create(response.getResult(), true));
|
||||
msgMap.put(user, messages);
|
||||
System.out.println("\n\n");
|
||||
return response;
|
||||
}
|
||||
|
||||
public String getGPTVersion() {
|
||||
return (url.equals(url_3_5) ? "3.5" : "4.0");
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
ResponseMessage message = BaiduGPTManager.getManager().sendMessage("test", "现在假设小猪等于1,小猴等于2");
|
||||
System.out.println(message.getResult());
|
||||
message = BaiduGPTManager.getManager().sendMessage("test", "那么小猪加上小猴等于多少?");
|
||||
System.out.println(message.getResult());
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,7 @@ public class ConfigTools {
|
||||
public static final String BAIDU_GPT_VERSION = "baidu.gpt.version";
|
||||
public static final String BAIDU_GPT_APPID = "baidu.gpt.appid";
|
||||
public static final String BAIDU_GPT_API_KEY = "baidu.gpt.apikey";
|
||||
public static final String BAIDU_GPT_ACCESS_KEY = "baidu.gpt.accessKey";
|
||||
public static final String BAIDU_GPT_SECRET_KEY = "baidu.gpt.SecretKey";
|
||||
public static final String TURNIP_PROPHET_SERVER = "turnip.server";
|
||||
public static final String TURNIP_PROPHET_SEND_TMP_GROUP = "turnip.send.tmp.group";
|
||||
@@ -141,4 +142,11 @@ public class ConfigTools {
|
||||
public static String getServerUrl() {
|
||||
return ConfigTools.load(CONFIG, SERVER_URL, String.class);
|
||||
}
|
||||
public static String getUserAgent() {
|
||||
String ua=load(CONFIG,"userAgent",String.class);
|
||||
if(!org.springframework.util.StringUtils.hasText(ua)){
|
||||
ua="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36";
|
||||
}
|
||||
return ua;
|
||||
}
|
||||
}
|
||||
|
||||
134
src/main/java/com/yutou/qqbot/utlis/DateFormatUtils.java
Normal file
134
src/main/java/com/yutou/qqbot/utlis/DateFormatUtils.java
Normal file
@@ -0,0 +1,134 @@
|
||||
package com.yutou.qqbot.utlis;
|
||||
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class DateFormatUtils {
|
||||
private final Map<String, ThreadLocal<SimpleDateFormat>> formats = new ConcurrentHashMap<>();
|
||||
private static volatile DateFormatUtils utils;
|
||||
public static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS";
|
||||
|
||||
private DateFormatUtils() {}
|
||||
|
||||
public static DateFormatUtils getInstance() {
|
||||
if (utils == null) {
|
||||
synchronized (DateFormatUtils.class) {
|
||||
if (utils == null) {
|
||||
utils = new DateFormatUtils();
|
||||
}
|
||||
}
|
||||
}
|
||||
return utils;
|
||||
}
|
||||
|
||||
public String format(Date date, String format) {
|
||||
getFormat(format).applyPattern(format);
|
||||
return getFormat(format).format(date);
|
||||
}
|
||||
|
||||
public String format(long time, String format) {
|
||||
return getFormat(format).format(new Date(time));
|
||||
}
|
||||
|
||||
public String format(long time) {
|
||||
if (time < 1000000000) {
|
||||
time *= 1000;
|
||||
}
|
||||
return getFormat().format(new Date(time));
|
||||
}
|
||||
|
||||
public String format(Date date) {
|
||||
return getFormat().format(date);
|
||||
}
|
||||
|
||||
public String format() {
|
||||
return getFormat().format(new Date());
|
||||
}
|
||||
|
||||
public Date parseTimer(String date) {
|
||||
return parse(date, "HH:mm:ss");
|
||||
}
|
||||
|
||||
public Date parse(String date, String format) {
|
||||
try {
|
||||
if(date.startsWith("1")){
|
||||
return new Date(Long.parseLong(date));
|
||||
}
|
||||
return getFormat(format).parse(date);
|
||||
} catch (ParseException e) {
|
||||
System.err.println("Error parsing date: " + e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public String parseString(String date, String format) {
|
||||
Date time = parse(date, format);
|
||||
return format(time, format);
|
||||
}
|
||||
public String convertSeconds(long totalSeconds) {
|
||||
// 计算总小时数
|
||||
long hours = totalSeconds / 3600;
|
||||
// 剩余的秒数
|
||||
long remainingSecondsAfterHours = totalSeconds % 3600;
|
||||
// 计算分钟数
|
||||
long minutes = remainingSecondsAfterHours / 60;
|
||||
// 最后剩余的秒数
|
||||
long seconds = remainingSecondsAfterHours % 60;
|
||||
return String.format("%d小时%d分%d秒", hours, minutes, seconds);
|
||||
}
|
||||
public String formatMillis(long millis) {
|
||||
Duration duration = Duration.ofMillis(millis);
|
||||
int seconds = (int) (duration.getSeconds() % 60);
|
||||
int minutes = (int) ((duration.getSeconds() / 60) % 60);
|
||||
int hours = (int) (duration.getSeconds() / 3600);
|
||||
|
||||
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
|
||||
}
|
||||
public boolean checkTime(List<String> weeks, String recordDate) {
|
||||
if (!StringUtils.hasText(recordDate)) {
|
||||
recordDate = "00:00:00 - 23:59:59";
|
||||
}
|
||||
String[] parts = recordDate.split(" - ");
|
||||
LocalTime startTime = LocalTime.parse(parts[0], DateTimeFormatter.ofPattern("HH:mm:ss"));
|
||||
LocalTime endTime = LocalTime.parse(parts[1], DateTimeFormatter.ofPattern("HH:mm:ss"));
|
||||
|
||||
|
||||
// 获取当前时间
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
LocalDate currentDate = LocalDate.now();
|
||||
|
||||
|
||||
// 获取当前日期对应的星期几(1-7分别对应周一到周日)
|
||||
int currentWeekDay = currentDate.getDayOfWeek().getValue();
|
||||
|
||||
// 判断当前日期是否在指定的星期列表中
|
||||
boolean isSpecifiedWeekDay;
|
||||
if (weeks == null) {
|
||||
isSpecifiedWeekDay = true;
|
||||
} else {
|
||||
isSpecifiedWeekDay = weeks.contains(String.valueOf(currentWeekDay));
|
||||
}
|
||||
|
||||
// 判断当前时间是否在指定的时间范围内
|
||||
boolean isWithinRange = (currentTime.isAfter(startTime) || currentTime.equals(startTime)) &&
|
||||
(currentTime.isBefore(endTime) || currentTime.equals(endTime));
|
||||
return isWithinRange && isSpecifiedWeekDay;
|
||||
}
|
||||
private SimpleDateFormat getFormat() {
|
||||
return getFormat(DEFAULT_PATTERN);
|
||||
}
|
||||
|
||||
private SimpleDateFormat getFormat(String format) {
|
||||
return formats.computeIfAbsent(format, key -> ThreadLocal.withInitial(() -> new SimpleDateFormat(key))).get();
|
||||
}
|
||||
}
|
||||
135
src/main/java/com/yutou/qqbot/utlis/DynamicLogFile.java
Normal file
135
src/main/java/com/yutou/qqbot/utlis/DynamicLogFile.java
Normal file
@@ -0,0 +1,135 @@
|
||||
package com.yutou.qqbot.utlis;
|
||||
|
||||
import com.google.common.cache.Cache;
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import org.apache.logging.log4j.Level;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.core.Appender;
|
||||
import org.apache.logging.log4j.core.Layout;
|
||||
import org.apache.logging.log4j.core.LoggerContext;
|
||||
import org.apache.logging.log4j.core.appender.ConsoleAppender;
|
||||
import org.apache.logging.log4j.core.appender.RollingFileAppender;
|
||||
import org.apache.logging.log4j.core.appender.rolling.CompositeTriggeringPolicy;
|
||||
import org.apache.logging.log4j.core.appender.rolling.SizeBasedTriggeringPolicy;
|
||||
import org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy;
|
||||
import org.apache.logging.log4j.core.config.Configuration;
|
||||
import org.apache.logging.log4j.core.layout.PatternLayout;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class DynamicLogFile {
|
||||
// 创建一个缓存,用于存储Logger对象,最大容量为1000,过期时间为10分钟
|
||||
static Cache<String, Logger> cache = CacheBuilder.newBuilder()
|
||||
.maximumSize(1000)
|
||||
.expireAfterAccess(10, TimeUnit.MINUTES)
|
||||
.removalListener(it -> {
|
||||
if (it.wasEvicted()) {
|
||||
if (it.getKey() != null) {
|
||||
String loggerName = (String) it.getKey();
|
||||
remove(loggerName, true);
|
||||
}
|
||||
}
|
||||
})
|
||||
.build();
|
||||
|
||||
// 根据loggerName获取Logger对象,如果缓存中不存在,则创建一个新的Logger对象并放入缓存
|
||||
public static Logger getLogger(String loggerName) {
|
||||
try {
|
||||
return cache.get(loggerName, () -> {
|
||||
configureLogger(loggerName);
|
||||
return LogManager.getLogger(loggerName);
|
||||
});
|
||||
} catch (ExecutionException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
// 配置Logger对象
|
||||
private static void configureLogger(String loggerName) {
|
||||
|
||||
LoggerContext context = (LoggerContext) LogManager.getContext(false);
|
||||
Configuration config = context.getConfiguration();
|
||||
|
||||
// 创建日志格式
|
||||
Layout<String> layout = PatternLayout.newBuilder()
|
||||
.withPattern("%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} %-5p [%thread] (%F:%L) : %m%n")
|
||||
.build();
|
||||
|
||||
// 创建时间触发策略
|
||||
TimeBasedTriggeringPolicy timePolicy = TimeBasedTriggeringPolicy.newBuilder()
|
||||
.build();
|
||||
|
||||
// 创建文件大小触发策略
|
||||
SizeBasedTriggeringPolicy sizePolicy = SizeBasedTriggeringPolicy.createPolicy("100 MB");
|
||||
|
||||
// 创建组合触发策略
|
||||
CompositeTriggeringPolicy triggeringPolicy = CompositeTriggeringPolicy.createPolicy(timePolicy, sizePolicy);
|
||||
|
||||
|
||||
// 创建滚动文件Appender
|
||||
RollingFileAppender appender = RollingFileAppender.newBuilder()
|
||||
.setName(loggerName)
|
||||
.withFileName("logs" + "/" + DateFormatUtils.getInstance().format(new Date(), "yyyy-MM-dd") + "/" + loggerName + ".log")
|
||||
.withFilePattern("logs" + "/" + "%d{yyyy-MM-dd}" + "/" + loggerName + "-%i.log.gz")
|
||||
.setLayout(layout)
|
||||
.setImmediateFlush(true)
|
||||
.withAppend(true)
|
||||
.setIgnoreExceptions(false)
|
||||
.withPolicy(triggeringPolicy)
|
||||
.build();
|
||||
|
||||
// 创建控制台Appender
|
||||
Appender consoleAppender = ConsoleAppender.newBuilder()
|
||||
.setName(loggerName + "-console")
|
||||
.setLayout(layout)
|
||||
.setTarget(ConsoleAppender.Target.SYSTEM_OUT)
|
||||
.build();
|
||||
|
||||
appender.start();
|
||||
consoleAppender.start();
|
||||
config.addAppender(appender);
|
||||
config.addAppender(consoleAppender);
|
||||
|
||||
// 获取Logger对象
|
||||
org.apache.logging.log4j.core.Logger coreLogger = context.getLogger(loggerName);
|
||||
if (coreLogger == null) {
|
||||
throw new IllegalStateException("Logger with name " + loggerName + " does not exist.");
|
||||
}
|
||||
|
||||
// 将Appender添加到Logger对象中
|
||||
coreLogger.addAppender(appender);
|
||||
coreLogger.addAppender(consoleAppender);
|
||||
coreLogger.setLevel(Level.ALL);
|
||||
coreLogger.setAdditive(false);
|
||||
|
||||
// 更新Logger对象
|
||||
context.updateLoggers();
|
||||
|
||||
}
|
||||
|
||||
// 移除Logger对象
|
||||
public static void remove(String loggerName) {
|
||||
remove(loggerName, false);
|
||||
}
|
||||
|
||||
// 私有方法,移除Logger对象,isAuto参数用于判断是否是自动移除
|
||||
private static void remove(String loggerName, boolean isAuto) {
|
||||
if (!isAuto) {
|
||||
cache.invalidate(loggerName);
|
||||
}
|
||||
LoggerContext context = (LoggerContext) LogManager.getContext(false);
|
||||
Configuration config = context.getConfiguration();
|
||||
org.apache.logging.log4j.core.Logger coreLogger = context.getLogger(loggerName);
|
||||
Appender appender = config.getAppender(loggerName);
|
||||
if (appender != null) {
|
||||
appender.stop();
|
||||
coreLogger.removeAppender(appender);
|
||||
}
|
||||
config.getAppenders().remove(loggerName);
|
||||
context.updateLoggers();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,33 +1,74 @@
|
||||
package com.yutou.qqbot.utlis;
|
||||
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.apache.logging.log4j.util.StackLocatorUtil;
|
||||
|
||||
|
||||
public class Log {
|
||||
public static void i(String tag, Object log) {
|
||||
i('[' + tag + ']' + log);
|
||||
|
||||
public static void i() {
|
||||
System.out.println();
|
||||
}
|
||||
|
||||
public static void i(Object log) {
|
||||
if (ConfigTools.load(ConfigTools.CONFIG, ConfigTools.SERVICE_LOG, boolean.class, false)) {
|
||||
System.out.printf("[%s]%s%n",
|
||||
AppTools.getToDayNowTimeToString(),
|
||||
log
|
||||
);
|
||||
public static Logger getDynamicLogger(String loggerName) {
|
||||
return DynamicLogFile.getLogger(loggerName);
|
||||
}
|
||||
|
||||
public static void removeDynamicLogger(String loggerName) {
|
||||
DynamicLogFile.remove(loggerName);
|
||||
}
|
||||
|
||||
public static void i(Object... log) {
|
||||
if (!((boolean) ConfigTools.load(ConfigTools.CONFIG, ConfigTools.SERVICE_LOG))) {
|
||||
return;
|
||||
}
|
||||
|
||||
LogManager.getLogger(getStackTrace()).info(buildLog(log));
|
||||
}
|
||||
|
||||
public static void e(String tag, Exception e) {
|
||||
System.err.printf("[%s]%s - %s%n",
|
||||
AppTools.getToDayNowTimeToString(),
|
||||
tag,
|
||||
AppTools.getExceptionString(e)
|
||||
);
|
||||
}
|
||||
|
||||
public static void i(Object tag, Object log) {
|
||||
if (tag instanceof String) {
|
||||
i("[" + tag + "]" + log);
|
||||
} else {
|
||||
i(tag.getClass().getSimpleName(), log);
|
||||
public static void e(Object... log) {
|
||||
if (!ConfigTools.load(ConfigTools.CONFIG, ConfigTools.SERVICE_LOG, Boolean.class)) {
|
||||
return;
|
||||
}
|
||||
LogManager.getLogger(getStackTrace()).error(buildLog(log));
|
||||
}
|
||||
|
||||
public static void e(Throwable e, Object... log) {
|
||||
if (!ConfigTools.load(ConfigTools.CONFIG, ConfigTools.SERVICE_LOG, Boolean.class)) {
|
||||
return;
|
||||
}
|
||||
LogManager.getLogger(getStackTrace()).error(buildLog(log), e);
|
||||
}
|
||||
|
||||
public static void e(Throwable e) {
|
||||
if (!ConfigTools.load(ConfigTools.CONFIG, ConfigTools.SERVICE_LOG, Boolean.class)) {
|
||||
return;
|
||||
}
|
||||
LogManager.getLogger().error(getStackTrace(), e);
|
||||
}
|
||||
|
||||
|
||||
public static void d(Object... log) {
|
||||
if (!ConfigTools.load(ConfigTools.CONFIG, ConfigTools.SERVICE_LOG, Boolean.class)) {
|
||||
return;
|
||||
}
|
||||
LogManager.getLogger().debug(buildLog(log));
|
||||
}
|
||||
|
||||
private static String getStackTrace() {
|
||||
StackTraceElement element = StackLocatorUtil.getStackTraceElement(3);
|
||||
return "(" + element.getFileName() + ":" + element.getLineNumber() + ")";
|
||||
}
|
||||
|
||||
private static String buildLog(Object... log) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Object obj : log) {
|
||||
if (!sb.isEmpty()) {
|
||||
sb.append("|");
|
||||
}
|
||||
sb.append(obj);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
server.port=8002
|
||||
spring.servlet.multipart.max-file-size=10MB
|
||||
spring.servlet.multipart.max-request-size=100MB
|
||||
spring.servlet.multipart.max-request-size=100MB
|
||||
logging.config=classpath:log4j2.xml
|
||||
logging.file.path=./logs
|
||||
logging.level.com.log.controller = trace
|
||||
39
src/main/resources/log4j2.xml
Normal file
39
src/main/resources/log4j2.xml
Normal file
@@ -0,0 +1,39 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="WARN">
|
||||
<Appenders>
|
||||
<!-- 控制台输出 -->
|
||||
<Console name="ConsoleAppender" target="SYSTEM_OUT">
|
||||
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p [%thread] (%F:%L) : %m%n%throwable"/>
|
||||
</Console>
|
||||
|
||||
<!-- 动态路由日志文件 -->
|
||||
<Routing name="RoutingAppender">
|
||||
<Routes pattern="$${date:yyyy-MM-dd}">
|
||||
<Route>
|
||||
<RollingFile name="Rolling-${date:yyyy-MM-dd}" fileName="logs/${date:yyyy-MM-dd}/system.log"
|
||||
filePattern="logs/%d{yyyy-MM-dd}/system-%i.log.gz">
|
||||
<PatternLayout>
|
||||
<pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} %-5p [%thread] (%F:%L) : %m%n%throwable</pattern>
|
||||
</PatternLayout>
|
||||
<Policies>
|
||||
<TimeBasedTriggeringPolicy />
|
||||
<SizeBasedTriggeringPolicy size="1024 MB"/>
|
||||
</Policies>
|
||||
</RollingFile>
|
||||
</Route>
|
||||
</Routes>
|
||||
</Routing>
|
||||
</Appenders>
|
||||
<Loggers>
|
||||
<!-- 屏蔽 org.apache.hc.client5 包下的所有日志 -->
|
||||
<Logger name="org.apache.hc.client5" level="OFF"/>
|
||||
<!-- 根日志记录器 -->
|
||||
<Root level="info">
|
||||
<AppenderRef ref="ConsoleAppender"/>
|
||||
<AppenderRef ref="RoutingAppender"/>
|
||||
</Root>
|
||||
</Loggers>
|
||||
</Configuration>
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user