1
0
mirror of https://github.com/Mrs4s/go-cqhttp.git synced 2025-06-30 20:03:24 +00:00

Compare commits

...

7 Commits

Author SHA1 Message Date
1843bd6a4e fix reconnect loop on account banned. 2021-01-06 22:08:02 +08:00
938ebf630f update doc. 2021-01-06 21:43:55 +08:00
2bbf969cfa feature download_file. 2021-01-06 21:27:07 +08:00
416a3460ab Merge pull request #541 from wdvxdr1123/patch-2
fix reconnect
2021-01-06 21:00:21 +08:00
f98c334089 fix reconnect 2021-01-06 12:46:10 +08:00
0e5276ea4d fix ptt. 2021-01-06 02:38:21 +08:00
6113eb9200 update MiraiGo. 2021-01-06 02:36:56 +08:00
10 changed files with 136 additions and 17 deletions

View File

@ -1,9 +1,12 @@
package coolq
import (
"crypto/md5"
"encoding/hex"
"io/ioutil"
"os"
"path"
"path/filepath"
"runtime"
"strconv"
"strings"
@ -741,6 +744,25 @@ func (bot *CQBot) CQGetImage(file string) MSG {
}
}
func (bot *CQBot) CQDownloadFile(url string, headers map[string]string, threadCount int) MSG {
hash := md5.Sum([]byte(url))
file := path.Join(global.CACHE_PATH, hex.EncodeToString(hash[:])+".cache")
if global.PathExists(file) {
if err := os.Remove(file); err != nil {
log.Warnf("删除缓存文件 %v 时出现错误: %v", file, err)
return Failed(100, "DELETE_FILE_ERROR", err.Error())
}
}
if err := global.DownloadFileMultiThreading(url, file, 0, threadCount, headers); err != nil {
log.Warnf("下载链接 %v 时出现错误: %v", url, err)
return Failed(100, "DOWNLOAD_FILE_ERROR", err.Error())
}
abs, _ := filepath.Abs(file)
return OK(MSG{
"file": abs,
})
}
func (bot *CQBot) CQGetForwardMessage(resId string) MSG {
m := bot.Client.GetForwardMessage(resId)
if m == nil {

View File

@ -5,7 +5,6 @@ import (
"encoding/gob"
"fmt"
"hash/crc32"
"io/ioutil"
"os"
"path"
"runtime/debug"
@ -150,8 +149,8 @@ func (bot *CQBot) SendGroupMessage(groupId int64, m *message.SendingMessage) int
newElem = append(newElem, gm)
continue
}
if i, ok := elem.(*LocalVoiceElement); ok {
gv, err := bot.Client.UploadGroupPtt(groupId, i.Stream)
if i, ok := elem.(*message.VoiceElement); ok {
gv, err := bot.Client.UploadGroupPtt(groupId, bytes.NewReader(i.Data))
if err != nil {
log.Warnf("警告: 群 %v 消息语音上传失败: %v", groupId, err)
continue
@ -270,13 +269,8 @@ func (bot *CQBot) SendPrivateMessage(target int64, m *message.SendingMessage) in
bot.Client.SendFriendPoke(i.Target)
return 0
}
if i, ok := elem.(*LocalVoiceElement); ok {
data, err := ioutil.ReadAll(i.Stream)
if err != nil {
log.Warnf("警告: 好友 %v 消息语音读取失败: %v", target, err)
continue
}
fv, err := bot.Client.UploadPrivatePtt(target, data)
if i, ok := elem.(*message.VoiceElement); ok {
fv, err := bot.Client.UploadPrivatePtt(target, i.Data)
if err != nil {
log.Warnf("警告: 好友 %v 消息语音上传失败: %v", target, err)
continue

View File

@ -833,7 +833,7 @@ func (bot *CQBot) makeImageElem(d map[string]string, group bool) (message.IMessa
_ = os.Remove(cacheFile)
}
thread, _ := strconv.Atoi(c)
if err := global.DownloadFileMultiThreading(f, cacheFile, maxImageSize, thread); err != nil {
if err := global.DownloadFileMultiThreading(f, cacheFile, maxImageSize, thread, nil); err != nil {
return nil, err
}
return &LocalImageElement{File: cacheFile}, nil

View File

@ -760,6 +760,46 @@ Type: `tts`
| `remain_at_all_count_for_group` | int16 | 群内所有管理当天剩余@全体成员次数 |
| `remain_at_all_count_for_uin` | int16 | BOT当天剩余@全体成员次数 |
### 下载文件到缓存目录
终结点: `/download_file`
**参数**
| 字段 | 类型 | 说明 |
| ---------- | ------ | ------------------------- |
| `url` | string | 链接地址 |
| `thread_count` | int32 | 下载线程数 |
| `headers` | string or array | 自定义请求头 |
**`headers`格式:**
字符串:
```
User-Agent=YOUR_UA[\r\n]Referer=https://www.baidu.com
```
> `[\r\n]` 为换行符, 使用http请求时请注意编码
JSON数组:
```
[
"User-Agent=YOUR_UA",
"Referer=https://www.baidu.com",
]
```
**响应数据**
| 字段 | 类型 | 说明 |
| ---------- | ---------- | ------------ |
| `file` | string | 下载文件的*绝对路径* |
> 通过这个API下载的文件能直接放入CQ码作为图片或语音发送
> 调用后会阻塞直到下载完成后才会返回数据,请注意下载大文件时的超时
### 获取用户VIP信息
终结点:`/_get_vip_info`

View File

@ -99,7 +99,7 @@ func DownloadFile(url, path string, limit int64) error {
return nil
}
func DownloadFileMultiThreading(url, path string, limit int64, threadCount int) error {
func DownloadFileMultiThreading(url, path string, limit int64, threadCount int, headers map[string]string) error {
if threadCount < 2 {
return DownloadFile(url, path, limit)
}
@ -128,6 +128,11 @@ func DownloadFileMultiThreading(url, path string, limit int64, threadCount int)
if err != nil {
return err
}
if headers != nil {
for k, v := range headers {
req.Header.Set(k, v)
}
}
req.Header.Set("range", "bytes=0-")
resp, err := client.Do(req)
if err != nil {
@ -184,6 +189,11 @@ func DownloadFileMultiThreading(url, path string, limit int64, threadCount int)
_, _ = file.Seek(block.BeginOffset, io.SeekStart)
writer := bufio.NewWriter(file)
defer writer.Flush()
if headers != nil {
for k, v := range headers {
req.Header.Set(k, v)
}
}
req.Header.Set("range", "bytes="+strconv.FormatInt(block.BeginOffset, 10)+"-"+strconv.FormatInt(block.EndOffset, 10))
resp, err := client.Do(req)
if err != nil {

2
go.mod
View File

@ -3,7 +3,7 @@ module github.com/Mrs4s/go-cqhttp
go 1.15
require (
github.com/Mrs4s/MiraiGo v0.0.0-20210104171920-510924ba979c
github.com/Mrs4s/MiraiGo v0.0.0-20210105173234-72521dec9b56
github.com/dustin/go-humanize v1.0.0
github.com/gin-contrib/pprof v1.3.0
github.com/gin-gonic/gin v1.6.3

6
go.sum
View File

@ -1,9 +1,7 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Mrs4s/MiraiGo v0.0.0-20210104164708-e94ea61cc8e9 h1:jzaBgDPLKRuJxQO9UT/2vCFL0ScCO9IThRCa7ViMbGE=
github.com/Mrs4s/MiraiGo v0.0.0-20210104164708-e94ea61cc8e9/go.mod h1:HW2e375lCQiRwtuA/LV6ZVTsi7co1TRfBn+L5Ow77Bo=
github.com/Mrs4s/MiraiGo v0.0.0-20210104171920-510924ba979c h1:0O4TonUV7ZTawM+lwy0pNTYqngpbCrZGtYARGRvMQLw=
github.com/Mrs4s/MiraiGo v0.0.0-20210104171920-510924ba979c/go.mod h1:HW2e375lCQiRwtuA/LV6ZVTsi7co1TRfBn+L5Ow77Bo=
github.com/Mrs4s/MiraiGo v0.0.0-20210105173234-72521dec9b56 h1:U7kObHDk3RfaD81+1hA29gxHf3PfRGpX7dqR2UPNO0c=
github.com/Mrs4s/MiraiGo v0.0.0-20210105173234-72521dec9b56/go.mod h1:HW2e375lCQiRwtuA/LV6ZVTsi7co1TRfBn+L5Ow77Bo=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=

View File

@ -266,6 +266,8 @@ func (s *webServer) Dologin() {
log.Info("アトリは、高性能ですから!")
cli.OnDisconnected(func(bot *client.QQClient, e *client.ClientDisconnectedEvent) {
if conf.ReLogin.Enabled {
conf.ReLogin.Enabled = false
defer func() { conf.ReLogin.Enabled = true }()
var times uint = 1
for {
if cli.Online {
@ -293,6 +295,9 @@ func (s *webServer) Dologin() {
log.Fatalf("重连失败: 设备锁")
default:
log.Errorf("重连失败: %v", rsp.ErrorMessage)
if strings.Contains(rsp.ErrorMessage, "冻结") {
log.Fatalf("账号被冻结, 放弃重连")
}
cli.Disconnect()
continue
}

View File

@ -428,6 +428,33 @@ func HandleQuickOperation(s *httpServer, c *gin.Context) {
}
}
func DownloadFile(s *httpServer, c *gin.Context) {
url := getParam(c, "url")
tc, _ := strconv.Atoi(getParam(c, "thread_count"))
h, t := getParamWithType(c, "headers")
headers := map[string]string{}
if t == gjson.Null || t == gjson.String {
lines := strings.Split(h, "\r\n")
for _, sub := range lines {
str := strings.SplitN(sub, "=", 2)
if len(str) == 2 {
headers[str[0]] = str[1]
}
}
}
if t == gjson.JSON {
arr := gjson.Parse(h)
for _, sub := range arr.Array() {
str := strings.SplitN(sub.String(), "=", 2)
if len(str) == 2 {
headers[str[0]] = str[1]
}
}
}
println(url, tc, h, t)
c.JSON(200, s.bot.CQDownloadFile(url, headers, tc))
}
func OcrImage(s *httpServer, c *gin.Context) {
img := getParam(c, "image")
c.JSON(200, s.bot.CQOcrImage(img))
@ -535,6 +562,7 @@ var httpApi = map[string]func(s *httpServer, c *gin.Context){
"reload_event_filter": ReloadEventFilter,
"set_group_portrait": SetGroupPortrait,
"set_group_anonymous_ban": SetGroupAnonymousBan,
"download_file": DownloadFile,
".handle_quick_operation": HandleQuickOperation,
".ocr_image": OcrImage,
"ocr_image": OcrImage,

View File

@ -490,6 +490,28 @@ var wsApi = map[string]func(*coolq.CQBot, gjson.Result) coolq.MSG{
"get_msg": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQGetMessage(int32(p.Get("message_id").Int()))
},
"download_file": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
headers := map[string]string{}
headersToken := p.Get("headers")
if headersToken.IsArray() {
for _, sub := range headersToken.Array() {
str := strings.SplitN(sub.String(), "=", 2)
if len(str) == 2 {
headers[str[0]] = str[1]
}
}
}
if headersToken.Type == gjson.String {
lines := strings.Split(headersToken.String(), "\r\n")
for _, sub := range lines {
str := strings.SplitN(sub, "=", 2)
if len(str) == 2 {
headers[str[0]] = str[1]
}
}
}
return bot.CQDownloadFile(p.Get("url").Str, headers, int(p.Get("thread_count").Int()))
},
"get_group_honor_info": func(bot *coolq.CQBot, p gjson.Result) coolq.MSG {
return bot.CQGetGroupHonorInfo(p.Get("group_id").Int(), p.Get("type").Str)
},