first commit

master
Administrator 2024-05-01 20:03:20 +08:00
commit 6b1d76b8b2
19 changed files with 912 additions and 0 deletions

8
.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

8
.idea/modules.xml Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/week.iml" filepath="$PROJECT_DIR$/.idea/week.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

9
.idea/week.iml Normal file
View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="Go" enabled="true" />
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

7
Dockerfile Normal file
View File

@ -0,0 +1,7 @@
FROM alpine:latest
USER root
RUN apk --no-cache add tzdata
ENV TZ=Asia/Shanghai
COPY ai-week /usr/local/bin
RUN chmod +x /usr/local/bin/ai-week
ENTRYPOINT ["ai-week"]

42
cmd/main.go Normal file
View File

@ -0,0 +1,42 @@
package main
import (
"log"
"time"
"week/moonshot"
"week/qywechat"
"github.com/jasonlvhit/gocron"
)
var maxRetries = 3
func main() {
now := time.Now()
nowDate := now.Format("2006-01-02 15:04:05") + " " + now.Weekday().String()
log.Printf("等待执行定时任务中...当前时间是:%s", nowDate)
if maxRetries != 0 {
// 定义任务,每周五的五点执行
gocron.Every(1).Friday().At("17:00").Do(job)
// 开始定时任务
<-gocron.Start()
} else {
log.Fatalln("最大重试次数已到达3退出")
}
}
func job() {
err := moonshot.CreateExcel()
if err != nil {
job()
maxRetries--
}
repContent, err := moonshot.AiChat()
if err != nil {
job()
maxRetries--
}
qywechat.Send(repContent)
}

25
go.mod Normal file
View File

@ -0,0 +1,25 @@
module week
go 1.22.2
require (
github.com/PuerkitoBio/goquery v1.9.1
github.com/google/uuid v1.6.0
github.com/jasonlvhit/gocron v0.0.1
github.com/tidwall/gjson v1.17.1
github.com/xuri/excelize/v2 v2.8.1
)
require (
github.com/andybalholm/cascadia v1.3.2 // indirect
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/richardlehane/mscfb v1.0.4 // indirect
github.com/richardlehane/msoleps v1.0.3 // indirect
github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.0 // indirect
github.com/xuri/efp v0.0.0-20231025114914-d1ff6096ae53 // indirect
github.com/xuri/nfp v0.0.0-20230919160717-d98342af3f05 // indirect
golang.org/x/crypto v0.19.0 // indirect
golang.org/x/net v0.21.0 // indirect
golang.org/x/text v0.14.0 // indirect
)

98
go.sum Normal file
View File

@ -0,0 +1,98 @@
github.com/PuerkitoBio/goquery v1.9.1 h1:mTL6XjbJTZdpfL+Gwl5U2h1l9yEkJjhmlTeV9VPW7UI=
github.com/PuerkitoBio/goquery v1.9.1/go.mod h1:cW1n6TmIMDoORQU5IU/P1T3tGFunOeXEpGP2WHRwkbY=
github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss=
github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/go-redis/redis v6.15.5+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/jasonlvhit/gocron v0.0.1 h1:qTt5qF3b3srDjeOIR4Le1LfeyvoYzJlYpqvG7tJX5YU=
github.com/jasonlvhit/gocron v0.0.1/go.mod h1:k9a3TV8VcU73XZxfVHCHWMWF9SOqgoku0/QlY2yvlA4=
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw=
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/richardlehane/mscfb v1.0.4 h1:WULscsljNPConisD5hR0+OyZjwK46Pfyr6mPu5ZawpM=
github.com/richardlehane/mscfb v1.0.4/go.mod h1:YzVpcZg9czvAuhk9T+a3avCpcFPMUWm7gK3DypaEsUk=
github.com/richardlehane/msoleps v1.0.1/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
github.com/richardlehane/msoleps v1.0.3 h1:aznSZzrwYRl3rLKRT3gUk9am7T/mLNSnJINvN0AQoVM=
github.com/richardlehane/msoleps v1.0.3/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/tidwall/gjson v1.17.1 h1:wlYEnwqAHgzmhNUFfw7Xalt2JzQvsMx2Se4PcoFCT/U=
github.com/tidwall/gjson v1.17.1/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/xuri/efp v0.0.0-20231025114914-d1ff6096ae53 h1:Chd9DkqERQQuHpXjR/HSV1jLZA6uaoiwwH3vSuF3IW0=
github.com/xuri/efp v0.0.0-20231025114914-d1ff6096ae53/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI=
github.com/xuri/excelize/v2 v2.8.1 h1:pZLMEwK8ep+CLIUWpWmvW8IWE/yxqG0I1xcN6cVMGuQ=
github.com/xuri/excelize/v2 v2.8.1/go.mod h1:oli1E4C3Pa5RXg1TBXn4ENCXDV5JUMlBluUhG7c+CEE=
github.com/xuri/nfp v0.0.0-20230919160717-d98342af3f05 h1:qhbILQo1K3mphbwKh1vNm4oGezE1eF9fQWmNiIpSfI4=
github.com/xuri/nfp v0.0.0-20230919160717-d98342af3f05/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.19.0 h1:ENy+Az/9Y1vSrlrvBSyna3PITt4tiZLf7sgCjZBX7Wo=
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/image v0.14.0 h1:tNgSxAFe3jC4uYqvZdTr84SZoM1KfwdC9SKIFrLjFn4=
golang.org/x/image v0.14.0/go.mod h1:HUYqC05R2ZcZ3ejNQsIHQDQiwWM4JBqmm6MKANTp4LE=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns=
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

311
moonshot/function.go Normal file
View File

@ -0,0 +1,311 @@
package moonshot
import (
"bytes"
"encoding/json"
"fmt"
"github.com/PuerkitoBio/goquery"
"github.com/tidwall/gjson"
"io"
"log"
"mime/multipart"
"net/http"
"os"
"strings"
"week/tools"
"week/udesk"
)
//请求月之暗面所需要的常量
const (
MoonshotFileApiUrl = "https://api.moonshot.cn/v1/files/"
moonshotApiKey = "sk-DwKNLIVfGFi5CUocISixedd2kLcNzYVRFShbScKtbxMNOPkQ"
)
// 上传文件
func ReqMoonShotFileSendApi() *string {
filePath := "./周报.xlsx"
// 打开文件
file, err := os.Open(filePath)
if err != nil {
log.Printf("打开周报excel失败错误是:%v", err)
}
defer file.Close()
// 创建一个缓冲区
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
// 创建一个文件表单字段
part, err := writer.CreateFormFile("file", filePath)
if err != nil {
log.Printf("写文件缓存失败,错误是%v", err)
}
// 将文件内容拷贝到表单字段
_, err = io.Copy(part, file)
if err != nil {
log.Printf("拷贝文件到缓存失败,错误是%v", err)
}
// 添加其他表单字段
writer.WriteField("purpose", "file-extract")
// 完成表单写入
writer.Close()
// 创建 HTTP 请求
req, err := http.NewRequest("POST", MoonshotFileApiUrl, body)
if err != nil {
log.Printf("请求月之暗面api过程创建http请求失败错误是%s", err)
}
// 设置请求头
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("Authorization", "Bearer "+moonshotApiKey)
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Printf("请求月之暗面api过程请求失败错误是%s", err)
}
defer resp.Body.Close()
// 读取响应
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
log.Printf("请求月之暗面api过程读取响应失败错误是%s", err)
}
// 打印响应内容
fileId := gjson.Get(string(responseBody), "id").String()
log.Printf("文件上传成功你上传的文件id是%s", fileId)
return &fileId
}
// 删除文件
func ReqMoonShotFileDeleteApi(fileID *string) {
// 设置 API endpoint
url := fmt.Sprintf(MoonshotFileApiUrl + *fileID)
// 创建 HTTP 请求
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
log.Printf("调用月之暗面删除文件api过程创建http请求失败错误是%v", err)
return
}
// 设置请求头(如果需要的话)
req.Header.Set("Authorization", "Bearer "+moonshotApiKey)
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Printf("调用月之暗面删除文件api过程发送http请求失败错误是%v", err)
return
}
defer resp.Body.Close()
// 检查响应状态码
if resp.StatusCode == http.StatusOK {
log.Printf("请求月之暗面删除文件api成功~")
} else {
log.Println("请求月之暗面删除文件api失败>_<, http状态码是:", resp.StatusCode)
}
}
// 开启ai对话主函数
func AiChat() (string, error) {
fileId := ReqMoonShotFileSendApi()
contentStr := GetFileContent(fileId)
// 设置 API endpoint
url := "https://api.moonshot.cn/v1/chat/completions"
// 构造请求体
requestBody := map[string]interface{}{
"model": "moonshot-v1-128k",
"messages": []map[string]string{
{"role": "system", "content": contentStr},
{"role": "user", "content": "帮忙分析下工单中的错别字告诉我对应的工单id"},
},
"temperature": 0.2,
}
// 将请求体转换为 JSON 格式
jsonBody, err := json.Marshal(requestBody)
if err != nil {
log.Printf("开启会话过程将请求体转换为json格式失败错误是%v", err)
return "", err
}
// 创建 HTTP 请求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
if err != nil {
log.Printf("开启会话过程,创建请求失败,错误是:%v", err)
return "", err
}
// 设置请求头
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+moonshotApiKey)
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Printf("开启会话过程,发送请求失败,错误是:%v:", err)
return "", err
}
defer resp.Body.Close()
// 读取响应
responseBody := new(bytes.Buffer)
_, err = responseBody.ReadFrom(resp.Body)
if err != nil {
log.Printf("开启会话过程,读取响应失败,错误是:%v:", err)
return "", err
}
defer ReqMoonShotFileDeleteApi(fileId) //对话后清空文件
// 打印响应内容
jsonData := responseBody.String()
repFromAi := gjson.Get(jsonData, "choices.#.message.content").String()
repFromAi = strings.Replace(repFromAi, "\\n", "\n", -1)
repFromAi = strings.Replace(repFromAi, "\\", "", -1)
repFromAi = strings.Replace(repFromAi, "[", "", -1)
repFromAi = strings.Replace(repFromAi, "]", "", -1)
repFromAi = strings.Replace(repFromAi, "\"", "", 1)
log.Println(repFromAi)
return repFromAi, nil
}
// 获取文件内容
func GetFileContent(fileID *string) string {
// 设置 API endpoint
url := fmt.Sprintf(MoonshotFileApiUrl + *fileID + "/content")
// 创建 HTTP 请求
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Printf("月之暗面api获取文件内容过程创建http请求错误是%v:", err)
}
// 设置请求头
req.Header.Set("Authorization", "Bearer "+moonshotApiKey)
// 发送请求
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Printf("月之暗面api获取文件内容过程发送请求错误是%v", err)
}
defer resp.Body.Close()
// 读取响应内容
content, err := io.ReadAll(resp.Body)
if err != nil {
log.Printf("月之暗面api获取文件内容过程读取响应失败错误是%v", err)
}
contentStr := string(content)
// 打印文件内容
fmt.Println(contentStr)
return contentStr
}
// 根据工单id循环获取工单回复内容
func CreateExcel() error {
totalPages, err := udesk.GetUdeskTicketId()
if err != nil {
return err
}
id, err := udesk.LoopGetTicketId(totalPages)
if err != nil {
return err
}
contentMap := make(map[string][]string)
j := 1
for _, v := range id {
idUrl := fmt.Sprintf("https://servicecenter-alauda.udesk.cn/open_api_v1/tickets/%v/replies?", v)
repliesUrl := udesk.Geturlstring(idUrl)
resp, err := http.Get(repliesUrl)
if err != nil {
// 处理错误
log.Printf("获取工单过滤器下的回复信息失败,发送请求过程,错误是:%v\n", err)
return err
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
}
}(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
// 处理错误
log.Printf("获取工单过滤器下的回复信息失败,读取返回体过程,错误是:%v\n", err)
return err
}
jsonData := string(body)
repliesContent := gjson.Get(jsonData, "replies.#.content").String()
repliesContent = strings.Trim(repliesContent, "[]")
//repliesContent = trimHtml(repliesContent)
//查找回复内容和配图
doc, err := goquery.NewDocumentFromReader(strings.NewReader(repliesContent))
var s = make([]string, 0)
doc.Find("p,img").Each(func(i int, selection *goquery.Selection) {
imgSrc, exists := selection.Attr("src")
if exists {
s = append(s, imgSrc)
s = append(s, "\n")
}
s = append(s, selection.Text())
s = append(s, "\n")
})
//跳过没有回复内容的工单,即运维服务,减少给模型的错误条件
if len(s) == 0 {
continue
}
repliesContentSlice := tools.ReverseSlice(s)
cloudId := udesk.Id2CloudId(v)
log.Printf("正在处理map中的第%v个数据,键是%v\n", j, v)
if cloudId == "" {
contentMap[v] = repliesContentSlice
} else {
contentMap[cloudId] = repliesContentSlice
}
log.Printf("第%v个数据数据处理完成\n", j)
j++
}
log.Printf("所有回复数据处理完成,map中键的数量%v\n", len(contentMap))
//fmt.Printf("map的值:%v\n", contentMap) //回复内容的map待办将这个map中的建存储第一列将这个map中的值作为第二列存储
// 生成excel表格内容为id --> 回复内容
// 保存到某地
tools.CreateNewExcel(contentMap) //创建了excel
//sk-DwKNLIVfGFi5CUocISixedd2kLcNzYVRFShbScKtbxMNOPkQ
//卡点,如何根据文件内容获取回复,目前这个结构只能开启单轮对话
return nil
}

33
qywechat/send.go Normal file
View File

@ -0,0 +1,33 @@
package qywechat
import (
"bytes"
"log"
"net/http"
)
//企业微信机器人发送
const webhookURL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=7b50e0c4-8a35-4f29-b652-25e1d6142c2b"
func Send(repContent string) {
// 替换为你的企业微信机器人Webhook URL
// 创建消息体
requestBody := []byte(`{
"msgtype": "text",
"text": {
"content": "` + repContent + `"
}
}`)
// 发送HTTP POST请求到企业微信机器人Webhook
resp, err := http.Post(webhookURL, "application/json", bytes.NewBuffer(requestBody))
if err != nil {
log.Fatalf("Failed to send message: %v", err)
}
defer resp.Body.Close()
log.Println("Message sent successfully!")
}

14
run.sh Normal file
View File

@ -0,0 +1,14 @@
#!/usr/bin/env bash
#安装golang1.22.2
wget https://golang.google.cn/dl/go1.22.2.linux-amd64.tar.gz
tar -zxvf go1.22.2.linux-amd64.tar.gz -C /usr/local/
go env -w GO111MODULE=on
go env -w GOPROXY=https://goproxy.cn,direct
go version
#编译
cd ./cmd
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o ../ai-week
#镜像
docker build -t ai-week:v2 .
sleep 3
docker run --name week -d --restart always ai-week:v2

12
tools/algorithm.go Normal file
View File

@ -0,0 +1,12 @@
package tools
// 反转切片
func ReverseSlice(s []string) []string {
length := len(s)
reversed := make([]string, length)
for i, v := range s {
reversed[length-i-1] = v
}
return reversed
}

18
tools/checktime.go Normal file
View File

@ -0,0 +1,18 @@
package tools
import (
"fmt"
"time"
)
// 当前时间是否为周五5点
func CheckTime() bool {
nowTime := time.Now()
if nowTime.Weekday().String() == "Friday" && nowTime.Format("15:04:05") == "17:00:00" {
fmt.Println("当前时间是周五5点")
return true
} else {
fmt.Println("当前时间不是周五5点")
return false
}
}

44
tools/excel.go Normal file
View File

@ -0,0 +1,44 @@
package tools
import (
"fmt"
"github.com/xuri/excelize/v2"
"log"
"strconv"
)
//创建excel文件覆盖写即可
func CreateNewExcel(data map[string][]string) { // 示例的 map
// 创建一个新的 Excel 文件
f := excelize.NewFile()
// 设置工作表的名称
index, err := f.NewSheet("Sheet1")
if err != nil {
return
}
// 在第一行,第一列写入标题
f.SetCellValue("Sheet1", "A1", "工单id")
f.SetCellValue("Sheet1", "B1", "工单回复")
//遍历 map将键和值写入 Excel 表格
row := 2
for key, value := range data {
fmt.Println(row, key, value)
fmt.Println("A"+strconv.Itoa(row), "B"+strconv.Itoa(row))
f.SetCellValue("Sheet1", "A"+strconv.Itoa(row), key)
f.SetCellValue("Sheet1", "B"+strconv.Itoa(row), value)
row++
}
// 设置工作表为默认激活状态
f.SetActiveSheet(index)
// 保存 Excel 文件
if err := f.SaveAs("周报.xlsx"); err != nil {
log.Fatal(err)
}
}

35
udesk/base.go Normal file
View File

@ -0,0 +1,35 @@
package udesk
const (
Email = "hbqi@alauda.io"
Sign_version = "v2"
Password = "Ye_qiu@123"
Auth_token_url = "https://servicecenter-alauda.udesk.cn/open_api_v1/log_in"
)
//获取鉴权token的账号密码请求体对象
type RequestUdeskBody struct {
Email string `json:"email"`
Password string `json:"password"`
}
//udesk鉴权接口返回token对象
type UdeskToken struct {
Code string `json:"code"`
Open_api_auth_token string `json:"open_api_auth_token"`
}
// 定义认证对象
type Authobj struct {
Email,
Timestamp,
Sign,
Nonce,
Sign_version string
}
//全局声明返回体对象
var u = newRespUdeskBody()

188
udesk/function.go Normal file
View File

@ -0,0 +1,188 @@
package udesk
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/google/uuid"
"github.com/tidwall/gjson"
"io"
"log"
"net/http"
"strconv"
"strings"
"time"
)
//新建请求体对象
func newReqUdeskToken() RequestUdeskBody {
return RequestUdeskBody{
Email: Email,
Password: Password,
}
}
// 新建返回体对象
func newRespUdeskBody() UdeskToken {
return UdeskToken{
Code: "",
Open_api_auth_token: "",
}
}
//获取Unix时间戳
func GetTimeStamp() string {
return strconv.FormatInt(time.Now().Unix(), 10)
}
//获取nonce
func GetNonce() string {
randomUUID := uuid.New()
nonce := randomUUID.String()
return nonce
}
// sha256转换函数
func calculateSHA256(input string) string {
// 将字符串转换为字节数组
inputBytes := []byte(input)
// 创建SHA-256哈希对象
hasher := sha256.New()
// 将字节数组写入哈希对象
hasher.Write(inputBytes)
// 计算哈希值并返回
hashInBytes := hasher.Sum(nil)
hashString := hex.EncodeToString(hashInBytes)
return hashString
}
// 获取鉴权token对象
func GetUdeskAuthToken() UdeskToken {
reqBody := newReqUdeskToken()
jsonData, err := json.Marshal(reqBody)
if err != nil {
fmt.Printf("获取udesk管理员token过程中转换请求体json失败错误是%v", err)
}
payload := bytes.NewBufferString(string(jsonData))
resp, err := http.Post(Auth_token_url, "application/json", payload)
if err != nil {
fmt.Printf("获取udesk管理员token过程中请求获取token接口失败错误是%v", err)
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
return
}
}(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("获取udesk管理员token过程中获取token接口响应失败错误是%v", err)
}
json.Unmarshal(body, &u)
return u
}
//把udeskid转换为cloudid
func Id2CloudId(id string) string {
detailUrl := Geturlstring("https://servicecenter-alauda.udesk.cn/open_api_v1/tickets/detail?") + "&id=" + id
resp, err := http.Get(detailUrl)
if err != nil {
// 处理错误
log.Printf("获取工单过滤器下的cloudid失败发送请求过程错误是%v", err)
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
}
}(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
// 处理错误
log.Printf("获取工单过滤器下的cloudid失败读取返回体过程错误是%v", err)
}
jsonData := string(body)
cloudId := gjson.Get(jsonData, "ticket.custom_fields.TextField_219254").String()
return cloudId
}
//* 获取工单过滤器下的符合条件的工单id *
// 获取工单总共的页数
func GetUdeskTicketId() (*int64, error) {
filterUrl := Geturlstring("https://servicecenter-alauda.udesk.cn/open_api_v1/tickets/tickets_in_filter?filter_id=16523464&")
resp, err := http.Get(filterUrl)
if err != nil {
// 处理错误
log.Printf("获取工单过滤器下的工单信息失败,发送请求过程,错误是:%v", err)
return nil, err
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
}
}(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
// 处理错误
log.Printf("获取工单过滤器下的工单信息失败,读取返回体过程,错误是:%v", err)
return nil, err
}
jsonData := string(body)
//fmt.Println(jsonData)
totalPages := gjson.Get(jsonData, "meta.total_pages").Int()
return &totalPages, nil
}
// 根据上面获取的页数,分别请求接口取到工单id切片
func LoopGetTicketId(totalPages *int64) ([]string, error) {
var idSlice = make([]string, 0)
for i := int64(1); i <= *totalPages; i++ {
getIdUrl := Geturlstring("https://servicecenter-alauda.udesk.cn/open_api_v1/tickets/tickets_in_filter?filter_id=16523464&") + "&page=" + strconv.FormatInt(i, 10)
resp, err := http.Get(getIdUrl)
if err != nil {
// 处理错误
log.Printf("获取工单过滤器下的工单id失败发送请求过程错误是%v", err)
return nil, err
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Printf("获取工单过滤器下的工单id失败关闭返回体错误是%v", err)
}
}(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
// 处理错误
log.Printf("获取工单过滤器下的工单id失败读取返回体过程错误是%v", err)
return nil, err
}
jsonData := string(body)
ticketIdstr := gjson.Get(jsonData, "contents.#.ticket.id").String()
sliceStr := strings.Trim(ticketIdstr, "[]")
numbers := strings.Split(sliceStr, ",")
log.Printf("处理id切片中...第%v次处理...\n", i)
idSlice = append(idSlice, numbers...)
log.Printf("%T,%v", idSlice, idSlice)
}
log.Println("处理完成~owo~")
return idSlice, nil
}

17
udesk/geturl.go Normal file
View File

@ -0,0 +1,17 @@
package udesk
import "strings"
//最终请求的url后缀拼接
func Geturlstring(url string) string {
var authobj = u.getAuthobj() //必须要同步处理timestamp和sign的关系否则会鉴权失败所以从同一个结构体中取值
var builder strings.Builder
builder.WriteString(url)
builder.WriteString("email=" + authobj.Email)
builder.WriteString("&timestamp=" + authobj.Timestamp)
builder.WriteString("&sign=" + authobj.Sign)
builder.WriteString("&nonce=" + authobj.Nonce)
builder.WriteString("&sign_version=" + authobj.Sign_version)
return builder.String()
}

37
udesk/method.go Normal file
View File

@ -0,0 +1,37 @@
package udesk
import (
"strings"
)
//获取token字符串
func (UdeskToken) getTokenString() string {
token := GetUdeskAuthToken().Open_api_auth_token
return token
}
//计算sign并返回authobj
func (UdeskToken) getAuthobj() Authobj {
token := u.getTokenString()
timestamp := GetTimeStamp()
nonce := GetNonce()
var builder strings.Builder
builder.WriteString(Email + "&")
builder.WriteString(token + "&")
builder.WriteString(timestamp + "&")
builder.WriteString(nonce + "&")
builder.WriteString(Sign_version)
str2sha256 := builder.String()
hashResult := calculateSHA256(str2sha256)
//fmt.Println(str2sha256)
return Authobj{
Email: Email,
Timestamp: timestamp,
Sign: hashResult,
Nonce: nonce,
Sign_version: Sign_version,
}
}

BIN
周报.xlsx Normal file

Binary file not shown.