Browse Source

fix:edit send_msg.go

jimmyyem 7 months ago
parent
commit
fe9a72ff0c
1 changed files with 50 additions and 11 deletions
  1. 50 11
      crontask/send_msg.go

+ 50 - 11
crontask/send_msg.go

@@ -1,11 +1,15 @@
 package crontask
 
 import (
+	"encoding/json"
+	"net/url"
+	"path"
 	"strings"
 	"time"
 	"wechat-api/ent"
 	"wechat-api/ent/batchmsg"
 	"wechat-api/ent/contact"
+	"wechat-api/ent/custom_types"
 	"wechat-api/ent/label"
 	"wechat-api/ent/labelrelationship"
 	"wechat-api/ent/msg"
@@ -64,19 +68,37 @@ func (l *CronTask) sendMsg() {
 				}
 			}
 
+			// 这里是待插入到 msg 表的数据
 			msgs := make([]*ent.MsgCreate, 0)
 
-			for _, user := range userlist {
-
-				msg := l.svcCtx.DB.Msg.Create().
-					SetNotNilFromwxid(&batch.Fromwxid).
-					SetNotNilToid(&user.Wxid).
-					SetMsgtype(1).
-					SetNotNilMsg(&batch.Msg).
-					SetStatus(0).
-					SetNotNilBatchNo(&batch.BatchNo)
+			// 这里是把 batch.Msg 转换为 json 数组
+			msgArray := make([]custom_types.Action, 0)
+			err := json.Unmarshal([]byte(batch.Msg), &msgArray)
+			l.Logger.Infof("msgArray length= %v, err:%v", len(msgArray), err)
+			if err != nil {
+				// json 解析失败
+				msgArray = make([]custom_types.Action, 0)
+			}
 
-				msgs = append(msgs, msg)
+			for _, user := range userlist {
+				// 这里改动主要是 batch_msg 目前支持批量添加图文,导致 batch_msg 的 msg 字段为 json
+				// msg 里包括文字和图片,msgtype=1 为文字, msgtype=2 为图片
+				// 每一条文字或者图片 都是一条单独的消息
+
+				if len(msgArray) > 0 {
+					// 这里是新格式(msg内容为json),需要遍历数组
+					for _, msgItem := range msgArray {
+						msgRow := l.svcCtx.DB.Msg.Create().
+							SetNotNilFromwxid(&batch.Fromwxid).
+							SetNotNilToid(&user.Wxid).
+							SetMsgtype(int32(msgItem.Type)).
+							SetNotNilMsg(&msgItem.Content).
+							SetStatus(0).
+							SetNotNilBatchNo(&batch.BatchNo)
+
+						msgs = append(msgs, msgRow)
+					}
+				}
 			}
 
 			if len(msgs) > 0 {
@@ -128,7 +150,15 @@ func (l *CronTask) sendMsg() {
 
 		//循环发送消息
 		for _, msg := range msglist {
-			err = hookClient.SendTextMsg(msg.Toid, msg.Msg)
+			// 这里之前只有文字消息(既 msgtype=1) 目前增加了图片 所以增加了msgtype=2
+			// 所以增加了一个判断,判断发送的内容类型,如果是文字就调用SendTextMsg,如果是图片就调用SendPicMsg
+			if msg.Msgtype == 1 {
+				err = hookClient.SendTextMsg(msg.Toid, msg.Msg)
+			} else {
+				diyfilename := getFileName(msg.Msg)
+				err = hookClient.SendPicMsg(msg.Toid, msg.Msg, diyfilename)
+			}
+
 			// 每次发完暂停1秒
 			time.Sleep(time.Second)
 			if err != nil {
@@ -174,3 +204,12 @@ func (l *CronTask) sendMsg() {
 	}
 
 }
+
+// 根据URL获取图片名
+func getFileName(photoUrl string) string {
+	u, err := url.Parse(photoUrl)
+	if err != nil {
+		return ""
+	}
+	return path.Base(u.Path)
+}