This commit is contained in:
Leo
2025-04-04 15:10:00 +08:00
parent 2f87f4a38a
commit f5715aa683
3 changed files with 199 additions and 101 deletions

View File

@@ -53,7 +53,7 @@ public enum WXReqType {
GET_MP_LIST("Q0007", "获取公众号列表"),
GET_GROUP_MEMBER_LIST("Q0008", "获取群成员列表"),
SEND_CHAT_RECORD("Q0009", "发送聊天记录"),
SEND_IMAGE("Q0010", "发送图片"),
SEND_IMAGE("sendImage", "发送图片"),
SEND_LOCAL_FILE("Q0011", "发送本地文件"),
SEND_SHARE_LINK("Q0012", "发送分享链接"),
SEND_MINIPROGRAM("Q0013", "发送小程序"),

View File

@@ -30,6 +30,9 @@ import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
@@ -48,6 +51,7 @@ import static cn.van.business.util.JDUtil.UserInteractionState.ProcessState.DISI
import static cn.van.business.util.JDUtil.UserInteractionState.ProcessState.INIT;
import static cn.van.business.util.JDUtil.UserInteractionState.ProductOrderStep.*;
import static cn.van.business.util.WXUtil.super_admins;
import java.net.URL;
/**
* @author Leo
@@ -664,10 +668,16 @@ public class JDUtil {
case PRODUCT_PROMOTION:
if ("content".equals(state.getCurrentField())) {
// 第一次输入文案,直接生成内容
List<String> messages = generatePromotionContent(message); // 不需要图片和SKU名称
HashMap<String, List<String>> messagesAll = generatePromotionContent(message);
List<String> messages = messagesAll.get("text") ;// 不需要图片和SKU名称
for (String s : messages) {
wxUtil.sendTextMessage(fromWxid, s, 1, fromWxid);
}
if (messagesAll.get("image") != null){
for (String s : messagesAll.get("image")) {
wxUtil.sendImageMessage(fromWxid, s);
}
}
// 询问是否需要继续转链
state.setCurrentField("confirm");
@@ -841,13 +851,17 @@ public class JDUtil {
* @param message 文案内容,包含商品链接
* @return 处理后的文案,附带商品信息
*/
public List<String> generatePromotionContent(String message) {
List<String> results = new ArrayList<>();
public HashMap<String, List<String>> generatePromotionContent(String message) {
HashMap<String, List<String>> finallMessage = new HashMap<>();
List<String> textList = new ArrayList<>();
List<String> imagesList = new ArrayList<>();
// 提取文案中的所有 u.jd.com 链接
List<String> urls = extractUJDUrls(message);
if (urls.isEmpty()) {
results.add("文案中未找到有效的商品链接,请检查格式是否正确。");
return results;
textList.add("文案中未找到有效的商品链接,请检查格式是否正确。");
finallMessage.put("text", textList);
return finallMessage;
}
@@ -1091,6 +1105,7 @@ public class JDUtil {
// 如果需要图片和SKU名称则代表要把图片下载发过去还有对应的skuName
StringBuilder couponInfo = new StringBuilder();
ArrayList<HashMap<String, String>> resultList = new ArrayList<>();
for (String url : urls) {
try {
// 查询商品信息
@@ -1138,19 +1153,21 @@ public class JDUtil {
int index = 1;
for (UrlInfo image : productInfo.getData()[0].getImageInfo().getImageList()) {
images.append("图片 ").append(index++).append("\n").append(image.getUrl()).append("\n");
imagesList.add(image.getUrl());
}
}
results.add(String.valueOf(images));
textList.add(String.valueOf(images));
resultList.add(itemMap);
}
results.add(String.valueOf(couponInfo));
textList.add(String.valueOf(couponInfo));
} catch (Exception e) {
logger.error("处理商品链接时发生异常:{}", url, e);
couponInfo.append(" 处理商品链接时发生异常:").append(url).append("\n");
results.add(String.valueOf(couponInfo));
textList.add(String.valueOf(couponInfo));
finallMessage.put("text", textList);
}
}
StringBuilder wenan = new StringBuilder().append("文案生成: \n");
@@ -1161,12 +1178,28 @@ public class JDUtil {
}
results.add(String.valueOf(wenan));
textList.add(String.valueOf(wenan));
return results;
finallMessage.put("text", textList);
finallMessage.put("images", imagesList);
return finallMessage;
}
private String downloadImage(String imageUrl, String destinationFile) {
try (BufferedInputStream in = new BufferedInputStream(new URL(imageUrl).openStream());
FileOutputStream fileOutputStream = new FileOutputStream(destinationFile)) {
byte[] dataBuffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
fileOutputStream.write(dataBuffer, 0, bytesRead);
}
return destinationFile;
} catch (IOException e) {
logger.error("Error downloading image from URL: {}", imageUrl, e);
return null;
}
}
/**
* 提取文案中的所有 u.jd.com 链接
*

View File

@@ -14,8 +14,11 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
@@ -27,45 +30,11 @@ import java.util.*;
@Component
public class WXUtil {
private static final Logger logger = LoggerFactory.getLogger(WXUtil.class);
public static final String default_super_admin_wxid = "wxid_ytpc72mdoskt22";
private static final Logger logger = LoggerFactory.getLogger(WXUtil.class);
public static String default_bot_wxid = "wxid_kr145nk7l0an31";
public static Map<String, SuperAdmin> super_admins = new HashMap<>();
public static Map<String, String> jdidToWxidMap = new HashMap<>();
private final WxtsUtil wxTsUtil;
private final MessageProducerService messageProducerService;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SuperAdmin {
private String wxid;
private String name;
// 联盟ID
private String unionId;
private String appKey;
private String secretKey;
}
// 初始化超级管理员
public void initSuperAdmins() {
SuperAdmin admin1 = new SuperAdmin("wxid_ytpc72mdoskt22", "", "2014264913", "98e21c89ae5610240ec3f5f575f86a59", "3dcb6b23a1104639ac433fd07adb6dfb");
super_admins.put(admin1.getWxid(), admin1);
jdidToWxidMap.put(admin1.getUnionId(), admin1.getWxid());
SuperAdmin admin2 = new SuperAdmin("wxid_yneqf1implxu12", "", "2025353364", "e3c161242c8a1416fada5b5564d7ee70", "41ae9aabf03b41e6ba309682e36b323e");
super_admins.put(admin2.getWxid(), admin2);
jdidToWxidMap.put(admin2.getUnionId(), admin2.getWxid());
//wxTsUtil.sendNotify("initSuperAdmins 初始化完成");
//发送通知到微信
sendTextMessage(default_super_admin_wxid,"Jarvis 重启完成 [亲亲][亲亲][亲亲] ", 1, default_super_admin_wxid);
}
public static String getWxidFromJdid(String jdid) {
return jdidToWxidMap.get(jdid);
}
/**
* url http://127.0.0.1:7777/DaenWxHook/httpapi/
* 获取微信列表 (X0000)
@@ -97,9 +66,11 @@ public class WXUtil {
* 发送名片(Q0025)
*/
public static String WX_BASE_URL;
private final WxtsUtil wxTsUtil;
private final MessageProducerService messageProducerService;
public int sendTimes = 0;
private Environment env;
@Autowired
public WXUtil(Environment env, WxtsUtil wxTsUtil, @Lazy MessageProducerService messageProducerService) {
this.messageProducerService = messageProducerService;
@@ -110,6 +81,36 @@ public class WXUtil {
initSuperAdmins();
}
public static String getWxidFromJdid(String jdid) {
return jdidToWxidMap.get(jdid);
}
public static List<String> splitStringByLength(String input, int length) {
List<String> result = new ArrayList<>();
// 循环增加长度直到超过字符串长度
for (int start = 0; start < input.length(); start += length) {
// 截取字符串,但需要检查边界
int end = Math.min(start + length, input.length());
result.add(input.substring(start, end));
}
return result;
}
// 初始化超级管理员
public void initSuperAdmins() {
SuperAdmin admin1 = new SuperAdmin("wxid_ytpc72mdoskt22", "", "2014264913", "98e21c89ae5610240ec3f5f575f86a59", "3dcb6b23a1104639ac433fd07adb6dfb");
super_admins.put(admin1.getWxid(), admin1);
jdidToWxidMap.put(admin1.getUnionId(), admin1.getWxid());
SuperAdmin admin2 = new SuperAdmin("wxid_yneqf1implxu12", "", "2025353364", "e3c161242c8a1416fada5b5564d7ee70", "41ae9aabf03b41e6ba309682e36b323e");
super_admins.put(admin2.getWxid(), admin2);
jdidToWxidMap.put(admin2.getUnionId(), admin2.getWxid());
//wxTsUtil.sendNotify("initSuperAdmins 初始化完成");
//发送通知到微信
sendTextMessage(default_super_admin_wxid, "Jarvis 重启完成 [亲亲][亲亲][亲亲] ", 1, default_super_admin_wxid);
}
// 获取微信列表
public JSONObject getWxList() {
WxReqDate wxReqDate = createWxReqData(WXReqType.GET_WX_LIST);
@@ -122,17 +123,6 @@ public class WXUtil {
}
public static List<String> splitStringByLength(String input, int length) {
List<String> result = new ArrayList<>();
// 循环增加长度直到超过字符串长度
for (int start = 0; start < input.length(); start += length) {
// 截取字符串,但需要检查边界
int end = Math.min(start + length, input.length());
result.add(input.substring(start, end));
}
return result;
}
// 发送文本消息 msgType 1:私聊 2:群发
public void sendTextMessage(String wxid, String content, Integer msgType, String fromwxid) {
// 全部打印
@@ -159,9 +149,8 @@ public class WXUtil {
//botWxid = wxBotInfo.getString("wxid");
//
////
//WxReqDate wxReqDate = createWxReqData(WXReqType.SEND_TEXT_MESSAGE);
JSONObject jsonObject = new JSONObject();
jsonObject.put("type", WXReqType.SEND_TEXT_MESSAGE.getType());
WxReqDate wxReqDate = createWxReqData(WXReqType.SEND_TEXT_MESSAGE);
JSONObject data = new JSONObject();
//if ((msgType.equals(1))) {
// jsonObject.put("wxid", wxid);
// content = content;
@@ -176,43 +165,37 @@ public class WXUtil {
"wxid": "filehelper",
"msg": "666大佬~"
}*/
JSONObject data = new JSONObject();
data.put("msg", string);
data.put("wxid", wxid);
jsonObject.put("data", data);
wxReqDate.setData(data);
// wxReqDate 转成 JSONObject
JSONObject message = JSON.parseObject(JSON.toJSONString(wxReqDate));
//System.out.println(JSON.toJSONString(jsonObject));
//wxReqDate.setData(jsonObject);
if (Util.isNotEmpty(wxid)) {
// 把消息发送到RocketMQ使用'wx-message'作为topicjsonObject作为消息内容。
messageProducerService.sendMessage(jsonObject);
messageProducerService.sendMessage(message);
}
}
}
public void sendImageMessage(String wxid, String imagePath){
WxReqDate wxReqDate = createWxReqData(WXReqType.SEND_IMAGE);
JSONObject data = new JSONObject();
data.put("wxid", wxid);
data.put("path", imagePath);
String[] split = imagePath.split("/");
data.put("fileName", split[split.length - 1]);
wxReqDate.setData(data);
JSONObject message = JSON.parseObject(JSON.toJSONString(wxReqDate));
//private JSONObject sendWxReq(WxReqDate wxReqDate) {
// if (wxReqDate == null) {
// return null;
// } else {
// logger.info("wxReqDate: {}", wxReqDate);
//
// String responseStr = HttpRequest.post(WX_BASE_URL).body(JSON.toJSONString(wxReqDate)).execute().body();
// if (ObjectUtil.isNotEmpty(responseStr)) {
// JSONObject jsonObject = JSON.parseObject(responseStr);
// //WxResponse wxResponse = JSON.parseObject(responseStr, WxResponse.class);
// //System.out.println(wxResponse);
// //if (Objects.equals(String.valueOf(wxResponse.getCode()), "200")) {
// // return wxResponse.getData();
// //}
// //JSONObject jsonObject = HttpUtil.sendPost(url, wxReqDate.getData());
// return jsonObject;
// }
// }
//
// return null;
// }
//}
if (Util.isNotEmpty(wxid)) {
// 把消息发送到RocketMQ使用'wx-message'作为topicjsonObject作为消息内容。
messageProducerService.sendMessage(message);
}
}
/**
* {
@@ -244,6 +227,29 @@ public class WXUtil {
}
//private JSONObject sendWxReq(WxReqDate wxReqDate) {
// if (wxReqDate == null) {
// return null;
// } else {
// logger.info("wxReqDate: {}", wxReqDate);
//
// String responseStr = HttpRequest.post(WX_BASE_URL).body(JSON.toJSONString(wxReqDate)).execute().body();
// if (ObjectUtil.isNotEmpty(responseStr)) {
// JSONObject jsonObject = JSON.parseObject(responseStr);
// //WxResponse wxResponse = JSON.parseObject(responseStr, WxResponse.class);
// //System.out.println(wxResponse);
// //if (Objects.equals(String.valueOf(wxResponse.getCode()), "200")) {
// // return wxResponse.getData();
// //}
// //JSONObject jsonObject = HttpUtil.sendPost(url, wxReqDate.getData());
// return jsonObject;
// }
// }
//
// return null;
// }
//}
public WxReqDate createWxReqData(WXReqType wxReqType) {
WxReqDate wxReqDate = new WxReqDate(wxReqType.getType(), null);
@@ -251,6 +257,79 @@ public class WXUtil {
return wxReqDate;
}
@Scheduled(cron = "0 * * * * ?")
public void checkWxStatus() {
WxReqDate wxReqDate = createWxReqData(WXReqType.GET_WX_STATUS);
JSONObject data = new JSONObject();
data.put("wxid", default_bot_wxid);
wxReqDate.setData(data);
String responseStr = HttpRequest.post(WX_BASE_URL).body(JSON.toJSONString(wxReqDate)).execute().body();
if (ObjectUtil.isNotEmpty(responseStr)) {
JSONObject jsonObject = JSON.parseObject(responseStr);
/**
* {
* "code": 200,
* "msg": "正常",
* "result": {
* "startTimeStamp": "1716467892",
* "startTime": "2024年5月23日20时38分12秒",
* "runTime": "3分10秒",
* "recv": 0,
* "send": 0,
* "wxNum": "DaenPro",
* "nick": "小鹿\\uD83D\\uDE00\\uD83D\\uDE00摸",
* "wxid": "wxid_nq6r0w9v12612"
* },
* "wxid": "wxid_nq6r0w9v12612",
* "port": 7799,
* "pid": 18892,
* "flag": "7888",
* "timestamp": "1716468082967"
* }
* */
Integer code = jsonObject.getInteger("code");
if (code == 500) {
if (sendTimes > 3) {
return;
}
wxTsUtil.sendCriticalAlert("微信状态异常", jsonObject.getString("msg"));
sendTimes++;
} else if (code == 200) {
sendTimes = 0;
}
} else {
// 新建格式化日期
DateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
wxTsUtil.sendCriticalAlert("千寻框架状态异常", dateFormat.format(new Date()));
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
private static class WxReqDate {
//{
// "type": "X0000",
// "data": {}
//}
private String type;
private JSONObject data;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SuperAdmin {
private String wxid;
private String name;
// 联盟ID
private String unionId;
private String appKey;
private String secretKey;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@@ -277,18 +356,4 @@ public class WXUtil {
private String timestamp;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
private static class WxReqDate {
//{
// "type": "X0000",
// "data": {}
//}
private String type;
private JSONObject data;
}
}