diff --git a/pom.xml b/pom.xml index 032d797..e1b26d9 100644 --- a/pom.xml +++ b/pom.xml @@ -32,11 +32,6 @@ spring-boot-starter-test test - - net.mamoe - mirai-core-jvm - 2.15.0 - org.jetbrains.kotlinx kotlinx-coroutines-jdk8 @@ -77,19 +72,6 @@ system ${project.basedir}/libs/json-jena-1.0.jar - - com.fix-protocol-version.mirai2 - mirai2 - 1.9.9 - system - ${project.basedir}/libs/fix-protocol-version-1.9.9.mirai2.jar - - - - org.asynchttpclient - async-http-client - 2.12.3 - org.seleniumhq.selenium @@ -163,6 +145,20 @@ 0.1.2 + + + com.squareup.okhttp3 + okhttp + 4.12.0 + + + + + com.squareup.retrofit2 + retrofit + 2.11.0 + + diff --git a/src/main/java/com/yutou/napcat/NapCatQQ.java b/src/main/java/com/yutou/napcat/NapCatQQ.java new file mode 100644 index 0000000..a8b0b17 --- /dev/null +++ b/src/main/java/com/yutou/napcat/NapCatQQ.java @@ -0,0 +1,45 @@ +package com.yutou.napcat; + +import com.alibaba.fastjson2.JSONObject; +import com.yutou.napcat.enums.MessageEnum; +import com.yutou.napcat.event.MessageEvent; +import com.yutou.napcat.handle.*; +import com.yutou.napcat.model.*; +import com.yutou.okhttp.HttpCallback; +import com.yutou.napcat.http.NapCatApi; +import com.yutou.qqbot.QQBotManager; +import lombok.val; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class NapCatQQ { + + + private NapCatQQ() { + + } + + public static void main(String[] args) { + /* List> list = new ArrayList<>(); + list.add(new Text("1", false)); + list.add(new Text("2", false)); + list.add(new Text("3")); + list.add(new Text("4", false)); + list.add(new At(583819556L)); + list.add(new Text("5")); + QQBotManager.getInstance().sendMessage(false, 891655174L, list);*/ + val at = new At(); + System.out.println("at = " + at); + } + /** + * 私聊 + {"self_id":240828363,"user_id":583819556,"time":1714472684,"message_id":376,"real_id":376,"message_type":"private","sender":{"user_id":583819556,"nickname":"魔芋","card":""},"raw_message":"123","font":14,"sub_type":"friend","message":[{"data":{"text":"123"},"type":"text"}],"message_format":"array","post_type":"message"} + */ + + /** + * 群聊 + * {"self_id":240828363,"user_id":583819556,"time":1714472695,"message_id":377,"real_id":377,"message_type":"group","sender":{"user_id":583819556,"nickname":"魔芋","card":"","role":"owner"},"raw_message":"222","font":14,"sub_type":"normal","message":[{"data":{"text":"222"},"type":"text"}],"message_format":"array","post_type":"message","group_id":891655174} + */ +} diff --git a/src/main/java/com/yutou/napcat/QQDatabase.java b/src/main/java/com/yutou/napcat/QQDatabase.java new file mode 100644 index 0000000..46e5e7d --- /dev/null +++ b/src/main/java/com/yutou/napcat/QQDatabase.java @@ -0,0 +1,54 @@ +package com.yutou.napcat; + +import com.yutou.napcat.model.FriendBean; +import com.yutou.napcat.model.GroupBean; +import lombok.Getter; +import lombok.Setter; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class QQDatabase { + private static Map data = new HashMap<>(); + + @Getter + @Setter + private static FriendBean me; + + public static void addUser(Long qq, FriendBean bean) { + data.put(qq, bean); + } + + public static void addGroup(Long qq, GroupBean bean) { + data.put(qq, bean); + } + + public static boolean checkFriend(Long qq) { + if (data.containsKey(qq)) { + return data.get(qq) instanceof FriendBean; + } + return false; + } + + public static boolean checkGroup(Long qq) { + if (data.containsKey(qq)) { + return data.get(qq) instanceof GroupBean; + } + return false; + } + + public static List getGroups() { + List numbers = new ArrayList<>(); + for (Long qq : data.keySet()) { + if (data.get(qq) instanceof GroupBean) { + { + numbers.add((GroupBean) data.get(qq)); + } + } + } + return numbers; + } + +} diff --git a/src/main/java/com/yutou/napcat/enums/MessageEnum.java b/src/main/java/com/yutou/napcat/enums/MessageEnum.java new file mode 100644 index 0000000..9a93a93 --- /dev/null +++ b/src/main/java/com/yutou/napcat/enums/MessageEnum.java @@ -0,0 +1,29 @@ +package com.yutou.napcat.enums; + +public enum MessageEnum { + TEXT("text"), + IMAGE("image"), + AT("at"), + REPLY("reply"), + JSON("json"); + + String type; + + MessageEnum(String type) { + this.type = type; + } + + public String getType() { + return type; + } + + public static MessageEnum of(String type) { + for (MessageEnum messageEnum : MessageEnum.values()) { + if (messageEnum.getType().equals(type)) { + return messageEnum; + } + } + + return null; + } +} diff --git a/src/main/java/com/yutou/napcat/enums/RecordFormatEnum.java b/src/main/java/com/yutou/napcat/enums/RecordFormatEnum.java new file mode 100644 index 0000000..052fb0c --- /dev/null +++ b/src/main/java/com/yutou/napcat/enums/RecordFormatEnum.java @@ -0,0 +1,28 @@ +package com.yutou.napcat.enums; + +public enum RecordFormatEnum { + MP3("mp3"), + AMR("amr"), + WMA("wma"), + M4A("m4a"), + SPX("spx"), + OGG("ogg"), + WAV("wav"), + FLAC("flac"); + + + private final String format; + + RecordFormatEnum(String format) { + this.format = format; + } + + public String getFormat() { + return format; + } + + @Override + public String toString() { + return format; + } +} diff --git a/src/main/java/com/yutou/napcat/event/GroupMessageEvent.java b/src/main/java/com/yutou/napcat/event/GroupMessageEvent.java new file mode 100644 index 0000000..b826563 --- /dev/null +++ b/src/main/java/com/yutou/napcat/event/GroupMessageEvent.java @@ -0,0 +1,13 @@ +package com.yutou.napcat.event; + +import com.yutou.napcat.model.GroupFrom; +import lombok.Data; +import lombok.Getter; +import lombok.Setter; + +@Setter +@Getter +public class GroupMessageEvent extends MessageEvent { + private GroupFrom group; + +} diff --git a/src/main/java/com/yutou/napcat/event/MessageEvent.java b/src/main/java/com/yutou/napcat/event/MessageEvent.java new file mode 100644 index 0000000..b89dfe1 --- /dev/null +++ b/src/main/java/com/yutou/napcat/event/MessageEvent.java @@ -0,0 +1,186 @@ +package com.yutou.napcat.event; + +import com.alibaba.fastjson2.JSONArray; +import com.alibaba.fastjson2.JSONObject; +import com.alibaba.fastjson2.annotation.JSONField; +import com.fasterxml.jackson.databind.deser.impl.BeanPropertyMap; +import com.yutou.napcat.QQDatabase; +import com.yutou.napcat.enums.MessageEnum; +import com.yutou.napcat.handle.*; +import com.yutou.napcat.model.AppShareBean; +import com.yutou.napcat.model.Message; +import com.yutou.napcat.model.SourceFrom; +import lombok.Data; +import lombok.val; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +@Data +public class MessageEvent { + + @JSONField(name = "self_id") + private Long selfId; + + @JSONField(name = "user_id") + private Long userId; + + @JSONField(name = "time") + private Long time; + + @JSONField(name = "message_id") + private Integer messageId; + + @JSONField(name = "real_id") + private Integer realId; + + @JSONField(name = "message_type") + private String messageType; + + @JSONField(name = "sender") + private SourceFrom source; + + @JSONField(name = "raw_message") + private String rawMessage; + + @JSONField(name = "font") + private Integer font; + + @JSONField(name = "sub_type") + private String subType; + + @JSONField(name = "message") + private List> message; + + @JSONField(name = "message_format") + private String messageFormat; + + @JSONField(name = "post_type") + private String postType; + + @JSONField(name = "group_id") + private Long groupId; + + + public static MessageEvent parseHandleHttp(String jsonString) { + return parseHandle(JSONObject.parseObject(jsonString).getJSONObject("data").toString()); + } + + public static MessageEvent parseHandle(String jsonString) { + JSONObject json = JSONObject.parseObject(jsonString); + + JSONArray array = json.getJSONArray("message"); + List> messageList = new ArrayList<>(); + for (Object o : array) { + JSONObject _json = (JSONObject) o; + Type classType = null; + MessageEnum _type = MessageEnum.of(_json.getString("type")); + classType = switch (_type) { + case TEXT -> Text.TextInfo.class; + case IMAGE -> Image.ImageInfo.class; + case AT -> At.AtData.class; + case JSON -> OtherHandle.OtherInfo.class; + case REPLY -> Reply.ReplyInfo.class; + default -> classType; + }; + BaseHandle handle = new BaseHandle<>(_type.getType()); + if (_type == MessageEnum.JSON) { + handle.setData(JSONObject.parseObject(((JSONObject) o).getJSONObject("data").getString("data"), classType)); + } else { + handle.setData(JSONObject.parseObject(((JSONObject) o).getJSONObject("data").toString(), classType)); + } + messageList.add(handle); + } + + + SourceFrom sender = new SourceFrom(); + sender.setUserId(json.getJSONObject("sender").getLong("user_id")); + sender.setNickname(json.getJSONObject("sender").getString("nickname")); + sender.setCard(json.getJSONObject("sender").getString("card")); + + MessageEvent event = new MessageEvent(); + event.setSelfId(json.getLong("self_id")); + event.setUserId(json.getLong("user_id")); + event.setTime(json.getLong("time")); + event.setMessageId(json.getInteger("message_id")); + event.setRealId(json.getInteger("real_id")); + event.setMessageType(json.getString("message_type")); + event.setSource(sender); + event.setRawMessage(json.getString("raw_message")); + event.setFont(json.getInteger("font")); + event.setSubType(json.getString("sub_type")); + event.setMessageFormat(json.getString("message_format")); + event.setPostType(json.getString("post_type")); + event.setGroupId(json.getLong("group_id")); + event.setMessage(messageList); + return event; + } + + public boolean hasType(MessageEnum messageEnum) { + for (BaseHandle handle : message) { + if (MessageEnum.of(handle.getType()) == messageEnum) { + return true; + } + } + return false; + } + + public List findAllType(Class t) { + List tmp = new ArrayList<>(); + try { + T newed = t.getDeclaredConstructor().newInstance(); + for (BaseHandle baseHandle : message) { + if (baseHandle.getType().equals(newed.getType())) { + newed.setData(baseHandle.getData()); + tmp.add(newed); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + return tmp; + } + + public T findType(Class tClass) { + List list = findAllType(tClass); + if (list == null || list.isEmpty()) { + return null; + } + return list.get(0); + } + + + public boolean isAtMe() { + if (!hasType(MessageEnum.AT)) { + return false; + } + List list = findAllType(At.class); + for (At handle : list) { + if (handle.getData().getQq() == QQDatabase.getMe().getUserId()) { + return true; + } + } + return false; + } + + public String getTextMessage() { + val texts = findAllType(Text.class); + StringBuilder sb = new StringBuilder(); + for (Text text : texts) { + sb.append(text); + } + return sb.toString().trim(); + } + + public boolean isUser() { + return "private".equals(messageType); + } + + public boolean isGroup() { + return "group".equals(messageType); + } + + +} diff --git a/src/main/java/com/yutou/napcat/handle/At.java b/src/main/java/com/yutou/napcat/handle/At.java new file mode 100644 index 0000000..866f6fb --- /dev/null +++ b/src/main/java/com/yutou/napcat/handle/At.java @@ -0,0 +1,32 @@ +package com.yutou.napcat.handle; + +import com.yutou.okhttp.BaseBean; +import lombok.Data; + +public class At extends BaseHandle { + public At() { + super("at"); + } + + public At(Long userId) { + super("at"); + data = new AtData(userId); + } + + @Override + public String toString() { + if (data == null) { + return null; + } + return String.format("[CQ:at,qq=%d]", data.qq); + } + + @Data + public class AtData extends BaseBean { + private Long qq; + + public AtData(Long qq) { + this.qq = qq; + } + } +} diff --git a/src/main/java/com/yutou/napcat/handle/BaseHandle.java b/src/main/java/com/yutou/napcat/handle/BaseHandle.java new file mode 100644 index 0000000..7bee617 --- /dev/null +++ b/src/main/java/com/yutou/napcat/handle/BaseHandle.java @@ -0,0 +1,28 @@ +package com.yutou.napcat.handle; + +import com.alibaba.fastjson2.JSONObject; +import com.yutou.napcat.enums.MessageEnum; +import com.yutou.okhttp.BaseBean; +import lombok.Data; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.List; + +@Data +public class BaseHandle extends BaseBean { + protected String type; + protected T data; + protected String src; + + public BaseHandle(String type) { + this.type = type; + } + + + public BaseHandle(String type, Object obj) { + super(); + this.type = type; + this.data= (T) obj; + } +} diff --git a/src/main/java/com/yutou/napcat/handle/Image.java b/src/main/java/com/yutou/napcat/handle/Image.java new file mode 100644 index 0000000..6efb542 --- /dev/null +++ b/src/main/java/com/yutou/napcat/handle/Image.java @@ -0,0 +1,28 @@ +package com.yutou.napcat.handle; + +import com.alibaba.fastjson2.annotation.JSONField; +import lombok.Data; + +public class Image extends BaseHandle { + + public Image() { + super("image"); + } + + public Image(String imageUrl) { + super("image"); + data = new ImageInfo(imageUrl); + } + + @Data + public static class ImageInfo { + String file; + String url; + @JSONField(name = "file_size") + String fileSize; + + public ImageInfo(String file) { + this.file = file; + } + } +} diff --git a/src/main/java/com/yutou/napcat/handle/MessageHandleBuild.java b/src/main/java/com/yutou/napcat/handle/MessageHandleBuild.java new file mode 100644 index 0000000..b10257f --- /dev/null +++ b/src/main/java/com/yutou/napcat/handle/MessageHandleBuild.java @@ -0,0 +1,57 @@ +package com.yutou.napcat.handle; + +import com.alibaba.fastjson2.JSONArray; +import com.alibaba.fastjson2.JSONObject; +import com.yutou.okhttp.BaseBean; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +public class MessageHandleBuild { + private List> msgList = new ArrayList<>(); + private long qq; + private boolean autoEscape; + private boolean isGroup; + + public static MessageHandleBuild create() { + return new MessageHandleBuild(); + } + + private MessageHandleBuild() { + msgList = new ArrayList<>(); + } + + public MessageHandleBuild setQQNumber(long qq) { + this.qq = qq; + return this; + } + + public MessageHandleBuild setAutoEscape(boolean autoEscape) { + this.autoEscape = autoEscape; + return this; + } + + public MessageHandleBuild add(BaseHandle msg) { + msgList.add(msg); + return this; + } + + public MessageHandleBuild setGroup(boolean group) { + isGroup = group; + return this; + } + + public JSONObject build() { + JSONObject json=new JSONObject(); + if(isGroup){ + json.put("group_id", qq); + }else { + json.put("user_id", qq); + } + json.put("auto_escape", autoEscape); + json.put("message", msgList); + System.out.println(json); + return json; + } +} diff --git a/src/main/java/com/yutou/napcat/handle/OtherHandle.java b/src/main/java/com/yutou/napcat/handle/OtherHandle.java new file mode 100644 index 0000000..69cb92e --- /dev/null +++ b/src/main/java/com/yutou/napcat/handle/OtherHandle.java @@ -0,0 +1,20 @@ +package com.yutou.napcat.handle; + +import com.alibaba.fastjson2.JSONObject; +import com.yutou.napcat.model.AppShareBean; +import lombok.Data; + +public class OtherHandle extends BaseHandle{ + + public OtherHandle() { + super("json"); + data= new OtherInfo(); + } + + + @Data + public static class OtherInfo extends AppShareBean{ + + + } +} diff --git a/src/main/java/com/yutou/napcat/handle/QuoteReply.java b/src/main/java/com/yutou/napcat/handle/QuoteReply.java new file mode 100644 index 0000000..cab5cad --- /dev/null +++ b/src/main/java/com/yutou/napcat/handle/QuoteReply.java @@ -0,0 +1,14 @@ +package com.yutou.napcat.handle; + +public class QuoteReply { + private final String messageId; + + public QuoteReply(String messageId) { + this.messageId = messageId; + } + + @Override + public String toString() { + return String.format("[CQ:reply,id=%s]",messageId); + } +} diff --git a/src/main/java/com/yutou/napcat/handle/Record.java b/src/main/java/com/yutou/napcat/handle/Record.java new file mode 100644 index 0000000..9139b73 --- /dev/null +++ b/src/main/java/com/yutou/napcat/handle/Record.java @@ -0,0 +1,38 @@ +package com.yutou.napcat.handle; + +import com.yutou.qqbot.utlis.ConfigTools; +import lombok.Data; + +public class Record extends BaseHandle { + + public Record() { + super("record"); + } + + public Record(String file) { + super("record"); + data = new RecordInfo(file); + } + + public Record(String file, boolean proxy) { + super("record"); + data = new RecordInfo(file); + data.proxy = proxy ? "1" : "0"; + } + + + @Data + public static class RecordInfo { + String file; + int magic; + String url; + String cache; + String proxy; + String timeout; + + public RecordInfo(String file) { + this.file = ConfigTools.getServerUrl()+file; + } + + } +} diff --git a/src/main/java/com/yutou/napcat/handle/Reply.java b/src/main/java/com/yutou/napcat/handle/Reply.java new file mode 100644 index 0000000..76aaedc --- /dev/null +++ b/src/main/java/com/yutou/napcat/handle/Reply.java @@ -0,0 +1,24 @@ +package com.yutou.napcat.handle; + +import lombok.Data; + +public class Reply extends BaseHandle { + + public Reply() { + super("reply"); + } + + public Reply(long id) { + super("reply"); + data = new ReplyInfo(id); + } + + @Data + public static class ReplyInfo { + private long id; + + public ReplyInfo(long id) { + this.id = id; + } + } +} diff --git a/src/main/java/com/yutou/napcat/handle/Text.java b/src/main/java/com/yutou/napcat/handle/Text.java new file mode 100644 index 0000000..b45b814 --- /dev/null +++ b/src/main/java/com/yutou/napcat/handle/Text.java @@ -0,0 +1,53 @@ +package com.yutou.napcat.handle; + +import lombok.Data; + +import java.lang.reflect.Type; + +public class Text extends BaseHandle { + + public Text() { + super("text"); + } + + public Text(String text) { + super("text"); + data = new TextInfo(text + "\n"); + } + + public Text(String text, boolean isNewLine) { + super("text"); + if (isNewLine) { + data = new TextInfo(text + "\n"); + } else { + data = new TextInfo(text); + } + } + + public Text(boolean isNewLine, String... text) { + super("text"); + StringBuilder sb = new StringBuilder(); + for (String s : text) { + sb.append(s); + } + if (isNewLine) { + data = new TextInfo(sb + "\n"); + } else { + data = new TextInfo(sb.toString()); + } + } + + @Override + public String toString() { + return data.text; + } + + @Data + public static class TextInfo { + String text; + + public TextInfo(String text) { + this.text = text; + } + } +} diff --git a/src/main/java/com/yutou/napcat/http/FriendApi.java b/src/main/java/com/yutou/napcat/http/FriendApi.java new file mode 100644 index 0000000..a170698 --- /dev/null +++ b/src/main/java/com/yutou/napcat/http/FriendApi.java @@ -0,0 +1,17 @@ +package com.yutou.napcat.http; + +import com.yutou.napcat.model.FriendBean; +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 java.util.List; + +public interface FriendApi { + @POST("/get_friend_list") + Call>> getFriendList( + ); +} diff --git a/src/main/java/com/yutou/napcat/http/GroupApi.java b/src/main/java/com/yutou/napcat/http/GroupApi.java new file mode 100644 index 0000000..9631841 --- /dev/null +++ b/src/main/java/com/yutou/napcat/http/GroupApi.java @@ -0,0 +1,71 @@ +package com.yutou.napcat.http; + +import com.yutou.napcat.model.FriendBean; +import com.yutou.napcat.model.GroupBean; +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 java.util.List; + +public interface GroupApi { + /** + * 禁言 + * @param group 群号 + * @param user 用户 + * @param duration 禁言时长,单位秒 + * + */ + @FormUrlEncoded + @POST("/set_group_ban") + Call> groupBan( + @Field("group_id") long group, + @Field("user_id") long user, + @Field("duration") long duration + ); + + /** + * 禁言群组全体成员 + * @param group 群号 + */ + @FormUrlEncoded + @POST("/set_group_whole_ban") + Call> groupBanAll( + @Field("group_id") long group + ); + + /** + * 获取群组列表 + */ + @POST("/get_group_list") + Call>> getGroupList( + ); + + /** + * 获取群组信息 + */ + @POST("/get_group_info") + Call> getGroupInfo( + ); + + /** + * 获取群组成员信息 + */ + @POST("/get_group_member_info") + Call> getGroupUserInfo( + ); + + /** + * 获取群组成员列表 + * @param group 群号 + */ + @FormUrlEncoded + @POST("/get_group_member_list") + Call> getGroupUserList( + @Field("group_id") long group + ); +} diff --git a/src/main/java/com/yutou/napcat/http/MessageAPI.java b/src/main/java/com/yutou/napcat/http/MessageAPI.java new file mode 100644 index 0000000..7ee7735 --- /dev/null +++ b/src/main/java/com/yutou/napcat/http/MessageAPI.java @@ -0,0 +1,52 @@ +package com.yutou.napcat.http; + +import com.alibaba.fastjson2.JSONArray; +import com.alibaba.fastjson2.JSONObject; +import com.yutou.napcat.handle.BaseHandle; +import com.yutou.napcat.model.MessageBean; +import com.yutou.napcat.model.SendMessageResponse; +import com.yutou.okhttp.BaseBean; +import com.yutou.okhttp.HttpBody; +import kotlin.jvm.JvmSuppressWildcards; +import retrofit2.Call; +import retrofit2.http.*; + +import java.util.List; + +public interface MessageAPI { + /** + * 发送私聊消息 + * @param message {@link com.yutou.napcat.handle.MessageHandleBuild} + * @return 消息id + */ + @POST("/send_private_msg") + Call> sendPrivateMsg( + @Body + JSONObject message); + /** + * 发送群聊消息 + * @param message 消息内容 + * @return 消息id + */ + @POST("/send_group_msg") + Call> sendGroupMsg( + @Body + JSONObject message + ); + + /** + * 撤回消息 + * @param messageId 消息id + */ + @FormUrlEncoded + @POST("/delete_msg") + Call> delMsg( + @Field("message_id") long messageId + ); + + @FormUrlEncoded + @POST("/get_msg") + Call> getMessage( + @Field("message_id") long messageId + ); +} diff --git a/src/main/java/com/yutou/napcat/http/NapCatApi.java b/src/main/java/com/yutou/napcat/http/NapCatApi.java new file mode 100644 index 0000000..b8b5214 --- /dev/null +++ b/src/main/java/com/yutou/napcat/http/NapCatApi.java @@ -0,0 +1,29 @@ +package com.yutou.napcat.http; + +import com.yutou.okhttp.HttpLoggingInterceptor; +import com.yutou.okhttp.api.BaseApi; +import com.yutou.qqbot.utlis.ConfigTools; + +public class NapCatApi extends BaseApi { + private static final String URL; + static { + URL= ConfigTools.load(ConfigTools.CONFIG,"napcat.url",String.class); + } + + public static void setLog(boolean log){ + HttpLoggingInterceptor.setLog(log); + } + + public static MessageAPI getMessageApi(){ + return new NapCatApi().setURL(URL).createApi(MessageAPI.class); + } + public static UtilsApi getUtilsApi(){ + return new NapCatApi().setURL(URL).createApi(UtilsApi.class); + } + public static GroupApi getGroupApi(){ + return new NapCatApi().setURL(URL).createApi(GroupApi.class); + } + public static FriendApi getFriendApi(){ + return new NapCatApi().setURL(URL).createApi(FriendApi.class); + } +} diff --git a/src/main/java/com/yutou/napcat/http/UtilsApi.java b/src/main/java/com/yutou/napcat/http/UtilsApi.java new file mode 100644 index 0000000..63a0ab7 --- /dev/null +++ b/src/main/java/com/yutou/napcat/http/UtilsApi.java @@ -0,0 +1,80 @@ +package com.yutou.napcat.http; + +import com.yutou.napcat.model.*; +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; + +public interface UtilsApi { + /** + * 获取语音 + * + * @param fileId 收到的语音文件名(消息段的 file 参数),如 0B38145AA44505000B38145AA4450500.silk + * @param format 要转换到的格式,目前支持 mp3、amr、wma、m4a、spx、ogg、wav、flac {@link com.yutou.napcat.enums.RecordFormatEnum} + * @return 转换后的语音文件路径 + */ + @FormUrlEncoded + @POST("/get_record") + Call> getMessageRecord( + @Field("file") String fileId, + @Field("out_format") String format + ); + + /** + * 获取图片 + * + * @param fileId 收到的图片文件名(消息段的 file 参数) + * @return 下载后的图片文件路径 + */ + @FormUrlEncoded + @POST("/get_image") + Call> getMessageImage( + @Field("file") String fileId + ); + + /** + * 检查是否可以发送图片 + */ + @POST("/can_send_image") + Call> checkSendImage( + ); + + /** + * 检查是否可以发送语音 + */ + @POST("/can_send_record") + Call> checkSendRecord( + ); + + /** + * 获取机器人状态 + */ + @POST("/get_status") + Call> checkQQBotStatus( + ); + + /** + * 获取机器人版本信息 + */ + @POST("/get_version_info") + Call> checkQQBotVersion( + ); + + /** + * 清理缓存 + */ + @POST("/clean_cache") + Call> cleanCache( + ); + + /** + * 获取登录信息 + */ + @POST("/get_login_info") + Call> getLoginInfo( + ); + +} diff --git a/src/main/java/com/yutou/napcat/model/AppShareBean.java b/src/main/java/com/yutou/napcat/model/AppShareBean.java new file mode 100644 index 0000000..b6da655 --- /dev/null +++ b/src/main/java/com/yutou/napcat/model/AppShareBean.java @@ -0,0 +1,139 @@ +package com.yutou.napcat.model; + +import com.alibaba.fastjson2.annotation.JSONField; +import com.yutou.okhttp.BaseBean; +import lombok.Data; + +import java.util.Map; + +@Data + +public class AppShareBean extends BaseBean { + + @JSONField(name = "ver") + private String version; + + @JSONField(name = "prompt") + private String prompt; + + @JSONField(name = "config") + private Config config; + + @JSONField(name = "needShareCallBack") + private boolean needShareCallBack; + + @JSONField(name = "app") + private String app; + + @JSONField(name = "view") + private String view; + + @JSONField(name = "meta") + private Meta meta; + + // getters and setters... + + // Inner classes + + @Data + public static class Config { + @JSONField(name = "type") + private String type; + + @JSONField(name = "width") + private int width; + + @JSONField(name = "height") + private int height; + + @JSONField(name = "forward") + private int forward; + + @JSONField(name = "autoSize") + private int autoSize; + + @JSONField(name = "ctime") + private long ctime; + + @JSONField(name = "token") + private String token; + + // getters and setters... + } + + @Data + public static class Meta { + @JSONField(name = "detail_1") + private Detail detail1; + + // If there can be multiple "detail_X" entries, you might need a Map + // @JSONField(name = "detail_X") + // private Map details; + + // getters and setters... + } + + @Data + public static class Detail { + @JSONField(name = "appid") + private String appid; + + @JSONField(name = "appType") + private int appType; + + @JSONField(name = "title") + private String title; + + @JSONField(name = "desc") + private String desc; + + @JSONField(name = "icon") + private String icon; + + @JSONField(name = "preview") + private String preview; + + @JSONField(name = "url") + private String url; + + @JSONField(name = "scene") + private int scene; + + @JSONField(name = "host") + private Host host; + + @JSONField(name = "shareTemplateId") + private String shareTemplateId; + + // Since "shareTemplateData" is an empty object, it can be left as a Map or a specific class + // if you know the structure of the data that might be there + @JSONField(name = "shareTemplateData") + private Map shareTemplateData; + + @JSONField(name = "qqdocurl") + private String qqdocurl; + + @JSONField(name = "showLittleTail") + private String showLittleTail; + + @JSONField(name = "gamePoints") + private String gamePoints; + + @JSONField(name = "gamePointsUrl") + private String gamePointsUrl; + + // getters and setters... + } + + @Data + public static class Host { + @JSONField(name = "uin") + private long uin; + + @JSONField(name = "nick") + private String nick; + + // getters and setters... + } + +} diff --git a/src/main/java/com/yutou/napcat/model/CheckSendImageBean.java b/src/main/java/com/yutou/napcat/model/CheckSendImageBean.java new file mode 100644 index 0000000..fe7823d --- /dev/null +++ b/src/main/java/com/yutou/napcat/model/CheckSendImageBean.java @@ -0,0 +1,12 @@ +package com.yutou.napcat.model; + +import com.alibaba.fastjson2.annotation.JSONField; +import com.yutou.okhttp.BaseBean; +import lombok.Data; + +@Data +public class CheckSendImageBean extends BaseBean { + @JSONField(name = "yes") + private boolean yes; + +} diff --git a/src/main/java/com/yutou/napcat/model/CheckSendRecordBean.java b/src/main/java/com/yutou/napcat/model/CheckSendRecordBean.java new file mode 100644 index 0000000..89b16ef --- /dev/null +++ b/src/main/java/com/yutou/napcat/model/CheckSendRecordBean.java @@ -0,0 +1,12 @@ +package com.yutou.napcat.model; + +import com.alibaba.fastjson2.annotation.JSONField; +import com.yutou.okhttp.BaseBean; +import lombok.Data; + +@Data +public class CheckSendRecordBean extends BaseBean { + @JSONField(name = "yes") + private boolean yes; + +} diff --git a/src/main/java/com/yutou/napcat/model/FriendBean.java b/src/main/java/com/yutou/napcat/model/FriendBean.java new file mode 100644 index 0000000..db53c52 --- /dev/null +++ b/src/main/java/com/yutou/napcat/model/FriendBean.java @@ -0,0 +1,15 @@ +package com.yutou.napcat.model; + +import com.alibaba.fastjson2.annotation.JSONField; +import com.yutou.okhttp.BaseBean; +import lombok.Data; + +@Data +public class FriendBean extends BaseBean { + @JSONField(name = "user_id") + private long userId;//qq号 + @JSONField(name = "nickname") + private String nickName;//昵称 + @JSONField(name = "remark") + private String remark;//备注 +} diff --git a/src/main/java/com/yutou/napcat/model/GroupBean.java b/src/main/java/com/yutou/napcat/model/GroupBean.java new file mode 100644 index 0000000..1d7c9ab --- /dev/null +++ b/src/main/java/com/yutou/napcat/model/GroupBean.java @@ -0,0 +1,18 @@ +package com.yutou.napcat.model; + +import com.alibaba.fastjson2.annotation.JSONField; +import com.yutou.okhttp.BaseBean; +import lombok.Data; + +@Data +public class GroupBean extends BaseBean { + @JSONField(name = "group_id") + private long groupId; + @JSONField(name = "group_name") + private String groupName; + @JSONField(name = "member_count") + private int userCount; + @JSONField(name = "max_member_count") + private int userMaxCount; + +} diff --git a/src/main/java/com/yutou/napcat/model/GroupFrom.java b/src/main/java/com/yutou/napcat/model/GroupFrom.java new file mode 100644 index 0000000..1b3b278 --- /dev/null +++ b/src/main/java/com/yutou/napcat/model/GroupFrom.java @@ -0,0 +1,8 @@ +package com.yutou.napcat.model; + +import lombok.Data; + +@Data +public class GroupFrom { + private long id; +} diff --git a/src/main/java/com/yutou/napcat/model/GroupUserBean.java b/src/main/java/com/yutou/napcat/model/GroupUserBean.java new file mode 100644 index 0000000..9e20250 --- /dev/null +++ b/src/main/java/com/yutou/napcat/model/GroupUserBean.java @@ -0,0 +1,69 @@ +package com.yutou.napcat.model; + +import com.alibaba.fastjson2.annotation.JSONField; +import com.yutou.okhttp.BaseBean; +import lombok.Data; + +@Data +public class GroupUserBean extends BaseBean { + // 群号 + @JSONField(name = "group_id") + private long groupId; + + // QQ号 + @JSONField(name = "user_id") + private long userId; + + // 昵称 + @JSONField(name = "nickname") + private String nickname; + + // 群名片/备注 + @JSONField(name = "card") + private String card; + + // 性别,male 或 female 或 unknown + @JSONField(name = "sex") + private String sex; + + // 年龄 + @JSONField(name = "age") + private int age; + + // 地区 + @JSONField(name = "area") + private String area; + + // 加群时间戳 + @JSONField(name = "join_time") + private int joinTime; + + // 最后发言时间戳 + @JSONField(name = "last_sent_time") + private int lastSentTime; + + // 成员等级 + @JSONField(name = "level") + private String level; + + // 角色,owner 或 admin 或 member + @JSONField(name = "role") + private String role; + + // 是否不良记录成员 + @JSONField(name = "unfriendly") + private boolean unfriendly; + + // 专属头衔 + @JSONField(name = "title") + private String title; + + // 专属头衔过期时间戳 + @JSONField(name = "title_expire_time") + private int titleExpireTime; + + // 是否允许修改群名片 + @JSONField(name = "card_changeable") + private boolean cardChangeable; + +} diff --git a/src/main/java/com/yutou/napcat/model/Message.java b/src/main/java/com/yutou/napcat/model/Message.java new file mode 100644 index 0000000..962a07d --- /dev/null +++ b/src/main/java/com/yutou/napcat/model/Message.java @@ -0,0 +1,23 @@ +package com.yutou.napcat.model; + +import lombok.Data; + +@Data +public class Message { + private String message; + private String srcMessage; + private String id; + public Message(String message, String srcMessage) { + this.message = message; + this.srcMessage = srcMessage; + } + + public String serializeToMiraiCode(){ + return srcMessage; + } + + public String contentToString(){ + return message; + } + +} diff --git a/src/main/java/com/yutou/napcat/model/MessageBean.java b/src/main/java/com/yutou/napcat/model/MessageBean.java new file mode 100644 index 0000000..a2db3b2 --- /dev/null +++ b/src/main/java/com/yutou/napcat/model/MessageBean.java @@ -0,0 +1,50 @@ +package com.yutou.napcat.model; + +import com.alibaba.fastjson2.JSONObject; +import com.alibaba.fastjson2.annotation.JSONField; +import com.yutou.napcat.event.MessageEvent; +import com.yutou.napcat.handle.BaseHandle; +import com.yutou.okhttp.BaseBean; +import lombok.Data; + +import java.lang.reflect.Type; + +/** + * 消息 + * @see 文档 + */ +@Data +public class MessageBean extends BaseBean { + /** + *发送时间 + */ + @JSONField(name = "time") + private long time; + /** + * 消息类型,同 消息事件 + */ + @JSONField(name = "message_type") + private String type; + /** + * 消息 ID + */ + @JSONField(name = "message_id") + private int messageId; + /** + * 消息真实 ID + */ + @JSONField(name = "real_id") + private int realId; + /** + * 发送人信息,同 消息事件 + */ + @JSONField(name = "sender") + private SenderBean sender; + /** + * 消息内容 + */ + @JSONField(name = "message") + private String message; + + +} diff --git a/src/main/java/com/yutou/napcat/model/QQBotStatusBean.java b/src/main/java/com/yutou/napcat/model/QQBotStatusBean.java new file mode 100644 index 0000000..24b0498 --- /dev/null +++ b/src/main/java/com/yutou/napcat/model/QQBotStatusBean.java @@ -0,0 +1,13 @@ +package com.yutou.napcat.model; + +import com.alibaba.fastjson2.annotation.JSONField; +import com.yutou.okhttp.BaseBean; +import lombok.Data; + +@Data +public class QQBotStatusBean extends BaseBean { + @JSONField(name = "online") + private String online;//当前 QQ 在线,null 表示无法查询到在线状态 + @JSONField(name = "good") + private String good;//状态符合预期,意味着各模块正常运行、功能正常,且 QQ 在线 +} diff --git a/src/main/java/com/yutou/napcat/model/QQBotVersionBean.java b/src/main/java/com/yutou/napcat/model/QQBotVersionBean.java new file mode 100644 index 0000000..9ba668e --- /dev/null +++ b/src/main/java/com/yutou/napcat/model/QQBotVersionBean.java @@ -0,0 +1,17 @@ +package com.yutou.napcat.model; + +import com.alibaba.fastjson2.annotation.JSONField; +import lombok.Data; + +@Data +public class QQBotVersionBean { + @JSONField(name = "app_name") + private String appName;//应用标识,如 mirai-native + + @JSONField(name = "app_version") + private String appVersion;//应用版本,如 1.2.3 + + @JSONField(name = "protocol_version") + private String protocolVersion;//OneBot 标准版本,如 v11 + +} diff --git a/src/main/java/com/yutou/napcat/model/SendMessageRequest.java b/src/main/java/com/yutou/napcat/model/SendMessageRequest.java new file mode 100644 index 0000000..feb73c7 --- /dev/null +++ b/src/main/java/com/yutou/napcat/model/SendMessageRequest.java @@ -0,0 +1,21 @@ +package com.yutou.napcat.model; + +import com.alibaba.fastjson2.annotation.JSONField; +import com.google.gson.annotations.SerializedName; +import com.yutou.napcat.handle.BaseHandle; +import com.yutou.okhttp.BaseBean; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.List; +@EqualsAndHashCode(callSuper = true) +@Data +public class SendMessageRequest extends BaseBean { + @JSONField(name = "user_id") + private long userId; + @JSONField + List> message; + @SerializedName("auto_escape") + private boolean notCQCode; + +} diff --git a/src/main/java/com/yutou/napcat/model/SendMessageResponse.java b/src/main/java/com/yutou/napcat/model/SendMessageResponse.java new file mode 100644 index 0000000..c2d3f5d --- /dev/null +++ b/src/main/java/com/yutou/napcat/model/SendMessageResponse.java @@ -0,0 +1,17 @@ +package com.yutou.napcat.model; + +import com.alibaba.fastjson2.annotation.JSONField; +import com.google.gson.annotations.SerializedName; +import com.yutou.okhttp.BaseBean; +import lombok.Data; +import lombok.EqualsAndHashCode; + +@EqualsAndHashCode(callSuper = true) +@Data +public class SendMessageResponse extends BaseBean { + @JSONField( name = "message_id") + private int id; + + private String e; + +} diff --git a/src/main/java/com/yutou/napcat/model/SenderBean.java b/src/main/java/com/yutou/napcat/model/SenderBean.java new file mode 100644 index 0000000..ffc1596 --- /dev/null +++ b/src/main/java/com/yutou/napcat/model/SenderBean.java @@ -0,0 +1,24 @@ +package com.yutou.napcat.model; + +import com.alibaba.fastjson2.annotation.JSONField; +import com.yutou.okhttp.BaseBean; +import lombok.Data; + +/** + * 发送人结构体 + * + */ +@Data +public class SenderBean extends BaseBean { + @JSONField(name = "user_id") + private long userId; + @JSONField(name = "nickname") + private String nickName; + /** + * male 或 female 或 unknown + */ + @JSONField(name = "sex") + private String sex; + @JSONField(name = "age") + private int age; +} diff --git a/src/main/java/com/yutou/napcat/model/SourceFrom.java b/src/main/java/com/yutou/napcat/model/SourceFrom.java new file mode 100644 index 0000000..0dc3553 --- /dev/null +++ b/src/main/java/com/yutou/napcat/model/SourceFrom.java @@ -0,0 +1,17 @@ +package com.yutou.napcat.model; + +import com.alibaba.fastjson2.annotation.JSONField; +import lombok.Data; + +@Data +public class SourceFrom { + @JSONField(name = "user_id") + private long userId; + private String nickname; + private String card; + private String role; + + public Long getFromId() { + return userId; + } +} diff --git a/src/main/java/com/yutou/okhttp/BaseBean.java b/src/main/java/com/yutou/okhttp/BaseBean.java new file mode 100644 index 0000000..ffca9c9 --- /dev/null +++ b/src/main/java/com/yutou/okhttp/BaseBean.java @@ -0,0 +1,6 @@ +package com.yutou.okhttp; + +import java.io.Serializable; + +public class BaseBean implements Serializable { +} diff --git a/src/main/java/com/yutou/okhttp/GetRequestParams.java b/src/main/java/com/yutou/okhttp/GetRequestParams.java new file mode 100644 index 0000000..4008e27 --- /dev/null +++ b/src/main/java/com/yutou/okhttp/GetRequestParams.java @@ -0,0 +1,25 @@ +package com.yutou.okhttp; + + +import okhttp3.HttpUrl; +import okhttp3.Request; + +import java.util.HashMap; + +public class GetRequestParams implements IRequestParam { + /** + * 构建Request + * + * @param request + * @return + */ + @Override + public Request getRequest(HashMap map, Request request) { + //添加公共参数 + 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(); + } +} \ No newline at end of file diff --git a/src/main/java/com/yutou/okhttp/HttpBody.java b/src/main/java/com/yutou/okhttp/HttpBody.java new file mode 100644 index 0000000..7d8588e --- /dev/null +++ b/src/main/java/com/yutou/okhttp/HttpBody.java @@ -0,0 +1,14 @@ +package com.yutou.okhttp; + +import lombok.Data; + +@Data +public class HttpBody { + private String msg; + private String status; + private int code; + private int retcode; + private T data; + private String src; + +} \ No newline at end of file diff --git a/src/main/java/com/yutou/okhttp/HttpCallback.java b/src/main/java/com/yutou/okhttp/HttpCallback.java new file mode 100644 index 0000000..577bf1c --- /dev/null +++ b/src/main/java/com/yutou/okhttp/HttpCallback.java @@ -0,0 +1,31 @@ +package com.yutou.okhttp; + +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; + +public abstract class HttpCallback implements Callback> { + + public abstract void onResponse(int code, String status, T response, String rawResponse); + + public abstract void onFailure(Throwable throwable); + + @Override + public void onResponse(Call> call, Response> response) { + if (response.body() != null) { + onResponse( + response.body().getRetcode(), + response.body().getStatus(), + response.body().getData(), + response.body().getSrc() + ); + } else { + onFailure(new NullPointerException("response body is null")); + } + } + + @Override + public void onFailure(Call> call, Throwable throwable) { + onFailure(throwable); + } +} diff --git a/src/main/java/com/yutou/okhttp/HttpLoggingInterceptor.java b/src/main/java/com/yutou/okhttp/HttpLoggingInterceptor.java new file mode 100644 index 0000000..2284923 --- /dev/null +++ b/src/main/java/com/yutou/okhttp/HttpLoggingInterceptor.java @@ -0,0 +1,221 @@ +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 okhttp3.internal.http.HttpHeaders; +import okio.Buffer; +import okio.BufferedSource; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class HttpLoggingInterceptor implements Interceptor { + private static final String TAG = "HttpLogging"; + + private static final Charset UTF8 = Charset.forName("UTF-8"); + + private volatile Level printLevel = Level.NONE; + private java.util.logging.Level colorLevel; + private Logger logger; + + private static boolean prLog; + + public static void setLog(boolean log) { + prLog = log; + } + + public enum Level { + NONE, //不打印log + BASIC, //只打印 请求首行 和 响应首行 + HEADERS, //打印请求和响应的所有 Header + BODY //所有数据全部打印 + } + + public HttpLoggingInterceptor(String tag) { + logger = Logger.getLogger(tag); + colorLevel = java.util.logging.Level.INFO; + } + + public void setPrintLevel(Level level) { + if (printLevel == null) + throw new NullPointerException("printLevel == null. Use Level.NONE instead."); + printLevel = level; + } + + public void setColorLevel(java.util.logging.Level level) { + colorLevel = level; + } + + private void log(String message) { + //logger.log(colorLevel, message); + if (prLog) { + Log.i(TAG, message); + } + //Log.e(TAG,message); + } + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + if (request.body().contentLength() == 0) { + request = chain.call().request(); + } + if (printLevel == Level.NONE) { + return chain.proceed(request); + } + + //请求日志拦截 + logForRequest(request, chain.connection()); + + //执行请求,计算请求时间 + long startNs = System.nanoTime(); + Response response; + try { + response = chain.proceed(request); + } catch (Exception e) { + log("<-- HTTP FAILED: " + e); + throw e; + } + long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); + + //响应日志拦截 + return logForResponse(response, tookMs); + } + + private void logForRequest(Request request, Connection connection) throws IOException { + boolean logBody = (printLevel == Level.BODY); + boolean logHeaders = (printLevel == Level.BODY || printLevel == Level.HEADERS); + RequestBody requestBody = request.body(); + boolean hasRequestBody = requestBody != null; + Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1; + + try { + String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol; + log(requestStartMessage); + + 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()); + } + if (requestBody.contentLength() != -1) { + log("\tContent-Length: " + requestBody.contentLength()); + } + } + 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)); + } + } + + log(" "); + if (logBody && hasRequestBody) { + if (isPlaintext(requestBody.contentType())) { + bodyToString(request); + } else { + log("\tbody: maybe [binary body], omitted!"); + } + } + } + } catch (Exception e) { + logger.log(java.util.logging.Level.WARNING, e.getMessage(), e); + } finally { + log("--> END " + request.method()); + } + } + + private Response logForResponse(Response response, long tookMs) { + Response.Builder builder = response.newBuilder(); + Response clone = builder.build(); + ResponseBody responseBody = clone.body(); + boolean logBody = (printLevel == Level.BODY); + boolean logHeaders = (printLevel == Level.BODY || printLevel == Level.HEADERS); + + try { + 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++) { + log("\t" + headers.name(i) + ": " + headers.value(i)); + } + log(" "); + if (logBody && HttpHeaders.hasBody(clone)) { + 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)); + log("\tbody:" + body); + responseBody = ResponseBody.create(responseBody.contentType(), bytes); + return response.newBuilder().body(responseBody).build(); + } else { + log("\tbody: maybe [binary body], omitted!"); + } + } + } + } catch (Exception e) { + logger.log(java.util.logging.Level.WARNING, e.getMessage(), e); + } finally { + log("<-- END HTTP"); + } + return response; + } + + private static Charset getCharset(MediaType contentType) { + Charset charset = contentType != null ? contentType.charset(UTF8) : UTF8; + if (charset == null) charset = UTF8; + return charset; + } + + /** + * Returns true if the body in question probably contains human readable text. Uses a small sample + * of code points to detect unicode control characters commonly used in binary file signatures. + */ + private static boolean isPlaintext(MediaType mediaType) { + if (mediaType == null) return false; + if (mediaType.type() != null && mediaType.type().equals("text")) { + return true; + } + String subtype = mediaType.subtype(); + if (subtype != null) { + subtype = subtype.toLowerCase(); + if (subtype.contains("x-www-form-urlencoded") || subtype.contains("json") || subtype.contains("xml") || subtype.contains("html")) // + return true; + } + return false; + } + + private void bodyToString(Request request) { + try { + Request copy = request.newBuilder().build(); + RequestBody body = copy.body(); + if (body == null) return; + Buffer buffer = new Buffer(); + body.writeTo(buffer); + Charset charset = getCharset(body.contentType()); + log("\tbody:" + buffer.readString(charset)); + } catch (Exception e) { + logger.log(java.util.logging.Level.WARNING, e.getMessage(), e); + } + } +} diff --git a/src/main/java/com/yutou/okhttp/IRequestParam.java b/src/main/java/com/yutou/okhttp/IRequestParam.java new file mode 100644 index 0000000..42ec4cc --- /dev/null +++ b/src/main/java/com/yutou/okhttp/IRequestParam.java @@ -0,0 +1,9 @@ +package com.yutou.okhttp; + +import okhttp3.Request; + +import java.util.HashMap; + +public interface IRequestParam { + Request getRequest(HashMap map, Request request); +} \ No newline at end of file diff --git a/src/main/java/com/yutou/okhttp/ParamsContext.java b/src/main/java/com/yutou/okhttp/ParamsContext.java new file mode 100644 index 0000000..ca43ba4 --- /dev/null +++ b/src/main/java/com/yutou/okhttp/ParamsContext.java @@ -0,0 +1,31 @@ +package com.yutou.okhttp; + +import okhttp3.Request; + +import java.util.HashMap; + +public class ParamsContext { + private IRequestParam iRequestParam; + private Request request; + private HashMap map; + + public ParamsContext(HashMap map,Request request) { + if(map==null){ + map=new HashMap<>(); + } + this.map=map; + this.request = request; + } + + public Request getInRequest() { + switch (request.method()) { + case "GET": + iRequestParam = new GetRequestParams(); + break; + case "POST": + iRequestParam = new PostRequestParams(); + break; + } + return iRequestParam.getRequest(map,request); + } +} \ No newline at end of file diff --git a/src/main/java/com/yutou/okhttp/PostRequestParams.java b/src/main/java/com/yutou/okhttp/PostRequestParams.java new file mode 100644 index 0000000..8cf9aca --- /dev/null +++ b/src/main/java/com/yutou/okhttp/PostRequestParams.java @@ -0,0 +1,68 @@ +package com.yutou.okhttp; + + +import com.alibaba.fastjson2.JSONObject; + +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 map, Request request) { + 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)); + } + for (String key : map.keySet()) { + bodyBuilder.addEncoded(key, String.valueOf(map.get(key))); + } + formBody = bodyBuilder.build(); + request = request.newBuilder().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()) + .post(requestBody).build(); + } + return request; + } + + public static String toUrlParams(JSONObject json) { + StringBuilder string = new StringBuilder(); + Set keys = json.keySet(); + for (String key : keys) { + try { + string.append("&").append(key).append("=").append(URLEncoder.encode(json.getString(key), "UTF-8")); + } catch (Exception e) { + e.printStackTrace(); + try { + string.append("&").append(URLEncoder.encode(key,"UTF-8")).append("="); + // string += "&" + key + "="; + } catch (Exception e1) { + string.append("&").append(key).append("="); + } + } + } + + string = new StringBuilder(string.substring(1, string.length()).replaceAll(" ", "")); + return string.toString(); + } + + public static String toUrlParams(Map map) { + if(map.isEmpty()){ + return ""; + } + StringBuilder builder = new StringBuilder(); + for (String key : map.keySet()) { + builder.append(key).append("=").append(map.get(key)).append("&"); + } + return builder.substring(0, builder.length() - 1); + } +} \ No newline at end of file diff --git a/src/main/java/com/yutou/okhttp/api/BaseApi.java b/src/main/java/com/yutou/okhttp/api/BaseApi.java new file mode 100644 index 0000000..c45ec46 --- /dev/null +++ b/src/main/java/com/yutou/okhttp/api/BaseApi.java @@ -0,0 +1,98 @@ +package com.yutou.okhttp.api; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.internal.bind.DateTypeAdapter; +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 retrofit2.CallAdapter; +import retrofit2.Converter; +import retrofit2.Retrofit; + +import java.io.IOException; +import java.util.Date; +import java.util.HashMap; +import java.util.logging.Level; + +public class BaseApi { + private String URL; + private HashMap params; + + public BaseApi setURL(String URL) { + this.URL = URL; + return this; + } + + public BaseApi setParams(HashMap params) { + this.params = params; + return this; + } + + /** + * 创建一个接口方法 + * + * @param okHttpClient okhttp客户端 + * @param converterFactory 处理工厂类 + * @param callAdapterFactory 请求适配器工厂 + * @param baseUrl 基础地质 + * @param service 接口 + * @param 接口泛型 + * @return 接口 + */ + public T create(OkHttpClient okHttpClient, Converter.Factory converterFactory, CallAdapter.Factory callAdapterFactory, String baseUrl, Class service) { + Retrofit.Builder builder = new Retrofit.Builder() + //基础url + .baseUrl(baseUrl) + //客户端OKHttp + .client(okHttpClient); + //添加转换工厂 + if (null != converterFactory) { + builder.addConverterFactory(converterFactory); + } + //添加请求工厂 + if (null != callAdapterFactory) { + builder.addCallAdapterFactory(callAdapterFactory); + } + //创建retrofit对象 + Retrofit retrofit = builder.build(); + + //返回创建的api + return retrofit.create(service); + } + + public T createApi(Class apiClass) { + Gson gson = new GsonBuilder() + .registerTypeAdapter(Date.class, new DateTypeAdapter()) + .create(); + HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("http"); + loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY); + OkHttpClient.Builder builder = new OkHttpClient() + .newBuilder() + + .addInterceptor(initQuery()) + .addInterceptor(loggingInterceptor); + return create(builder.build(), + JsonConverterFactory.create(gson), + JsonCallAdapter.create(), + 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); + } + }; + return addQueryParameterInterceptor; + } +} diff --git a/src/main/java/com/yutou/okhttp/converter/JsonCallAdapter.java b/src/main/java/com/yutou/okhttp/converter/JsonCallAdapter.java new file mode 100644 index 0000000..8fe0ff9 --- /dev/null +++ b/src/main/java/com/yutou/okhttp/converter/JsonCallAdapter.java @@ -0,0 +1,19 @@ +package com.yutou.okhttp.converter; + +import org.jetbrains.annotations.Nullable; +import retrofit2.CallAdapter; +import retrofit2.Retrofit; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +public class JsonCallAdapter extends CallAdapter.Factory{ + public static JsonCallAdapter create(){ + return new JsonCallAdapter(); + } + @Nullable + @Override + public CallAdapter get(Type type, Annotation[] annotations, Retrofit retrofit) { + return null; + } +} \ No newline at end of file diff --git a/src/main/java/com/yutou/okhttp/converter/JsonConverterFactory.java b/src/main/java/com/yutou/okhttp/converter/JsonConverterFactory.java new file mode 100644 index 0000000..f771cb8 --- /dev/null +++ b/src/main/java/com/yutou/okhttp/converter/JsonConverterFactory.java @@ -0,0 +1,41 @@ +package com.yutou.okhttp.converter; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapter; +import com.google.gson.reflect.TypeToken; +import retrofit2.Converter; + +import okhttp3.RequestBody; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.Nullable; +import retrofit2.Retrofit; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +public class JsonConverterFactory extends Converter.Factory { + Gson gson; + public static JsonConverterFactory create(Gson gson) { + return new JsonConverterFactory(gson); + } + + private JsonConverterFactory(Gson gson) { + this.gson = gson; + } + + @Nullable + @Override + public Converter requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { + // return super.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit); + TypeAdapter adapter = gson.getAdapter(TypeToken.get(type)); + return new JsonRequestBodyConverter<>(gson,adapter); + } + + @Nullable + @Override + public Converter responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { + // return super.responseBodyConverter(type, annotations, retrofit); + TypeAdapter adapter = gson.getAdapter(TypeToken.get(type)); + return new JsonResponseBodyConverter<>(gson,adapter,type); + } +} \ No newline at end of file diff --git a/src/main/java/com/yutou/okhttp/converter/JsonRequestBodyConverter.java b/src/main/java/com/yutou/okhttp/converter/JsonRequestBodyConverter.java new file mode 100644 index 0000000..1a4267c --- /dev/null +++ b/src/main/java/com/yutou/okhttp/converter/JsonRequestBodyConverter.java @@ -0,0 +1,37 @@ +package com.yutou.okhttp.converter; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonWriter; +import okhttp3.MediaType; +import okhttp3.RequestBody; +import okio.Buffer; +import org.jetbrains.annotations.Nullable; +import retrofit2.Converter; + +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +public class JsonRequestBodyConverter implements Converter { + Gson gson; + TypeAdapter adapter; + public JsonRequestBodyConverter(Gson gson, TypeAdapter adapter) { + this.gson=gson; + this.adapter=adapter; + } + + @Nullable + @Override + public RequestBody convert(T value) throws IOException { + Buffer buffer = new Buffer(); + Writer writer = new OutputStreamWriter(buffer.outputStream(), StandardCharsets.UTF_8); + JsonWriter jsonWriter = gson.newJsonWriter(writer); + adapter.write(jsonWriter, value); + jsonWriter.close(); + byte[] bytes = buffer.readByteArray(); + return RequestBody.create(MediaType.parse("application/json; charset=UTF-8"),bytes ); + } +} \ No newline at end of file diff --git a/src/main/java/com/yutou/okhttp/converter/JsonResponseBodyConverter.java b/src/main/java/com/yutou/okhttp/converter/JsonResponseBodyConverter.java new file mode 100644 index 0000000..e8c9eac --- /dev/null +++ b/src/main/java/com/yutou/okhttp/converter/JsonResponseBodyConverter.java @@ -0,0 +1,44 @@ +package com.yutou.okhttp.converter; + +import com.alibaba.fastjson2.JSONObject; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapter; +import com.yutou.okhttp.HttpBody; +import okhttp3.ResponseBody; +import org.jetbrains.annotations.Nullable; +import retrofit2.Converter; + +import java.io.IOException; +import java.lang.reflect.Type; + +public class JsonResponseBodyConverter implements Converter { + Gson gson; + TypeAdapter adapter; + Type type; + + public JsonResponseBodyConverter(Gson gson, TypeAdapter adapter, Type type) { + this.gson = gson; + this.adapter = adapter; + this.type = type; + } + + @Nullable + @Override + public T convert(ResponseBody responseBody) throws IOException { + String string = new String(responseBody.bytes()); + responseBody.close(); + HttpBody body; + try { + body = JSONObject.parseObject(string, type); + body.setSrc(string); + return (T) body; + } catch (Exception e) { + e.printStackTrace(); + body = new HttpBody(); + body.setSrc(string); + } + return (T) body; + + } +} \ No newline at end of file diff --git a/src/main/java/com/yutou/qqbot/Controllers/AppController.java b/src/main/java/com/yutou/qqbot/Controllers/AppController.java index b487ffd..8de5df2 100644 --- a/src/main/java/com/yutou/qqbot/Controllers/AppController.java +++ b/src/main/java/com/yutou/qqbot/Controllers/AppController.java @@ -1,12 +1,16 @@ package com.yutou.qqbot.Controllers; import com.alibaba.fastjson2.JSONObject; +import com.yutou.napcat.QQDatabase; +import com.yutou.napcat.handle.BaseHandle; +import com.yutou.napcat.handle.Image; +import com.yutou.napcat.handle.Text; +import com.yutou.napcat.model.SendMessageResponse; import com.yutou.qqbot.QQBotManager; import com.yutou.qqbot.utlis.AppTools; import com.yutou.qqbot.utlis.HttpTools; import com.yutou.qqbot.utlis.RedisTools; import com.yutou.qqbot.utlis.StringUtils; -import net.mamoe.mirai.message.MessageReceipt; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; @@ -64,44 +68,46 @@ public class AppController { @RequestMapping("/qq/send.do") public String sendQQ(@RequestBody JSONObject json) { File image = null; - MessageReceipt ret; - if(json.getString("message").isEmpty()){ + if (json.getString("message").isEmpty()) { return "not message"; } - if (json.containsKey("image")) { - image = HttpTools.syncDownload(json.getString("image"), System.currentTimeMillis() + ".png",true); - } - ret = QQBotManager.getInstance().sendMessage(image, json.getLong("qq"), json.getString("message")); - return ret==null?"message send fail":"message send success"; + SendMessageResponse sent = QQBotManager.getInstance().sendMessage(QQDatabase.checkFriend(json.getLong("qq")), + json.getLong("qq"), + new Text(json.getString("message")), + new Image(json.getString("image")) + ); + return sent == null ? "0" : sent.getId() + ""; } @ResponseBody @RequestMapping("/qq/file.do") public String sendFile(@RequestParam("image") MultipartFile file) throws Exception { - String path=AppTools.createFile("tmp",file,System.currentTimeMillis()+".png"); - if(StringUtils.isEmpty(path)){ + String path = AppTools.createFile("tmp", file, System.currentTimeMillis() + ".png"); + if (StringUtils.isEmpty(path)) { return "not file"; } - File _file=new File(path); - QQBotManager.getInstance().sendMessage(_file,583819556L,"time = "+AppTools.getToDayNowTimeToString()); + File _file = new File(path); + QQBotManager.getInstance().sendMessage(_file, 583819556L, "time = " + AppTools.getToDayNowTimeToString()); return "ok"; } + @RequestMapping("/test.do") @ResponseBody - public String test(HttpServletResponse response){ + public String test(HttpServletResponse response) { System.out.println("NAS自动关机"); /* try { response.sendRedirect("http://192.168.31.88:9999/live/index.m3u8"); } catch (IOException e) { e.printStackTrace(); }*/ - // return HttpTools.http_get("http://192.168.31.88:9999/live/index.m3u8",null); + // return HttpTools.http_get("http://192.168.31.88:9999/live/index.m3u8",null); return "1"; } + @RequestMapping("*.ts") - public void test2(HttpServletResponse response, HttpServletRequest request){ + public void test2(HttpServletResponse response, HttpServletRequest request) { try { - response.sendRedirect("http://192.168.31.88:9999/live"+request.getRequestURI()); + response.sendRedirect("http://192.168.31.88:9999/live" + request.getRequestURI()); } catch (IOException e) { e.printStackTrace(); } diff --git a/src/main/java/com/yutou/qqbot/Listeners/QQMessageListener.java b/src/main/java/com/yutou/qqbot/Listeners/QQMessageListener.java index 93f4048..202740f 100644 --- a/src/main/java/com/yutou/qqbot/Listeners/QQMessageListener.java +++ b/src/main/java/com/yutou/qqbot/Listeners/QQMessageListener.java @@ -4,25 +4,19 @@ import com.yutou.qqbot.MessageEvent.AdminMessage; import com.yutou.qqbot.QQNumberManager; import com.yutou.qqbot.models.Model; import kotlin.coroutines.CoroutineContext; -import net.mamoe.mirai.event.EventHandler; -import net.mamoe.mirai.event.ListeningStatus; -import net.mamoe.mirai.event.SimpleListenerHost; -import net.mamoe.mirai.event.events.GroupMessageEvent; -import net.mamoe.mirai.event.events.MessageEvent; + import org.jetbrains.annotations.NotNull; -public class QQMessageListener extends SimpleListenerHost { +public class QQMessageListener { - @Override public void handleException(@NotNull CoroutineContext context, @NotNull Throwable exception) { // super.handleException(context, exception); exception.printStackTrace(); } - @EventHandler - public ListeningStatus onMessage(MessageEvent event) { - long qqNumber; + public void onMessage() { + /* long qqNumber; boolean isGroup; if (event instanceof GroupMessageEvent) { qqNumber = ((GroupMessageEvent) event).getGroup().getId(); @@ -51,7 +45,7 @@ public class QQMessageListener extends SimpleListenerHost { } } - return ListeningStatus.LISTENING; // 表示继续监听事件 + return ListeningStatus.LISTENING; // 表示继续监听事件*/ } diff --git a/src/main/java/com/yutou/qqbot/QQBotApplication.java b/src/main/java/com/yutou/qqbot/QQBotApplication.java index c6cdd8d..e873061 100644 --- a/src/main/java/com/yutou/qqbot/QQBotApplication.java +++ b/src/main/java/com/yutou/qqbot/QQBotApplication.java @@ -1,15 +1,19 @@ package com.yutou.qqbot; +import com.yutou.napcat.http.NapCatApi; +import com.yutou.okhttp.HttpLoggingInterceptor; import com.yutou.qqbot.utlis.RedisTools; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class QQBotApplication { - public static final String version="QQBot v.1.6.2"; + public static final String version = "QQBot v.1.6.2"; + public static void main(String[] args) { System.out.println("version = " + version); SpringApplication.run(QQBotApplication.class, args); + NapCatApi.setLog(true); RedisTools.initRedisPoolSub(); QQBotManager.getInstance(); //1 diff --git a/src/main/java/com/yutou/qqbot/QQBotController.java b/src/main/java/com/yutou/qqbot/QQBotController.java index f79a4e5..1d63eb7 100644 --- a/src/main/java/com/yutou/qqbot/QQBotController.java +++ b/src/main/java/com/yutou/qqbot/QQBotController.java @@ -1,5 +1,13 @@ package com.yutou.qqbot; +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONObject; +import com.yutou.napcat.enums.MessageEnum; +import com.yutou.napcat.event.MessageEvent; +import com.yutou.napcat.handle.BaseHandle; +import com.yutou.napcat.handle.OtherHandle; +import com.yutou.qqbot.MessageEvent.AdminMessage; +import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.AppTools; import com.yutou.qqbot.utlis.RedisTools; import org.springframework.stereotype.Controller; @@ -7,7 +15,12 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Set; @Controller public class QQBotController { @@ -33,4 +46,53 @@ public class QQBotController { AppTools.sendServer(title, msg); return "ok"; } + + @ResponseBody + @RequestMapping("/napcat/qq/bot.do") + public String qq_bot(HttpServletRequest request, HttpServletResponse response) { + // 处理请求 + Set strings = request.getParameterMap().keySet(); + for (String key : strings) { + System.out.println(key + ":" + request.getParameter(key)); + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try { + BufferedInputStream stream = new BufferedInputStream(request.getInputStream()); + byte[] bytes = new byte[1024]; + int len = 0, size; + while ((len = stream.read(bytes)) != -1) { + outputStream.write(bytes, 0, len); + outputStream.flush(); + } + String str = outputStream.toString(StandardCharsets.UTF_8); + System.out.println("str = " + str); + MessageEvent event = MessageEvent.parseHandle(str); + + long qqNumber = event.isGroup() ? event.getGroupId() : event.getUserId(); + boolean isGroup = event.isGroup(); + + if ((event.isGroup() && event.getSource().getUserId() == 583819556L) || (!event.isGroup() && event.getUserId() == 583819556L)) { + new AdminMessage(qqNumber, event.getRawMessage()); + } + for (Class model : Model.classList) { + if (QQNumberManager.getManager().isUseModel(qqNumber, model) || !isGroup) { + try { + Model useModel = (Model) model.getDeclaredConstructor().newInstance(); + if (!useModel.isUserPublic()) { + if (!QQNumberManager.getManager().isExistsPower(event.getSource().getFromId(), useModel.getUsePowers())) { + continue; + } + } + useModel.onMessage(qqNumber, event, isGroup); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + + } catch (Exception e) { + e.printStackTrace(); + } + return "200"; + } } diff --git a/src/main/java/com/yutou/qqbot/QQBotManager.java b/src/main/java/com/yutou/qqbot/QQBotManager.java index 35da386..281cf13 100644 --- a/src/main/java/com/yutou/qqbot/QQBotManager.java +++ b/src/main/java/com/yutou/qqbot/QQBotManager.java @@ -2,22 +2,24 @@ package com.yutou.qqbot; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; -import com.yutou.qqbot.Listeners.QQMessageListener; +import com.yutou.napcat.QQDatabase; +import com.yutou.napcat.handle.BaseHandle; +import com.yutou.napcat.handle.MessageHandleBuild; +import com.yutou.napcat.handle.Text; +import com.yutou.napcat.http.NapCatApi; +import com.yutou.napcat.model.FriendBean; +import com.yutou.napcat.model.GroupBean; +import com.yutou.napcat.model.SendMessageResponse; +import com.yutou.okhttp.HttpBody; +import com.yutou.okhttp.HttpCallback; +import com.yutou.qqbot.data.MessageChainBuilder; import com.yutou.qqbot.utlis.*; -import net.mamoe.mirai.Bot; -import net.mamoe.mirai.BotFactory; -import net.mamoe.mirai.auth.BotAuthorization; -import net.mamoe.mirai.event.GlobalEventChannel; -import net.mamoe.mirai.message.MessageReceipt; -import net.mamoe.mirai.message.data.*; -import net.mamoe.mirai.utils.BotConfiguration; -import net.mamoe.mirai.utils.ExternalResource; -import xyz.cssxsh.mirai.tool.FixProtocolVersion; +import retrofit2.Response; + import java.io.File; -import java.io.IOException; +import java.util.Arrays; import java.util.List; -import java.util.Objects; public class QQBotManager { @@ -26,7 +28,6 @@ public class QQBotManager { private static QQBotManager botManager = null; - private Bot bot; private static final long qqGroup = 891655174L; private boolean isLogin = false; private static boolean isInit = false; @@ -41,70 +42,47 @@ public class QQBotManager { } private void init() { - new Thread(new Runnable() { - private void reset() { - try { - Log.i("QQBot", "签名加密服务未启动,1分钟后重试"); - Thread.sleep(60 * 1000); - init(); - } catch (InterruptedException e) { - e.printStackTrace(); + sendMessage("姬妻酱上线拉~☆Daze~ 当前版本:" + QQBotApplication.version); + NapCatApi.getGroupApi().getGroupList().enqueue(new HttpCallback>() { + @Override + public void onResponse(int code, String status, List response, String rawResponse) { + for (GroupBean groupBean : response) { + QQDatabase.addGroup(groupBean.getGroupId(), groupBean); + QQNumberManager.getManager().addNumber(groupBean.getGroupId(), true); } - } @Override - public void run() { - String test = HttpTools.get("http://192.168.31.88:7400/"); - try { - JSONObject json = JSONObject.parseObject(test); - if (json.getInteger("code") != 0) { - reset(); - return; - } - } catch (Exception e) { - reset(); - return; - } - long qq = ConfigTools.load(ConfigTools.CONFIG, "qq_number", Long.class); - String password = ConfigTools.load(ConfigTools.CONFIG, "qq_password", String.class); - System.out.println("qq = " + qq); - System.out.println("password = " + password); - FixProtocolVersion.load(BotConfiguration.MiraiProtocol.ANDROID_PAD); - - bot = BotFactory.INSTANCE.newBot(qq, password, new BotConfiguration() { - { - - setProtocol(MiraiProtocol.ANDROID_PAD); - fileBasedDeviceInfo("qq_bot_devices_info.json"); - if ("nas".equals(ConfigTools.load(ConfigTools.CONFIG, "model"))) { - noBotLog(); - noNetworkLog(); - } - } - }); - //Events.registerEvents(bot, new MessageListener()); - GlobalEventChannel.INSTANCE.registerListenerHost(new QQMessageListener()); - // GlobalEventChannel.INSTANCE.subscribeAlways(GroupMessageEvent.class, new MessageListener()); - bot.login(); - new Thread(new Runnable() { - @Override - public void run() { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - String str = sendMessage("姬妻酱上线拉~☆Daze~ 当前版本:" + QQBotApplication.version); - Log.i(str); - isInit = true; - } - }).start(); - bot.join(); + public void onFailure(Throwable throwable) { } - }).start(); + }); + NapCatApi.getFriendApi().getFriendList().enqueue(new HttpCallback>() { + @Override + public void onResponse(int code, String status, List response, String rawResponse) { + for (FriendBean friendBean : response) { + QQDatabase.addUser(friendBean.getUserId(), friendBean); + QQNumberManager.getManager().addNumber(friendBean.getUserId(), false); + } + } + @Override + public void onFailure(Throwable throwable) { + + } + }); + NapCatApi.getUtilsApi().getLoginInfo().enqueue(new HttpCallback() { + @Override + public void onResponse(int code, String status, FriendBean response, String rawResponse) { + QQDatabase.setMe(response); + } + + @Override + public void onFailure(Throwable throwable) { + + } + }); + isInit = true; } public synchronized static QQBotManager getInstance() { @@ -114,133 +92,96 @@ public class QQBotManager { return botManager; } - public boolean isLogin() { - return isLogin; - } - - private Image getImage(File file, Long qq) { - if (file == null) { - return null; - } - if (bot != null) { - ExternalResource resource = ExternalResource.create(file); - Image image; - if (QQNumberManager.getManager().isGroup(qq)) { - image = Objects.requireNonNull(bot.getGroup(qq)).uploadImage(resource); - } else { - image = Objects.requireNonNull(bot.getFriend(qq)).uploadImage(resource); - } - try { - resource.close(); - } catch (IOException e) { - e.printStackTrace(); - } - return image; - } - return null; - } private String getNotLoginQQ() { return "没有登录QQ"; } - - public String sendMessage(String text) { - if (bot != null && !StringUtils.isEmpty(text)) { - try { - return Objects.requireNonNull(bot.getGroup(qqGroup)).sendMessage(text).toString(); - } catch (Exception e) { - e.printStackTrace(); - } - } - return getNotLoginQQ(); + public SendMessageResponse sendPrivateMessage(Long qq, BaseHandle... items) { + return sendMessage(true, qq, items); } - public MessageReceipt sendMessage(Long group, String text) { - if (bot != null) { - try { - if (QQNumberManager.getManager().isGroup(group)) { - return Objects.requireNonNull(bot.getGroup(group)).sendMessage(text); - } else { - return Objects.requireNonNull(bot.getFriend(group)).sendMessage(text); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - return null; + private SendMessageResponse sendGroupMessage(Long group, BaseHandle... items) { + return sendMessage(false, group, items); } - public MessageReceipt sendMessage(Long group, MessageChainBuilder builder) { - if (bot != null) { - if (QQNumberManager.getManager().isGroup(group)) { - System.out.println("发群"); - return Objects.requireNonNull(bot.getGroup(group)).sendMessage(builder.asMessageChain()); - } else { - System.out.println("发个人"); - return Objects.requireNonNull(bot.getFriend(group)).sendMessage(builder.asMessageChain()); - } - } - return null; + public SendMessageResponse sendMessage(boolean user, Long qq, String msg) { + return sendMessage(user, qq, new Text(msg)); } - public MessageReceipt sendMessage(File imageFile, Long qq, String text) { - return sendMessage(imageFile, qq, null, text); + public SendMessageResponse sendMessage(Long qq, BaseHandle... items) { + return sendMessage(QQDatabase.checkFriend(qq), qq, Arrays.asList(items)); } - public MessageReceipt sendMessage(File imageFile, Long qq, MessageChain replyMessage, String text) { + public SendMessageResponse sendMessage(boolean isUser, Long qq, BaseHandle... items) { + return sendMessage(isUser, qq, Arrays.asList(items)); + } + + public SendMessageResponse sendMessage(boolean isUser, Long qq, List> items) { try { - if (bot != null) { - Image image = getImage(imageFile, qq); - MessageChainBuilder builder = new MessageChainBuilder(); - if (replyMessage != null) { - builder.append(new QuoteReply(replyMessage)); - } - if (image != null) { - builder.append(image); - } - List list = PatternTools.getQQ(text); - if (!list.isEmpty()) { - for (String _qq : list) { - String[] tmp = text.split(_qq); - builder.append(tmp[0]); - builder.append(new At(Long.parseLong(_qq.replace("@", "")))); - text = text.replace(tmp[0] + _qq, ""); - } - } - builder.append(text); - if (QQNumberManager.getManager().isGroup(qq)) { - return Objects.requireNonNull(bot.getGroup(qq)).sendMessage(builder.asMessageChain()); - } else { - return Objects.requireNonNull(bot.getFriend(qq)).sendMessage(builder.asMessageChain()); + MessageHandleBuild handleBuild = MessageHandleBuild + .create() + .setGroup(!isUser) + .setQQNumber(qq); + for (BaseHandle item : items) { + if (item.getData() == null) { + continue; } + handleBuild.add(item); + } + Response> response; + if (isUser) { + response = NapCatApi.getMessageApi().sendPrivateMsg( + handleBuild.build() + ).execute(); + } else { + response = NapCatApi.getMessageApi().sendGroupMsg( + handleBuild.build() + ).execute(); + } + if (response.body() != null) { + return response.body().getData(); } } catch (Exception e) { e.printStackTrace(); + SendMessageResponse response = new SendMessageResponse(); + response.setId(-1); + response.setE(e.getMessage()); + return response; } - return null; } - public MessageReceipt sendMessage(File imageFile, String text) { - return sendMessage(imageFile, qqGroup, text); + public String sendMessage(String text) { + + return getNotLoginQQ(); } - public String sendMessage(List imgs, Long qq, String text) { - System.out.println("imgs.size() = " + imgs.size()); - if (bot != null) { - MessageChainBuilder builder = new MessageChainBuilder(); - for (File img : imgs) { - builder.append(Objects.requireNonNull(getImage(img, qq))); - } - builder.append(text); - if (QQNumberManager.getManager().isGroup(qq)) { - return Objects.requireNonNull(bot.getGroup(qq)).sendMessage(builder.asMessageChain()).toString(); - } else { - return Objects.requireNonNull(bot.getFriend(qq)).sendMessage(builder.asMessageChain()).toString(); - } + public SendMessageResponse sendMessage(Long group, String text) { + return sendMessage(QQDatabase.checkFriend(group), group, new Text(text)); + } + + public void sendMessage(Long group, MessageChainBuilder builder) { + if (QQNumberManager.getManager().isGroup(group)) { + System.out.println("发群"); + } else { + System.out.println("发个人"); } - return getNotLoginQQ(); + } + + public void sendMessage(File imageFile, Long qq, String text) { + sendMessage(imageFile, qq, null, text); + } + + public void sendMessage(File imageFile, Long qq, String replyMessageId, String text) { + + } + + public void sendMessage(File imageFile, String text) { + } + + public void sendMessage(List imgs, Long qq, String text) { + } @@ -262,8 +203,9 @@ public class QQBotManager { AppTools.sendServer("服务版本查询", msg); } - - public Bot getBot() { - return bot; + public boolean isLogin() { + return true; } + + } diff --git a/src/main/java/com/yutou/qqbot/data/MessageChainBuilder.java b/src/main/java/com/yutou/qqbot/data/MessageChainBuilder.java new file mode 100644 index 0000000..80dea12 --- /dev/null +++ b/src/main/java/com/yutou/qqbot/data/MessageChainBuilder.java @@ -0,0 +1,16 @@ +package com.yutou.qqbot.data; + +public class MessageChainBuilder { + StringBuilder sb; + public MessageChainBuilder() { + sb=new StringBuilder(); + } + public MessageChainBuilder append(String s){ + sb.append(s); + return this; + } + public MessageChainBuilder append(Object o){ + sb.append(o.toString()); + return this; + } +} diff --git a/src/main/java/com/yutou/qqbot/models/Animal/TurnipProphet.java b/src/main/java/com/yutou/qqbot/models/Animal/TurnipProphet.java index 35961fc..1202631 100644 --- a/src/main/java/com/yutou/qqbot/models/Animal/TurnipProphet.java +++ b/src/main/java/com/yutou/qqbot/models/Animal/TurnipProphet.java @@ -3,11 +3,11 @@ package com.yutou.qqbot.models.Animal; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONArray; import com.alibaba.fastjson2.JSONObject; +import com.yutou.napcat.event.MessageEvent; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.*; -import net.mamoe.mirai.event.events.MessageEvent; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; @@ -69,7 +69,7 @@ public class TurnipProphet extends Model { user = qq; sendQQ = qq; if (isGroup) { - if (!event.getMessage().serializeToMiraiCode().contains("[mirai:at:2476945931]")) { + if (!event.isAtMe()) { return; } user = event.getSource().getFromId(); diff --git a/src/main/java/com/yutou/qqbot/models/BiliBili/BiliBiliLive.java b/src/main/java/com/yutou/qqbot/models/BiliBili/BiliBiliLive.java index d212e6d..1fb3c44 100644 --- a/src/main/java/com/yutou/qqbot/models/BiliBili/BiliBiliLive.java +++ b/src/main/java/com/yutou/qqbot/models/BiliBili/BiliBiliLive.java @@ -1,17 +1,13 @@ package com.yutou.qqbot.models.BiliBili; +import com.yutou.napcat.event.MessageEvent; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; -import com.yutou.qqbot.bilibili.AppUserTask; -import com.yutou.qqbot.bilibili.BiliBiliAppUtils; import com.yutou.qqbot.bilibili.BiliBiliUtils; import com.yutou.qqbot.bilibili.BiliLogin; import com.yutou.qqbot.models.Model; -import com.yutou.qqbot.utlis.QRCodeUtils; import com.yutou.qqbot.utlis.RedisTools; -import net.mamoe.mirai.event.events.MessageEvent; -import java.io.File; import java.util.Set; @UseModel diff --git a/src/main/java/com/yutou/qqbot/models/BiliBili/BiliVideo.java b/src/main/java/com/yutou/qqbot/models/BiliBili/BiliVideo.java index 60d8ab1..c558774 100644 --- a/src/main/java/com/yutou/qqbot/models/BiliBili/BiliVideo.java +++ b/src/main/java/com/yutou/qqbot/models/BiliBili/BiliVideo.java @@ -2,20 +2,29 @@ package com.yutou.qqbot.models.BiliBili; 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.OtherHandle; +import com.yutou.napcat.handle.Reply; +import com.yutou.napcat.http.NapCatApi; +import com.yutou.napcat.model.MessageBean; +import com.yutou.okhttp.HttpBody; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; -import com.yutou.qqbot.QQNumberManager; import com.yutou.qqbot.bilibili.*; import com.yutou.qqbot.interfaces.ObjectInterface; import com.yutou.qqbot.models.Model; -import com.yutou.qqbot.utlis.*; -import net.mamoe.mirai.event.events.MessageEvent; -import net.mamoe.mirai.message.data.QuoteReply; +import com.yutou.qqbot.utlis.AppTools; +import com.yutou.qqbot.utlis.ConfigTools; +import com.yutou.qqbot.utlis.HttpTools; +import com.yutou.qqbot.utlis.StringUtils; +import retrofit2.Response; import java.io.File; import java.io.FileWriter; import java.io.IOException; -import java.util.*; +import java.util.ArrayList; +import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -55,50 +64,47 @@ public class BiliVideo extends Model { @Override public void onMessage(Long qq, MessageEvent event, boolean isGroup) { super.onMessage(qq, event, isGroup); - if (event.getMessage().serializeToMiraiCode().contains("mirai:app")) { - int id = event.getSource().getIds()[0]; - String json = event.getMessage().get(1).contentToString(); - System.out.println("id = " + id); - System.out.println("json = " + json); - RedisTools.set("qq_msg_id_" + id, json, 60 * 60 * 2); - } else if (isAt()) { - if (event.getMessage().get(1) instanceof QuoteReply) { - int id = ((QuoteReply) event.getMessage().get(1)).getSource().getIds()[0]; - if (msg.contains("省流") || msg.contains("总结")) { - String value = onAIVideo(id); - if(!StringUtils.isEmpty(value)){ - QQBotManager.getInstance().sendMessage(qq,value); - } + if (event.isAtMe() && event.hasType(MessageEnum.REPLY)) { + Reply reply = event.findType(Reply.class); + long id = reply.getData().getId(); + if (msg.contains("省流") || msg.contains("总结")) { + String value = onAIVideo(id); + if (!StringUtils.isEmpty(value)) { + QQBotManager.getInstance().sendMessage(qq, value); } } } } - private String onAIVideo(int id) { - String string = RedisTools.get("qq_msg_id_" + id); - //RedisTools.remove("qq_msg_id_"+id); - String url = null; - if (StringUtils.isEmpty(string)) { - url = ((QuoteReply) event.getMessage().get(1)).getSource().getOriginalMessage().contentToString(); - } else { - JSONObject json = JSONObject.parseObject(string); - if (json.containsKey("ver")) { - url = json.getJSONObject("meta").getJSONObject("detail_1").getString("qqdocurl"); + private String onAIVideo(long id) { + try { + Response> execute = NapCatApi.getMessageApi().getMessage(id).execute(); + if(execute.body()==null){ + return "省流失败"; } + MessageEvent handle = MessageEvent.parseHandleHttp(execute.body().getSrc()); + if (handle.hasType(MessageEnum.JSON)) { + OtherHandle type = handle.findType(OtherHandle.class); + String url = type.getData().getMeta().getDetail1().getQqdocurl(); + if (StringUtils.isEmpty(url)) { + return "地址不正确"; + } + if (url.startsWith("BV")) { + url = "https://www.bilibili.com/video/" + url.trim(); + } + if (!url.startsWith("https://www.bilibili.com/video/") && !url.startsWith("https://b23.tv")) { + return "这是B站吗?"; + } + String ai = BiliBiliAppUtils.getVideoAI(url.trim()); + if (!StringUtils.isEmpty(ai)) { + return ai; + } + } + } catch (Exception e) { + e.printStackTrace(); } - if (StringUtils.isEmpty(url)) { - return "地址不正确"; - } - if (url.startsWith("BV")) { - url = "https://www.bilibili.com/video/" + url.trim(); - } - if (!url.startsWith("https://www.bilibili.com/video/") && !url.startsWith("https://b23.tv")) { - return "这是B站吗?"; - } - String ai = BiliBiliAppUtils.getVideoAI(url.trim()); - if (!StringUtils.isEmpty(ai)) { - return ai; - } + + return "省流失败"; } diff --git a/src/main/java/com/yutou/qqbot/models/Commands/BTDownload.java b/src/main/java/com/yutou/qqbot/models/Commands/BTDownload.java index 0fc326b..71818c7 100644 --- a/src/main/java/com/yutou/qqbot/models/Commands/BTDownload.java +++ b/src/main/java/com/yutou/qqbot/models/Commands/BTDownload.java @@ -5,10 +5,12 @@ import com.yutou.qqbot.QQBotManager; import com.yutou.qqbot.interfaces.ObjectInterface; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.AppTools; -import net.mamoe.mirai.event.events.MessageEvent; +import com.yutou.napcat.event.MessageEvent; + @UseModel public class BTDownload extends Model { - private static final String DownloadHomePath="/media/yutou/disk_lvm/public/download/"; + private static final String DownloadHomePath = "/media/yutou/disk_lvm/public/download/"; + @Override public boolean isUserPublic() { return false; @@ -29,11 +31,11 @@ public class BTDownload extends Model { @Override public void onMessage(Long qq, MessageEvent event, boolean isGroup) { super.onMessage(qq, event, isGroup); - if(msg.startsWith("magnet:?xt=")){ - String builder = "已添加下载磁链" ; - QQBotManager.getInstance().sendMessage(qq, builder); + if (msg.startsWith("magnet:?xt=")) { + String builder = "已添加下载磁链"; + QQBotManager.getInstance().sendMessage(event.isUser(), qq, builder); String exec = String.format("qbittorrent-nox --save-path=%sdownload_tmp/%s \"%s\" " - ,DownloadHomePath + , DownloadHomePath , AppTools.getToDayTime() , msg ); @@ -42,7 +44,7 @@ public class BTDownload extends Model { public void out(String data) { super.out(data); } - },true,false); + }, true, false); } } } diff --git a/src/main/java/com/yutou/qqbot/models/Commands/BaiduDown.java b/src/main/java/com/yutou/qqbot/models/Commands/BaiduDown.java index 22a7f31..a5c744d 100644 --- a/src/main/java/com/yutou/qqbot/models/Commands/BaiduDown.java +++ b/src/main/java/com/yutou/qqbot/models/Commands/BaiduDown.java @@ -1,14 +1,16 @@ package com.yutou.qqbot.models.Commands; +import com.yutou.napcat.handle.Text; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; import com.yutou.qqbot.interfaces.ObjectInterface; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.AppTools; import com.yutou.qqbot.utlis.Log; -import net.mamoe.mirai.event.events.MessageEvent; +import com.yutou.napcat.event.MessageEvent; import java.io.File; + @UseModel public class BaiduDown extends Model { @Override @@ -31,16 +33,16 @@ public class BaiduDown extends Model { @Override public void onMessage(Long qq, MessageEvent event, boolean isGroup) { super.onMessage(qq, event, isGroup); - if(msg.startsWith(QQFromCommands.BAIDU_DOWN)){ - QQBotManager.getInstance().sendMessage(qq,"开始同步百度云"); - AppTools.exec("cd "+new File("baidupan").getAbsolutePath()+" && bypy downdir -v", new ObjectInterface() { + if (msg.startsWith(QQFromCommands.BAIDU_DOWN)) { + QQBotManager.getInstance().sendMessage(event.isUser(), qq, new Text("开始同步百度云")); + AppTools.exec("cd " + new File("baidupan").getAbsolutePath() + " && bypy downdir -v", new ObjectInterface() { @Override public void out(String data) { super.out(data); Log.i(data); - QQBotManager.getInstance().sendMessage(qq,"任务完成"); + QQBotManager.getInstance().sendMessage(qq, "任务完成"); } - },true,true); + }, true, true); } } } diff --git a/src/main/java/com/yutou/qqbot/models/Commands/BaiduGPT.java b/src/main/java/com/yutou/qqbot/models/Commands/BaiduGPT.java index f9ea802..0af4d9b 100644 --- a/src/main/java/com/yutou/qqbot/models/Commands/BaiduGPT.java +++ b/src/main/java/com/yutou/qqbot/models/Commands/BaiduGPT.java @@ -1,11 +1,13 @@ package com.yutou.qqbot.models.Commands; +import com.yutou.napcat.QQDatabase; +import com.yutou.napcat.handle.Text; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; import com.yutou.qqbot.data.baidu.ResponseMessage; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.BaiduGPTManager; -import net.mamoe.mirai.event.events.MessageEvent; +import com.yutou.napcat.event.MessageEvent; @UseModel public class BaiduGPT extends Model { @@ -31,15 +33,32 @@ public class BaiduGPT extends Model { @Override public void onMessage(Long qq, MessageEvent event, boolean isGroup) { super.onMessage(qq, event, isGroup); - if (msg.equals(QQGroupCommands.GPT_CLEAR)) { + if (event.getTextMessage().equals(QQGroupCommands.GPT_CLEAR)) { BaiduGPTManager.getManager().clear(); - QQBotManager.getInstance().sendMessage(qq, "已经失忆捏"); - } else if (isAt()) { - if(msg.contains("省流")|| msg.contains("总结")){ + QQBotManager.getInstance().sendMessage(event.isUser(), qq, new Text("已经失忆捏")); + } else if (event.isAtMe()) { + if (event.getTextMessage().contains("省流") || event.getTextMessage().contains("总结")) { return; } - ResponseMessage message = BaiduGPTManager.getManager().sendMessage(String.valueOf(user), msg.replace("@2476945931", "").trim()); - QQBotManager.getInstance().sendMessage(qq, message.getResult()); + if ("GPT切换到4.0".equals(event.getTextMessage())) { + BaiduGPTManager.getManager().clear(); + BaiduGPTManager.getManager().setModelFor40(); + QQBotManager.getInstance().sendMessage(event.isUser(), qq, "切换为4.0了"); + return; + } else if ("GPT切换到3.5".equals(event.getTextMessage())) { + BaiduGPTManager.getManager().clear(); + BaiduGPTManager.getManager().setModelFor35(); + QQBotManager.getInstance().sendMessage(event.isUser(), qq, "切换为3.5了"); + return; + } + ResponseMessage message = BaiduGPTManager.getManager().sendMessage( + String.valueOf(user), + event.getTextMessage().replace("@" + QQDatabase.getMe().getUserId(), "").trim()); + String sb = "调用版本:" + + BaiduGPTManager.getManager().getGPTVersion() + + "\n" + + message.getResult(); + QQBotManager.getInstance().sendMessage(event.isUser(), qq, new Text(sb)); } } } diff --git a/src/main/java/com/yutou/qqbot/models/Commands/Bangumi.java b/src/main/java/com/yutou/qqbot/models/Commands/Bangumi.java index 807964f..bb5d3f9 100644 --- a/src/main/java/com/yutou/qqbot/models/Commands/Bangumi.java +++ b/src/main/java/com/yutou/qqbot/models/Commands/Bangumi.java @@ -1,20 +1,20 @@ package com.yutou.qqbot.models.Commands; +import com.yutou.napcat.handle.BaseHandle; +import com.yutou.napcat.handle.Image; +import com.yutou.napcat.handle.Text; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; -import com.yutou.qqbot.interfaces.DownloadInterface; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.BangumiTools; -import com.yutou.qqbot.utlis.HttpTools; -import com.yutou.qqbot.utlis.Log; import com.yutou.qqbot.utlis.RedisTools; -import net.mamoe.mirai.event.events.MessageEvent; +import com.yutou.napcat.event.MessageEvent; -import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; + @UseModel public class Bangumi extends Model { @@ -25,13 +25,13 @@ public class Bangumi extends Model { switch (msg) { case QQGroupCommands.QQ_BANGUMI_TODAY -> { - QQBotManager.getInstance().sendMessage(qq, "获取中..."); + QQBotManager.getInstance().sendMessage(event.isUser(), qq, "获取中..."); RedisTools.remove("reportToDayBangumi"); - QQBotManager.getInstance().sendMessage(qq, BangumiTools.reportToDayBangumi()); + QQBotManager.getInstance().sendMessage(event.isUser(), qq, new Text(BangumiTools.reportToDayBangumi())); } case QQGroupCommands.QQ_BANGUMI_LIST -> { - QQBotManager.getInstance().sendMessage(qq, "获取中..."); - QQBotManager.getInstance().sendMessage(qq, BangumiTools.reportBangumiList()); + QQBotManager.getInstance().sendMessage(event.isUser(), qq, "获取中..."); + QQBotManager.getInstance().sendMessage(event.isUser(), qq, BangumiTools.reportBangumiList()); } default -> { if (msg.startsWith(QQGroupCommands.QQ_BANGUMI_SUB)) { @@ -44,7 +44,7 @@ public class Bangumi extends Model { private void subBanGumi(long qq, String msg) { List infos = null; - QQBotManager.getInstance().sendMessage(qq, "获取中..."); + QQBotManager.getInstance().sendMessage(event.isUser(), qq, "获取中..."); try { int id = Integer.parseInt(msg.replace(QQGroupCommands.QQ_BANGUMI_SUB, "").trim()); infos = BangumiTools.reportBangumiInfo(id); @@ -77,28 +77,20 @@ public class Bangumi extends Model { return list; } - private List files; private int index = 0; private void sendImagesMsg(List imgs, Long qq, String text, String key) { - files = new ArrayList<>(); index = 0; if (imgs.size() == 0) { - QQBotManager.getInstance().sendMessage(qq, text); + QQBotManager.getInstance().sendMessage(event.isUser(), qq, text); return; } + List> list = new ArrayList<>(); for (String img : imgs) { - File file = HttpTools.syncDownload(img.replace("http://", "https://"), key + ".jpg",false); - files.add(file); - send(imgs.size(), qq, text); - } - } - - private void send(int size, Long qq, String text) { - if ((files.size() + index) == size) { - String str = QQBotManager.getInstance().sendMessage(files, qq, text); - Log.i("str = " + str); + list.add(new Image(img.replace("http://", "https://"))); } + list.add(new Text(text)); + QQBotManager.getInstance().sendMessage(event.isUser(), qq, list); } @Override @@ -124,7 +116,8 @@ public class Bangumi extends Model { public void onTime(Long qq, String time) { super.onTime(qq, time); switch (time) { - case "08:00:00", "20:00:00" -> QQBotManager.getInstance().sendMessage(qq, BangumiTools.reportToDayBangumi()); + case "08:00:00", "20:00:00" -> + QQBotManager.getInstance().sendMessage(qq, BangumiTools.reportToDayBangumi()); } } } diff --git a/src/main/java/com/yutou/qqbot/models/Commands/MaoMaoWorkWaring.java b/src/main/java/com/yutou/qqbot/models/Commands/MaoMaoWorkWaring.java index 12c4e88..48218b7 100644 --- a/src/main/java/com/yutou/qqbot/models/Commands/MaoMaoWorkWaring.java +++ b/src/main/java/com/yutou/qqbot/models/Commands/MaoMaoWorkWaring.java @@ -1,13 +1,15 @@ package com.yutou.qqbot.models.Commands; +import com.yutou.napcat.handle.QuoteReply; +import com.yutou.napcat.handle.Reply; +import com.yutou.napcat.handle.Text; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; +import com.yutou.qqbot.data.MessageChainBuilder; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.AppTools; import com.yutou.qqbot.utlis.RedisTools; -import net.mamoe.mirai.event.events.MessageEvent; -import net.mamoe.mirai.message.data.MessageChainBuilder; -import net.mamoe.mirai.message.data.QuoteReply; +import com.yutou.napcat.event.MessageEvent; import static com.yutou.qqbot.models.Model.QQGroupCommands.QQ_TIMEOUT; @@ -31,13 +33,13 @@ public class MaoMaoWorkWaring extends Model { @Override public void onMessage(Long qq, MessageEvent event, boolean isGroup) { super.onMessage(qq, event, isGroup); - if(Integer.parseInt(AppTools.getHours())>=6 && event.getSource().getFromId() == 526306604 - && "false".equals(RedisTools.get("maomao_work_"+AppTools.getToDayTime(),"false"))){ - MessageChainBuilder builder=new MessageChainBuilder(); - builder.append(new QuoteReply(event.getMessage())); - builder.append("别水了,快去打工,没钱氪老婆了"); - QQBotManager.getInstance().sendMessage(qq,builder); - RedisTools.set("maomao_work_"+AppTools.getToDayTime(),"true",20*60*60); + if (Integer.parseInt(AppTools.getHours()) >= 6 && event.getSource().getFromId() == 526306604 + && "false".equals(RedisTools.get("maomao_work_" + AppTools.getToDayTime(), "false"))) { + QQBotManager.getInstance().sendMessage(event.isUser(), qq, + new Reply(user), + new Text("别水了,快去打工,没钱氪老婆了") + ); + RedisTools.set("maomao_work_" + AppTools.getToDayTime(), "true", 20 * 60 * 60); } } } diff --git a/src/main/java/com/yutou/qqbot/models/Commands/Moyu.java b/src/main/java/com/yutou/qqbot/models/Commands/Moyu.java index 7db6987..ee825f1 100644 --- a/src/main/java/com/yutou/qqbot/models/Commands/Moyu.java +++ b/src/main/java/com/yutou/qqbot/models/Commands/Moyu.java @@ -2,6 +2,8 @@ package com.yutou.qqbot.models.Commands; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; +import com.yutou.napcat.QQDatabase; +import com.yutou.napcat.handle.Image; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; import com.yutou.qqbot.interfaces.DownloadInterface; @@ -9,7 +11,7 @@ import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.AppTools; import com.yutou.qqbot.utlis.HttpTools; import com.yutou.qqbot.utlis.Log; -import net.mamoe.mirai.event.events.MessageEvent; +import com.yutou.napcat.event.MessageEvent; import java.io.File; @@ -42,7 +44,7 @@ public class Moyu extends Model { public synchronized void onTime(Long qq, String time) { super.onTime(qq, time); if ("09:50:00".equals(time)) { - downloadImage(false, qq); + // downloadImage(false, qq); } if ("10:00:00".equals(time)) { send(qq); @@ -78,13 +80,12 @@ public class Moyu extends Model { } private void send(Long qq) { - File file = new File(HttpTools.downloadPath + AppTools.getToDayTime() + "_moyu.jpg"); - Log.i(this, "发送图片 : file.exists = " + file.exists() + " qq = " + qq); - if (file.exists()) { - QQBotManager.getInstance().sendMessage(file, qq, ""); - } else { - downloadImage(true, qq); - } + + String ret = HttpTools.get("https://api.vvhan.com/api/moyu?type=json"); + JSONObject json = JSON.parseObject(ret); + QQBotManager.getInstance().sendMessage(QQDatabase.checkFriend(qq), qq, + new Image(json.getString("url")) + ); } public static void main(String[] args) { diff --git a/src/main/java/com/yutou/qqbot/models/Commands/PaoPaoSleepWaring.java b/src/main/java/com/yutou/qqbot/models/Commands/PaoPaoSleepWaring.java index 690513b..edb8b71 100644 --- a/src/main/java/com/yutou/qqbot/models/Commands/PaoPaoSleepWaring.java +++ b/src/main/java/com/yutou/qqbot/models/Commands/PaoPaoSleepWaring.java @@ -1,14 +1,15 @@ package com.yutou.qqbot.models.Commands; +import com.yutou.napcat.handle.QuoteReply; +import com.yutou.napcat.handle.Reply; +import com.yutou.napcat.handle.Text; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; +import com.yutou.qqbot.data.MessageChainBuilder; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.AppTools; import com.yutou.qqbot.utlis.RedisTools; -import net.mamoe.mirai.event.events.MessageEvent; -import net.mamoe.mirai.message.data.At; -import net.mamoe.mirai.message.data.MessageChainBuilder; -import net.mamoe.mirai.message.data.QuoteReply; +import com.yutou.napcat.event.MessageEvent; import static com.yutou.qqbot.models.Model.QQGroupCommands.QQ_TIMEOUT; @@ -34,10 +35,11 @@ public class PaoPaoSleepWaring extends Model { super.onMessage(qq, event, isGroup); if(Integer.parseInt(AppTools.getHours())>=22 && event.getSource().getFromId() == 914520754 && "false".equals(RedisTools.get("paopao_sleep_"+AppTools.getToDayTime(),"false"))){ - MessageChainBuilder builder=new MessageChainBuilder(); - builder.append(new QuoteReply(event.getMessage())); - builder.append("别水了,该睡了~"); - QQBotManager.getInstance().sendMessage(qq,builder); + // builder.append(new QuoteReply(event.getMessage().getId())); + QQBotManager.getInstance().sendMessage(event.isUser(),qq, + new Reply(user), + new Text("别水了,该睡了~") + ); RedisTools.set("paopao_sleep_"+AppTools.getToDayTime(),"true",1*60*60); } /*if(event.getSource().getFromId() == 914520754 && msg.contains("#体力")){ diff --git a/src/main/java/com/yutou/qqbot/models/Commands/System/Audio.java b/src/main/java/com/yutou/qqbot/models/Commands/System/Audio.java index 0d9e2f0..ac88360 100644 --- a/src/main/java/com/yutou/qqbot/models/Commands/System/Audio.java +++ b/src/main/java/com/yutou/qqbot/models/Commands/System/Audio.java @@ -3,7 +3,7 @@ package com.yutou.qqbot.models.Commands.System; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.models.audio.QQAudio; -import net.mamoe.mirai.event.events.MessageEvent; +import com.yutou.napcat.event.MessageEvent; @UseModel public class Audio extends Model { diff --git a/src/main/java/com/yutou/qqbot/models/Commands/System/BtFlash.java b/src/main/java/com/yutou/qqbot/models/Commands/System/BtFlash.java index e3ca6b9..cd8e204 100644 --- a/src/main/java/com/yutou/qqbot/models/Commands/System/BtFlash.java +++ b/src/main/java/com/yutou/qqbot/models/Commands/System/BtFlash.java @@ -4,7 +4,7 @@ import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.HttpTools; -import net.mamoe.mirai.event.events.MessageEvent; +import com.yutou.napcat.event.MessageEvent; @UseModel public class BtFlash extends Model { @Override diff --git a/src/main/java/com/yutou/qqbot/models/Commands/System/Cmd.java b/src/main/java/com/yutou/qqbot/models/Commands/System/Cmd.java index 902fa8d..5a76068 100644 --- a/src/main/java/com/yutou/qqbot/models/Commands/System/Cmd.java +++ b/src/main/java/com/yutou/qqbot/models/Commands/System/Cmd.java @@ -3,7 +3,7 @@ package com.yutou.qqbot.models.Commands.System; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.RedisTools; -import net.mamoe.mirai.event.events.MessageEvent; +import com.yutou.napcat.event.MessageEvent; @UseModel public class Cmd extends Model { @Override diff --git a/src/main/java/com/yutou/qqbot/models/Commands/System/Help.java b/src/main/java/com/yutou/qqbot/models/Commands/System/Help.java index 2559245..777c402 100644 --- a/src/main/java/com/yutou/qqbot/models/Commands/System/Help.java +++ b/src/main/java/com/yutou/qqbot/models/Commands/System/Help.java @@ -3,7 +3,7 @@ package com.yutou.qqbot.models.Commands.System; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; import com.yutou.qqbot.models.Model; -import net.mamoe.mirai.event.events.MessageEvent; +import com.yutou.napcat.event.MessageEvent; @UseModel public class Help extends Model { diff --git a/src/main/java/com/yutou/qqbot/models/Commands/System/IP.java b/src/main/java/com/yutou/qqbot/models/Commands/System/IP.java index 0ef48da..05196e3 100644 --- a/src/main/java/com/yutou/qqbot/models/Commands/System/IP.java +++ b/src/main/java/com/yutou/qqbot/models/Commands/System/IP.java @@ -3,7 +3,7 @@ package com.yutou.qqbot.models.Commands.System; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.RedisTools; -import net.mamoe.mirai.event.events.MessageEvent; +import com.yutou.napcat.event.MessageEvent; @UseModel public class IP extends Model { @Override diff --git a/src/main/java/com/yutou/qqbot/models/Commands/System/OpenPC.java b/src/main/java/com/yutou/qqbot/models/Commands/System/OpenPC.java index a38a65f..04acbe5 100644 --- a/src/main/java/com/yutou/qqbot/models/Commands/System/OpenPC.java +++ b/src/main/java/com/yutou/qqbot/models/Commands/System/OpenPC.java @@ -3,7 +3,7 @@ package com.yutou.qqbot.models.Commands.System; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.RedisTools; -import net.mamoe.mirai.event.events.MessageEvent; +import com.yutou.napcat.event.MessageEvent; import java.text.SimpleDateFormat; import java.util.Date; diff --git a/src/main/java/com/yutou/qqbot/models/Commands/System/Restart.java b/src/main/java/com/yutou/qqbot/models/Commands/System/Restart.java index b1366ca..8fe5d49 100644 --- a/src/main/java/com/yutou/qqbot/models/Commands/System/Restart.java +++ b/src/main/java/com/yutou/qqbot/models/Commands/System/Restart.java @@ -4,7 +4,7 @@ import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.AppTools; -import net.mamoe.mirai.event.events.MessageEvent; +import com.yutou.napcat.event.MessageEvent; @UseModel public class Restart extends Model { @Override diff --git a/src/main/java/com/yutou/qqbot/models/Commands/System/ToolsIdea.java b/src/main/java/com/yutou/qqbot/models/Commands/System/ToolsIdea.java index 77cbefc..558739e 100644 --- a/src/main/java/com/yutou/qqbot/models/Commands/System/ToolsIdea.java +++ b/src/main/java/com/yutou/qqbot/models/Commands/System/ToolsIdea.java @@ -1,12 +1,14 @@ package com.yutou.qqbot.models.Commands.System; +import com.yutou.napcat.QQDatabase; +import com.yutou.napcat.handle.Text; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.IdeaTools; import com.yutou.qqbot.utlis.RedisTools; import com.yutou.qqbot.utlis.StringUtils; -import net.mamoe.mirai.event.events.MessageEvent; +import com.yutou.napcat.event.MessageEvent; @UseModel public class ToolsIdea extends Model { @Override @@ -49,7 +51,10 @@ public class ToolsIdea extends Model { RedisTools.set("ideaUrl", msg.replace(QQGroupCommands.QQ_TOOLS_IDEA_URL, "").trim()); QQBotManager.getInstance().sendMessage(qq, "已设定下载地址:" + RedisTools.get("ideaUrl")); } else if (msg.startsWith(QQGroupCommands.QQ_TOOLS_IDEA_FILE)) { - QQBotManager.getInstance().sendMessage(qq, IdeaTools.getIdea(event.getMessage().contentToString().replace(QQGroupCommands.QQ_TOOLS_IDEA_FILE, ""))); + QQBotManager.getInstance().sendMessage(event.isUser(),qq, + new Text(msg.replace(QQGroupCommands.QQ_TOOLS_IDEA_FILE, "")) + ); + // QQBotManager.getInstance().sendMessage(qq, IdeaTools.getIdea(event.getMessage().contentToString().replace(QQGroupCommands.QQ_TOOLS_IDEA_FILE, ""))); } } } diff --git a/src/main/java/com/yutou/qqbot/models/Commands/System/UpdateIP.java b/src/main/java/com/yutou/qqbot/models/Commands/System/UpdateIP.java index e1f679d..7121702 100644 --- a/src/main/java/com/yutou/qqbot/models/Commands/System/UpdateIP.java +++ b/src/main/java/com/yutou/qqbot/models/Commands/System/UpdateIP.java @@ -3,7 +3,7 @@ package com.yutou.qqbot.models.Commands.System; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.RedisTools; -import net.mamoe.mirai.event.events.MessageEvent; +import com.yutou.napcat.event.MessageEvent; @UseModel public class UpdateIP extends Model { @Override diff --git a/src/main/java/com/yutou/qqbot/models/Commands/System/Version.java b/src/main/java/com/yutou/qqbot/models/Commands/System/Version.java index 1489c46..5d62414 100644 --- a/src/main/java/com/yutou/qqbot/models/Commands/System/Version.java +++ b/src/main/java/com/yutou/qqbot/models/Commands/System/Version.java @@ -3,7 +3,7 @@ package com.yutou.qqbot.models.Commands.System; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; import com.yutou.qqbot.models.Model; -import net.mamoe.mirai.event.events.MessageEvent; +import com.yutou.napcat.event.MessageEvent; @UseModel public class Version extends Model { @Override diff --git a/src/main/java/com/yutou/qqbot/models/Commands/WoodenFish.java b/src/main/java/com/yutou/qqbot/models/Commands/WoodenFish.java index e4ab5b5..3566077 100644 --- a/src/main/java/com/yutou/qqbot/models/Commands/WoodenFish.java +++ b/src/main/java/com/yutou/qqbot/models/Commands/WoodenFish.java @@ -1,14 +1,10 @@ package com.yutou.qqbot.models.Commands; +import com.yutou.napcat.handle.Record; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; import com.yutou.qqbot.models.Model; -import net.mamoe.mirai.contact.AudioSupported; -import net.mamoe.mirai.event.events.MessageEvent; -import net.mamoe.mirai.message.data.Audio; -import net.mamoe.mirai.message.data.MessageChainBuilder; -import net.mamoe.mirai.message.data.OfflineAudio; -import net.mamoe.mirai.utils.ExternalResource; +import com.yutou.napcat.event.MessageEvent; import java.io.File; import java.util.Objects; @@ -35,20 +31,11 @@ public class WoodenFish extends Model { @Override public void onMessage(Long qq, MessageEvent event, boolean isGroup) { super.onMessage(qq, event, isGroup); - File file = null; - if(msg.contains("地狱笑话")){ - file=new File("muyu.mp3"); - QQBotManager.getInstance().sendMessage(qq,"功德+1"); - }else if(msg.contains("遥遥领先")){ - file=new File("遥遥领先.silk"); - } - if(file!=null){ - if(file.exists()) { - OfflineAudio audio = Objects.requireNonNull(event.getBot().getGroup(qq)).uploadAudio(ExternalResource.create(file)); - MessageChainBuilder builder = new MessageChainBuilder(); - builder.append(audio); - QQBotManager.getInstance().sendMessage(qq,builder); - } + if (msg.contains("地狱笑话")) { + QQBotManager.getInstance().sendMessage(event.isUser(), qq, new Record("muyu.mp3")); + QQBotManager.getInstance().sendMessage(event.isUser(), qq, "功德+1"); + } else if (msg.contains("遥遥领先")) { + QQBotManager.getInstance().sendMessage(event.isUser(), qq, new Record("遥遥领先.mp3")); } } } diff --git a/src/main/java/com/yutou/qqbot/models/Model.java b/src/main/java/com/yutou/qqbot/models/Model.java index eb86840..342bc47 100644 --- a/src/main/java/com/yutou/qqbot/models/Model.java +++ b/src/main/java/com/yutou/qqbot/models/Model.java @@ -1,14 +1,12 @@ package com.yutou.qqbot.models; -import com.yutou.qqbot.QQBotManager; +import com.yutou.napcat.event.GroupMessageEvent; +import com.yutou.napcat.event.MessageEvent; +import com.yutou.napcat.handle.At; import com.yutou.qqbot.QQNumberManager; import com.yutou.qqbot.interfaces.ModelInterface; import com.yutou.qqbot.utlis.ConfigTools; -import net.mamoe.mirai.Bot; -import net.mamoe.mirai.event.events.GroupMessageEvent; -import net.mamoe.mirai.event.events.MessageEvent; -import net.mamoe.mirai.message.data.At; -import net.mamoe.mirai.message.data.MessageChainBuilder; + import java.lang.reflect.Field; import java.util.ArrayList; @@ -45,8 +43,8 @@ public abstract class Model implements ModelInterface { public final static String QQ_WOODEN = "!电子木鱼"; public final static String QQ_TIMEOUT = "!timer"; - public final static String GPT="!百度gpt"; - public final static String GPT_CLEAR="!百度失忆"; + public final static String GPT = "!百度gpt"; + public final static String GPT_CLEAR = "!百度失忆"; } @@ -57,9 +55,9 @@ public abstract class Model implements ModelInterface { public static final String ROUTER_ADD = "!添加设备"; public static final String ROUTER_DEL = "!删除设备"; public static final String BT_DOWNLOAD = "下载bt"; - public static final String BILI_MANGA_SIGN="!b站漫画签到"; - public static final String BILI_MANGA_PAY="!b站漫画积分兑换"; - public static final String BILI_MANGA_PAY_STOP="!b站漫画积分兑换取消"; + public static final String BILI_MANGA_SIGN = "!b站漫画签到"; + public static final String BILI_MANGA_PAY = "!b站漫画积分兑换"; + public static final String BILI_MANGA_PAY_STOP = "!b站漫画积分兑换取消"; } @@ -84,14 +82,13 @@ public abstract class Model implements ModelInterface { public Long user; public void onMessage(Long qq, MessageEvent event, boolean isGroup) { - this.event=event; - msg = event.getMessage().contentToString(); + this.event = event; + msg = event.getRawMessage(); msg = msg.replace("!", "!").trim(); - this.isGroup = isGroup; + this.isGroup = event.isGroup(); if (isGroup) { user = event.getSource().getFromId(); - GroupMessageEvent groupEvent = (GroupMessageEvent) event; - group = groupEvent.getGroup().getId(); + group = event.getGroupId(); if (QQNumberManager.getManager().isExistsPower(group, msg.split(" ")[0])) { isGroupPower = true; } @@ -114,16 +111,17 @@ public abstract class Model implements ModelInterface { return builder; } - public MessageChainBuilder getMessage(String text) { - MessageChainBuilder chain = new MessageChainBuilder(); + public String getMessage(String text) { + StringBuilder chain = new StringBuilder(); if (isGroup) { - chain.add(new At(user)); - chain.add("\n"); + chain.append(new At(user)); + chain.append("\n"); } - chain.add(text); - return chain; + chain.append(text); + return chain.toString(); } - public boolean isAt(){ - return msg.contains("@"+ ConfigTools.load(ConfigTools.CONFIG,"qq_number",String.class)); + + public boolean isAt() { + return msg.contains("@" + ConfigTools.load(ConfigTools.CONFIG, "qq_number", String.class)); } } diff --git a/src/main/java/com/yutou/qqbot/models/WebSign/BiliBiliMangeSign.java b/src/main/java/com/yutou/qqbot/models/WebSign/BiliBiliMangeSign.java index 564e563..571fd66 100644 --- a/src/main/java/com/yutou/qqbot/models/WebSign/BiliBiliMangeSign.java +++ b/src/main/java/com/yutou/qqbot/models/WebSign/BiliBiliMangeSign.java @@ -7,7 +7,7 @@ import com.yutou.qqbot.bilibili.BiliLogin; import com.yutou.qqbot.interfaces.ObjectInterface; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.QRCodeUtils; -import net.mamoe.mirai.event.events.MessageEvent; +import com.yutou.napcat.event.MessageEvent; import java.io.File; diff --git a/src/main/java/com/yutou/qqbot/models/WebSign/Tsdm.java b/src/main/java/com/yutou/qqbot/models/WebSign/Tsdm.java index 750e7f0..9d45ad0 100644 --- a/src/main/java/com/yutou/qqbot/models/WebSign/Tsdm.java +++ b/src/main/java/com/yutou/qqbot/models/WebSign/Tsdm.java @@ -7,7 +7,7 @@ import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.*; -import net.mamoe.mirai.event.events.MessageEvent; +import com.yutou.napcat.event.MessageEvent; import org.openqa.selenium.*; import java.io.File; diff --git a/src/main/java/com/yutou/qqbot/models/XiaoMi/MiRouter.java b/src/main/java/com/yutou/qqbot/models/XiaoMi/MiRouter.java index 47e8ff8..7acf448 100644 --- a/src/main/java/com/yutou/qqbot/models/XiaoMi/MiRouter.java +++ b/src/main/java/com/yutou/qqbot/models/XiaoMi/MiRouter.java @@ -9,7 +9,7 @@ import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.HttpTools; import com.yutou.qqbot.utlis.RedisTools; import com.yutou.qqbot.utlis.XiaoMiRouter; -import net.mamoe.mirai.event.events.MessageEvent; +import com.yutou.napcat.event.MessageEvent; import java.util.HashSet; import java.util.Set; diff --git a/src/main/java/com/yutou/qqbot/models/setu/GetSeTu.java b/src/main/java/com/yutou/qqbot/models/setu/GetSeTu.java index 1bac2c7..d915101 100644 --- a/src/main/java/com/yutou/qqbot/models/setu/GetSeTu.java +++ b/src/main/java/com/yutou/qqbot/models/setu/GetSeTu.java @@ -3,19 +3,19 @@ package com.yutou.qqbot.models.setu; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONArray; import com.alibaba.fastjson2.JSONObject; +import com.yutou.napcat.QQDatabase; +import com.yutou.napcat.event.MessageEvent; +import com.yutou.napcat.handle.*; +import com.yutou.napcat.model.SourceFrom; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; +import com.yutou.qqbot.data.MessageChainBuilder; import com.yutou.qqbot.interfaces.DownloadInterface; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.HttpTools; import com.yutou.qqbot.utlis.Log; import com.yutou.qqbot.utlis.RedisTools; import com.yutou.qqbot.utlis.StringUtils; -import net.mamoe.mirai.event.events.MessageEvent; -import net.mamoe.mirai.message.MessageReceipt; -import net.mamoe.mirai.message.data.At; -import net.mamoe.mirai.message.data.MessageChainBuilder; -import net.mamoe.mirai.message.data.QuoteReply; import redis.clients.jedis.Jedis; import java.io.File; @@ -111,7 +111,7 @@ public class GetSeTu extends Model { builder.append("明天见~"); } if (builder != null) { - QQBotManager.getInstance().sendMessage(group, builder); + QQBotManager.getInstance().sendMessage(QQDatabase.checkFriend(group), group, builder.toString()); } } @@ -218,41 +218,27 @@ public class GetSeTu extends Model { for (Object tags : item.getJSONArray("tags")) { builder.append(tags).append("、"); } - HttpTools.download(item.getJSONObject("urls").getString("regular"), - System.currentTimeMillis() + "_setu.jpg", - true - , new DownloadInterface() { - @Override - public void onDownload(File file) { - super.onDownload(file); - builder.append("\n看不到图?点这里:http://setu.cnmglz.com/setu/").append(file.getName()); - QQBotManager.getInstance().sendMessage(file, qq, event.getMessage(), ""); - MessageChainBuilder chain = new MessageChainBuilder(); - chain.append(new QuoteReply(event.getMessage())); - chain.append(builder.toString()); - MessageReceipt message = QQBotManager.getInstance().sendMessage(qq, chain); - Log.i(getModelName(), message); - - } - - @Override - public void onError(Exception e) { - super.onError(e); - getSeTu(model, tmpKey, r18, fuzzyR18, qq, event, reset - 1); - e.printStackTrace(); - } - }); + builder.append("\n看不到图?点这里:").append(item.getJSONObject("urls").getString("regular")); + QQBotManager.getInstance().sendMessage(false, qq, + new Image(item.getJSONObject("urls").getString("regular")), + new Reply(event.getMessageId()) + ); + QQBotManager.getInstance().sendMessage(false, qq, + new Reply(event.getMessageId()), + new Text(builder.toString()) + ); return true; } public static void main(String[] args) { - String msg = "来点1色图"; + String msg = "来点色图"; Pattern pattern = Pattern.compile("来点(.*?)色图"); Matcher matcher = pattern.matcher(msg); - String key = null; - if (matcher.find()) { - key = matcher.group(1); - } - System.out.println("key = " + key); + MessageEvent event = new MessageEvent(); + SourceFrom sourceFrom = new SourceFrom(); + sourceFrom.setUserId(583819556L); + event.setSource(sourceFrom); + event.setRawMessage(msg); + new GetSeTu().onMessage(583819556L, event, false); } } diff --git a/src/main/java/com/yutou/qqbot/models/setu/QQSetu.java b/src/main/java/com/yutou/qqbot/models/setu/QQSetu.java index 5b5ac5f..9b4463c 100644 --- a/src/main/java/com/yutou/qqbot/models/setu/QQSetu.java +++ b/src/main/java/com/yutou/qqbot/models/setu/QQSetu.java @@ -4,17 +4,25 @@ package com.yutou.qqbot.models.setu; import com.alibaba.fastjson2.JSON; 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.http.NapCatApi; +import com.yutou.napcat.model.MessageBean; +import com.yutou.okhttp.HttpBody; import com.yutou.qqbot.Annotations.UseModel; import com.yutou.qqbot.QQBotManager; +import com.yutou.qqbot.data.MessageChainBuilder; import com.yutou.qqbot.models.Model; import com.yutou.qqbot.utlis.AppTools; import com.yutou.qqbot.utlis.Log; import com.yutou.qqbot.utlis.RedisTools; -import net.mamoe.mirai.event.events.GroupMessageEvent; -import net.mamoe.mirai.event.events.MessageEvent; -import net.mamoe.mirai.message.data.At; -import net.mamoe.mirai.message.data.Image; -import net.mamoe.mirai.message.data.MessageChainBuilder; +import com.yutou.napcat.event.MessageEvent; +import com.yutou.qqbot.utlis.StringUtils; import java.io.IOException; import java.net.HttpURLConnection; @@ -25,88 +33,91 @@ import java.util.*; @UseModel public class QQSetu extends Model { - private int db_print =1;//统计结果 - private int db_user =3;//当次数据 + private int db_print = 1;//统计结果 + private int db_user = 3;//当次数据 private long group; private Timer timer; private static final Map setuScore = new HashMap<>(); - public void printTodaySetu() { - String redisKey= AppTools.getToDayTime() + "_setu"; + public void printTodaySetu() throws Exception { + String redisKey = AppTools.getToDayTime() + "_setu"; Log.i("今日涩图 redisKey = " + redisKey); String js = RedisTools.get(redisKey, db_print); if (js != null) { JSONObject json = JSON.parseObject(js); - if(json.containsKey("isPrint")&&json.getBooleanValue("isPrint")){ + if (json.containsKey("isPrint") && json.getBooleanValue("isPrint")) { return; } - Map groupAverage=new HashMap<>(); - Map groupImage=new HashMap<>(); - JSONObject setu=null; + Map groupAverage = new HashMap<>(); + Map groupImage = new HashMap<>(); + JSONObject setu = null; for (String id : json.keySet()) { - String group=json.getJSONObject(id).getJSONObject("info").getLong("group")+""; - if(groupAverage.containsKey(group)){ - if(groupAverage.get(group)<=json.getJSONObject(id).getFloat("average")){ - groupAverage.put(group,json.getJSONObject(id).getFloat("average")); - groupImage.put(group,id); + String group = json.getJSONObject(id).getJSONObject("info").getLong("group") + ""; + if (groupAverage.containsKey(group)) { + if (groupAverage.get(group) <= json.getJSONObject(id).getFloat("average")) { + groupAverage.put(group, json.getJSONObject(id).getFloat("average")); + groupImage.put(group, id); } - }else{ - groupAverage.put(group,json.getJSONObject(id).getFloat("average")); - groupImage.put(group,id); + } else { + groupAverage.put(group, json.getJSONObject(id).getFloat("average")); + groupImage.put(group, id); } } for (String id : groupImage.keySet()) { - setu=json.getJSONObject(groupImage.get(id)); - if(setu!=null){ - json.put("isPrint",true); - RedisTools.set(db_print,redisKey,json.toJSONString()); - JSONObject info=setu.getJSONObject("info"); - JSONObject score=setu.getJSONObject("score"); - MessageChainBuilder builder = new MessageChainBuilder(); - builder.append(Image.fromId(info.getString("id"))); - builder.append("本日最佳涩图由").append(new At(info.getLong("sourQQ"))).append("提供\n"); - builder.append("获得分数 ").append(String.valueOf(setu.getFloat("average"))).append("\n"); - builder.append("共有 ").append(String.valueOf(score.getIntValue("userNumber"))).append(" 人参与投票"); - QQBotManager.getInstance().sendMessage(info.getLong("group"),builder); - Log.i("今日涩图:"+builder.toString()); + setu = json.getJSONObject(groupImage.get(id)); + if (setu != null) { + json.put("isPrint", true); + RedisTools.set(db_print, redisKey, json.toJSONString()); + JSONObject info = setu.getJSONObject("info"); + JSONObject score = setu.getJSONObject("score"); + HttpBody body = NapCatApi.getMessageApi().getMessage(info.getLong("id")).execute().body(); + List> sendList = new ArrayList<>(); + if (body == null) { + sendList.add(new Text("[图片获取失败]")); + return; + } + MessageEvent handle = MessageEvent.parseHandleHttp(body.getSrc()); + Image image = handle.findType(Image.class); + if (image == null) { + sendList.add(new Text("[图片获取失败]")); + } else { + sendList.add(image); + } + + //builder.append(Image.fromId(info.getString("id"))); + sendList.add(new Text( + "本日最佳涩图由", false + )); + sendList.add(new At(handle.getSource().getUserId())); + sendList.add(new Text("提供", false)); + sendList.add(new Text("获得分数 ", false)); + sendList.add(new Text(String.valueOf(setu.getFloat("average")), false)); + sendList.add(new Text("共有 ", false)); + sendList.add(new Text(String.valueOf(score.getIntValue("userNumber")), false)); + sendList.add(new Text(" 人参与投票", false)); + QQBotManager.getInstance().sendMessage(handle.isUser(), handle.getGroupId(), sendList); } } - }else { + } else { Log.i("今日没有涩图"); } } - private boolean isSetu(Image image) { - String url = Image.queryUrl(image); - try { - HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); - int length = connection.getContentLength(); - connection.disconnect(); - if (length > 50000) { - return true; - } - } catch (IOException e) { - e.printStackTrace(); - return false; - } - - return false; + private boolean isSetu(Long length) { + return length > 50000; } - private void setuBuilder(Image image, GroupMessageEvent event) { - if (!isSetu(image)) { + private void setuBuilder(Image image, MessageEvent event) { + if (StringUtils.isEmpty(image.getData().getFileSize()) || !isSetu(Long.parseLong(image.getData().getFileSize()))) { return; } - if (RedisTools.get(event.getGroup().getId()+"setu", db_user) != null) { - printSetu(event.getGroup().getId()); + if (RedisTools.get(event.getGroupId() + "setu", db_user) != null) { + printSetu(event.getGroupId()); } setuScore.clear(); JSONObject json = new JSONObject(); - json.put("id", image.getImageId()); - json.put("sourName", event.getSenderName()); - json.put("sourQQ", event.getSender().getId()); - json.put("group", event.getGroup().getId()); - RedisTools.set(event.getGroup().getId()+"setu", json.toJSONString(),6*60, db_user); + json.put("id", event.getMessageId()); + RedisTools.set(event.getGroupId() + "setu", json.toJSONString(), 6 * 60, db_user); if (timer != null) { timer.cancel(); timer = null; @@ -119,7 +130,7 @@ public class QQSetu extends Model { timer.schedule(new TimerTask() { @Override public void run() { - if(!setuScore.isEmpty()){ + if (!setuScore.isEmpty()) { printSetu(group); } timer.cancel(); @@ -129,7 +140,7 @@ public class QQSetu extends Model { } private void printSetu(long group) { - JSONObject jt = JSON.parseObject(RedisTools.get(group+"setu", db_user)); + JSONObject jt = JSON.parseObject(RedisTools.get(group + "setu", db_user)); String id = jt.getString("id"); float average = 0; float max = 0; @@ -137,7 +148,7 @@ public class QQSetu extends Model { float length = 0; String maxName = ""; String minName = ""; - if(setuScore.size()<=1){ + if (setuScore.size() <= 1) { return; } for (String name : setuScore.keySet()) { @@ -161,8 +172,8 @@ public class QQSetu extends Model { score.put("userNumber", setuScore.size()); average = average / setuScore.size(); - String builder = "涩图评分:" + average +"\n "+ - "其中最高分由:" + maxName + " 给与:" + max +"\n "+ + String builder = "涩图评分:" + average + "\n " + + "其中最高分由:" + maxName + " 给与:" + max + "\n " + "其中最低分由:" + minName + " 给与:" + min; QQBotManager.getInstance().sendMessage(group, builder); String st = RedisTools.get(AppTools.getToDayTime() + "_setu", db_print); @@ -186,33 +197,34 @@ public class QQSetu extends Model { json.put(id, item); RedisTools.set(db_print, AppTools.getToDayTime() + "_setu", json.toJSONString()); } - RedisTools.remove(group+"setu",db_user); + RedisTools.remove(group + "setu", db_user); setuScore.clear(); } + @Override - public void onMessage(Long qq, MessageEvent event, boolean isGroup){ - if(!isGroup){ + public void onMessage(Long qq, MessageEvent event, boolean isGroup) { + if (!isGroup) { return; } - group=qq; - String msg=event.getMessage().contentToString(); - if ("[图片]".equals(msg.trim())) { - Image image = (Image) event.getMessage().stream().filter(Image.class::isInstance).findFirst().orElse(null); - if (image != null) { - setuBuilder(image, (GroupMessageEvent) event); - return; - } + Image image = event.hasType(MessageEnum.IMAGE) ? event.findType(Image.class) : null; + if (image != null) { + setuBuilder(image, event); + return; + } + Text text = event.hasType(MessageEnum.TEXT) ? event.findType(Text.class) : null; + if (text == null) { + return; } try { - if(msg.trim().length()>3){ + if (text.toString().trim().length() > 3) { return; } - float i = Float.parseFloat(msg.trim()); + float i = Float.parseFloat(text.toString().trim()); if (i > 0 && i <= 10) { - String name = event.getSenderName(); - String sender=event.getSender().getId()+""; + String name = event.getSource().getNickname(); + String sender = event.getSource().getUserId() + ""; if (!setuScore.containsKey(name)) { - setuScore.put(name+"|"+sender, i); + setuScore.put(name + "|" + sender, i); } } } catch (Exception ignored) { @@ -220,10 +232,14 @@ public class QQSetu extends Model { } @Override - public void onTime(Long qq,String time) { - super.onTime(qq,time); - if("23:59:00".equals(time)){ - printTodaySetu(); + public void onTime(Long qq, String time) { + super.onTime(qq, time); + if ("23:59:00".equals(time)) { + try { + printTodaySetu(); + } catch (Exception e) { + e.printStackTrace(); + } } } diff --git a/src/main/java/com/yutou/qqbot/utlis/ApplicationInit.java b/src/main/java/com/yutou/qqbot/utlis/ApplicationInit.java index 8ad6515..e46a861 100644 --- a/src/main/java/com/yutou/qqbot/utlis/ApplicationInit.java +++ b/src/main/java/com/yutou/qqbot/utlis/ApplicationInit.java @@ -1,17 +1,19 @@ 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.models.Model; -import net.mamoe.mirai.Bot; -import net.mamoe.mirai.contact.Group; +import lombok.val; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; +import java.util.List; import java.util.Timer; import java.util.TimerTask; @@ -35,7 +37,15 @@ public class ApplicationInit implements ApplicationRunner { for (Class model : Model.classList) { new Thread(() -> { try { - Bot bot = QQBotManager.getInstance().getBot(); + List groups = QQDatabase.getGroups(); + Model useModel = (Model) model.getDeclaredConstructor().newInstance(); + for (GroupBean group : groups) { + if (QQNumberManager.getManager().isUseModel(group.getGroupId(), model)) { + useModel.onTime(group.getGroupId(), time); + } + } + + /* Bot bot = QQBotManager.getInstance().getBot(); if (bot == null) { return; } @@ -44,7 +54,7 @@ public class ApplicationInit implements ApplicationRunner { if (QQNumberManager.getManager().isUseModel(group.getId(), model)) { useModel.onTime(group.getId(), time); } - } + }*/ } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/com/yutou/qqbot/utlis/BaiduGPTManager.java b/src/main/java/com/yutou/qqbot/utlis/BaiduGPTManager.java index 12388cb..c0b24d4 100644 --- a/src/main/java/com/yutou/qqbot/utlis/BaiduGPTManager.java +++ b/src/main/java/com/yutou/qqbot/utlis/BaiduGPTManager.java @@ -13,9 +13,10 @@ import java.util.Map; public class BaiduGPTManager { private static int MAX_MESSAGE = 5; private static BaiduGPTManager manager; - private static final String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions"; + 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 = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro"; + 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 = "36668599"; private static final String ApiKey = "eyHo6K2ILBm7i378701Az1eT"; private static final String SecretKey = "U4vXt8AOTM9FgB0Omft5IOh6vwhzoDgZ"; @@ -37,6 +38,14 @@ public class BaiduGPTManager { return MAX_MESSAGE; } + public void setModelFor40() { + url = url_4_0; + } + + public void setModelFor35() { + url = url_3_5; + } + public void clear() { msgMap.clear(); } @@ -67,7 +76,7 @@ public class BaiduGPTManager { 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); + , json.toJSONString().getBytes(StandardCharsets.UTF_8), 0, map); System.out.println("post = " + post); if (StringUtils.isEmpty(post)) { clear(); @@ -80,9 +89,12 @@ public class BaiduGPTManager { return response; } - public static void main(String[] args) throws Exception { - ResponseMessage message = BaiduGPTManager.getManager().sendMessage("test", "2023年创业什么赚钱?"); - System.out.println(message.getResult()); + 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", "你是那个版本的大模型?"); + System.out.println(message.getResult()); } } diff --git a/src/main/java/com/yutou/qqbot/utlis/Base64Tools.java b/src/main/java/com/yutou/qqbot/utlis/Base64Tools.java new file mode 100644 index 0000000..14c32fc --- /dev/null +++ b/src/main/java/com/yutou/qqbot/utlis/Base64Tools.java @@ -0,0 +1,38 @@ +package com.yutou.qqbot.utlis; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Base64; + +public class Base64Tools { + public static String encode(String str) { + return java.util.Base64.getEncoder().encodeToString(str.getBytes()); + } + + public static String decode(String str) { + return new String(java.util.Base64.getDecoder().decode(str)); + } + + public static String encode(byte[] bytes) { + return java.util.Base64.getEncoder().encodeToString(bytes); + } + + public static String encode(File file) { + try { + byte[] fileContent = Files.readAllBytes(Paths.get(file.getAbsolutePath())); + return encode(fileContent); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + public static void main(String[] args) { + File file=new File("遥遥领先.mp3"); + + String base64 = encode(file); + System.out.println(base64); + } +} diff --git a/src/main/java/com/yutou/qqbot/utlis/ConfigTools.java b/src/main/java/com/yutou/qqbot/utlis/ConfigTools.java index 99a6813..6a57c1b 100644 --- a/src/main/java/com/yutou/qqbot/utlis/ConfigTools.java +++ b/src/main/java/com/yutou/qqbot/utlis/ConfigTools.java @@ -14,6 +14,8 @@ public class ConfigTools { public static final String SQLITE = "sqlite.json"; public static final String BiliBili = "bilibili.cookie"; + private static final String SERVER_URL = load(CONFIG, "server.url", String.class); + static { try { File file = new File(CONFIG); @@ -45,7 +47,7 @@ public class ConfigTools { String src = readFile(file); if (src != null) { try { - JSONObject json = JSONObject.parseObject(src,JSONObject.class); + JSONObject json = JSONObject.parseObject(src, JSONObject.class); return json.getObject(key, t); } catch (Exception e) { e.printStackTrace(); @@ -60,10 +62,10 @@ public class ConfigTools { BufferedReader reader = new BufferedReader(new FileReader(file)); String tmp, str = null; while ((tmp = reader.readLine()) != null) { - if(tmp.startsWith(key+"=")){ - str=tmp.split("=")[1]; - if(StringUtils.isEmpty(str)){ - str=null; + if (tmp.startsWith(key + "=")) { + str = tmp.split("=")[1]; + if (StringUtils.isEmpty(str)) { + str = null; } break; } @@ -116,4 +118,8 @@ public class ConfigTools { } return null; } + + public static String getServerUrl() { + return SERVER_URL; + } } diff --git a/src/main/java/com/yutou/qqbot/utlis/FixProtocolVersion.java b/src/main/java/com/yutou/qqbot/utlis/FixProtocolVersion.java deleted file mode 100644 index c5cd31b..0000000 --- a/src/main/java/com/yutou/qqbot/utlis/FixProtocolVersion.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.yutou.qqbot.utlis; - -import net.mamoe.mirai.utils.BotConfiguration; - -import java.lang.reflect.Field; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Map; - -public class FixProtocolVersion { - public static void fix(){ - try { - - Class MiraiProtocolInternal = Class.forName("net.mamoe.mirai.internal.utils.MiraiProtocolInternal"); - Field field = MiraiProtocolInternal.getFields()[0]; - Object companion = field.get(Object.class); - - EnumMap protocols = (EnumMap)companion.getClass().getMethod("getProtocols$mirai_core").invoke(companion); - Object pad = protocols.get(BotConfiguration.MiraiProtocol.ANDROID_PAD); - /* - * apkId: String, - id: Long, - ver: String, - sdkVer: String, - miscBitMap: Int, - subSigMap: Int, - mainSigMap: Int, - sign: String, - buildTime: Long, - ssoVersion: Int, - canDoQRCodeLogin: Boolean = false, - * */ - Class padClass = pad.getClass(); - Map padData = new HashMap(){{ - put("id", 537152242); - put("ver", "8.9.35.10440"); - put("sdkVer", "6.0.0.2535"); - put("buildTime", 1676531414L); - }}; - for (Field f : padClass.getFields()) { - f.setAccessible(true); - if(padData.containsKey(f.getName())){ - f.set(pad, padData.get(f.getName())); - } - f.setAccessible(false); - } - - Object phone = protocols.get(BotConfiguration.MiraiProtocol.ANDROID_PHONE); - Map phoneData = new HashMap(){{ - put("id", 537153294); - put("ver", "8.9.35.10440"); - put("sdkVer", "6.0.0.2535"); - put("buildTime", 1676531414L); - }}; - for (Field f : padClass.getFields()) { - f.setAccessible(true); - if(padData.containsKey(f.getName())){ - f.set(phone, phoneData.get(f.getName())); - } - f.setAccessible(false); - } - - } catch (Exception e) { - e.printStackTrace(); - } - } -} - diff --git a/src/main/java/com/yutou/qqbot/utlis/RedisTools.java b/src/main/java/com/yutou/qqbot/utlis/RedisTools.java index 924a58a..7dafb6b 100644 --- a/src/main/java/com/yutou/qqbot/utlis/RedisTools.java +++ b/src/main/java/com/yutou/qqbot/utlis/RedisTools.java @@ -36,7 +36,7 @@ public class RedisTools { //Properties properties = PropertyUtil.loadProperties("jedis.properties"); //host = properties.getProperty("redis.host"); //port = Integer.valueOf(properties.getProperty("redis.port")); - host = "127.0.0.1"; + host = "localhost"; port = 6379; } @@ -411,6 +411,7 @@ public class RedisTools { } public static void main(String[] args) { - RedisTools.pullMsg("msg", "abc"); + // RedisTools.pullMsg("msg", "abc"); + RedisTools.set("test","abc"); } } diff --git a/src/test/java/com/yutou/qqbot/QqBotApplicationTests.java b/src/test/java/com/yutou/qqbot/QqBotApplicationTests.java index 37fe0fb..890947c 100644 --- a/src/test/java/com/yutou/qqbot/QqBotApplicationTests.java +++ b/src/test/java/com/yutou/qqbot/QqBotApplicationTests.java @@ -1,7 +1,11 @@ package com.yutou.qqbot; +import com.yutou.napcat.http.NapCatApi; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; @SpringBootTest class QqBotApplicationTests { @@ -10,5 +14,8 @@ class QqBotApplicationTests { void contextLoads() { //1 } + @Test + void sendMessage(){ + } }