123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272 |
- package function
- import (
- "encoding/json"
- "fmt"
- "io"
- "log"
- "net/http"
- "net/url"
- "os"
- "regexp"
- "strconv"
- "strings"
- "time"
- "github.com/JamZYM/golagrange/api"
- "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
- "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
- "github.com/shirou/gopsutil/v4/cpu"
- "github.com/shirou/gopsutil/v4/disk"
- "github.com/shirou/gopsutil/v4/mem"
- )
- func Func_bvdl(msg_text string, connBot api.WsBot, user_id int) {
- bv := strings.Replace(msg_text, "/bvdl ", "", 1)
- info, err := http.Post("http://"+os.Getenv("HOST")+":"+os.Getenv("BVDLPORT")+"/api/info?bv="+bv, "application/json", nil)
- if err != nil {
- connBot.Send_private_msg(user_id, "请求失败")
- fmt.Println(err)
- } else {
- defer info.Body.Close()
- var jsondata map[string]interface{}
- data, _ := io.ReadAll(info.Body)
- json.Unmarshal(data, &jsondata)
- if jsondata["isSingle"].(bool) {
- title := jsondata["videos"].(map[string]interface{})["1"].(map[string]interface{})["title"].(string)
- fmt.Println("http://" + os.Getenv("HOST") + ":" + os.Getenv("BVDLPORT") + "/api/download?bv=" + bv + "&title=" + title)
- // qbv := url.QueryEscape(bv)
- qbv := bv
- // qtitle := url.QueryEscape(title)
- qtitle := title
- geturl := "http://" + os.Getenv("HOST") + ":" + os.Getenv("BVDLPORT") + "/api/download?bv=" + qbv + "&title=" + qtitle
- result, err := http.Get(geturl)
- if err != nil {
- connBot.Send_private_msg(user_id, "下载失败")
- fmt.Println(err)
- } else {
- fmt.Print(result.Body)
- connBot.Send_private_msg(user_id, title)
- }
- } else {
- connBot.Send_private_msg(user_id, "该视频包含多个合集,请选择需要下载的集数(0为全选)")
- videoList := make(map[int]interface{})
- for page, video := range jsondata["videos"].(map[string]interface{}) {
- title := video.(map[string]interface{})["title"].(string)
- // qbv := url.QueryEscape(bv + "?p=" + page)
- qbv := bv + "?p=" + page
- // qtitle := url.QueryEscape(title)
- qtitle := title
- geturl := "http://" + os.Getenv("HOST") + ":" + os.Getenv("BVDLPORT") + "/api/download?bv=" + qbv + "&title=" + qtitle
- // fmt.Println(geturl)
- pageInt, err := strconv.Atoi(page)
- if err != nil {
- connBot.Send_private_msg(user_id, "下载失败")
- fmt.Println(err)
- break
- }
- if videoList[pageInt] == nil {
- videoList[pageInt] = make(map[string]interface{})
- }
- videoList[pageInt].(map[string]interface{})["title"] = title
- videoList[pageInt].(map[string]interface{})["geturl"] = geturl
- }
- for page := 1; page <= len(videoList); page++ {
- connBot.Send_private_msg(user_id, fmt.Sprintf("%v. %v", page, videoList[page].(map[string]interface{})["title"].(string)))
- }
- timeout := false
- go func() {
- time.Sleep(90 * time.Second)
- timeout = true
- }()
- temp_connBot := api.WebsocketBot(os.Getenv("HOST"), os.Getenv("PORT"), os.Getenv("PATH"))
- defer temp_connBot.Wsconn.Close()
- for {
- if timeout {
- fmt.Println("timeout")
- temp_connBot.Send_private_msg(user_id, "回复超时,取消下载")
- break
- }
- time.Sleep(1 * time.Second)
- _, messageBytes, err := temp_connBot.Wsconn.ReadMessage()
- if err != nil {
- log.Println("read:", err)
- return
- }
- var message map[string]interface{}
- json.Unmarshal(messageBytes, &message)
- if message["post_type"] == "message" {
- if (message["message_type"].(string) == "private") && (user_id == int(message["user_id"].(float64))) && (message["message"].([]interface{})[0].(map[string]interface{})["type"].(string) == "text") {
- msg_text := message["message"].([]interface{})[0].(map[string]interface{})["data"].(map[string]interface{})["text"].(string)
- if msg_text == "0" {
- temp_connBot.Send_private_msg(user_id, "即将下载全部分集")
- for page := 1; page <= len(videoList); page++ {
- _, err = http.Get(videoList[page].(map[string]interface{})["geturl"].(string))
- if err != nil {
- connBot.Send_private_msg(user_id, "下载失败")
- fmt.Println(err)
- }
- // fmt.Println(videoList[page].(map[string]interface{})["geturl"].(string))
- }
- temp_connBot.Send_private_msg(user_id, "下载完成")
- break
- }
- }
- } else {
- }
- }
- }
- }
- }
- func Func_serverStatus(connBot api.WsBot, user_id int) {
- _mem, err := mem.VirtualMemory()
- _cpu, _ := cpu.Percent(time.Second, false)
- _disk, _ := disk.Usage("/")
- // _net, _ := net.IOCounters(true)
- // response_text := fmt.Sprintf("内存: %v%%,\nCPU:%v%%,\n磁盘:%v%%", fmt.Sprintf("%.1f", _mem.UsedPercent), fmt.Sprintf("%.1f", _cpu[0]), fmt.Sprintf("%.1f", _disk.UsedPercent))
- response_text := fmt.Sprintf("内存: %v%%,CPU:%v%%,磁盘:%v%%", fmt.Sprintf("%.1f", _mem.UsedPercent), fmt.Sprintf("%.1f", _cpu[0]), fmt.Sprintf("%.1f", _disk.UsedPercent))
- println(response_text)
- if err != nil {
- connBot.Send_private_msg(user_id, "服务器异常")
- } else {
- connBot.Send_private_msg(user_id, "服务器状态:")
- connBot.Send_private_msg(user_id, response_text)
- }
- }
- type TokenResult struct {
- ErrMsg string
- Token struct {
- UserId string
- Id string
- ExpireTime int64
- }
- }
- func Func_TTS(connBot api.WsBot, id int, msg_text string, isGroup bool, file_id int) {
- msg_text = strings.Replace(msg_text, "/tts ", "", 1)
- currentTime := time.Now().Unix()
- expireTime, _ := strconv.Atoi(os.Getenv("TOKENEXPIRE"))
- if currentTime > int64(expireTime) {
- _tts_getToken()
- }
- var appkey string = os.Getenv("APPKEY")
- var token string = os.Getenv("TOKEN")
- var text string = msg_text
- var textUrlEncode = text
- textUrlEncode = url.QueryEscape(textUrlEncode)
- textUrlEncode = strings.Replace(textUrlEncode, "+", "%20", -1)
- textUrlEncode = strings.Replace(textUrlEncode, "*", "%2A", -1)
- textUrlEncode = strings.Replace(textUrlEncode, "%7E", "~", -1)
- var audioSaveFile string = "temp/audio/" + strconv.Itoa(file_id) + ".wav"
- absoluteDir, _ := os.Getwd()
- var absoluteFile string = "file://" + absoluteDir + "/" + audioSaveFile
- var format string = "wav"
- var sampleRate int = 16000
- _tts_processGETRequest(appkey, token, textUrlEncode, audioSaveFile, format, sampleRate)
- if isGroup {
- connBot.Send_group_msg(id, "[CQ:record,file="+absoluteFile+"]")
- } else {
- connBot.Send_private_msg(id, "[CQ:record,file="+absoluteFile+"]")
- }
- }
- func _tts_processGETRequest(appkey string, token string, text string, audioSaveFile string, format string, sampleRate int) {
- /**
- * 设置HTTPS GET请求:
- * 1.使用HTTPS协议
- * 2.语音识别服务域名:nls-gateway-cn-shanghai.aliyuncs.com
- * 3.语音识别接口请求路径:/stream/v1/tts
- * 4.设置必须请求参数:appkey、token、text、format、sample_rate
- * 5.设置可选请求参数:voice、volume、speech_rate、pitch_rate
- */
- var url string = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/tts"
- url = url + "?appkey=" + appkey
- url = url + "&token=" + token
- url = url + "&text=" + text
- url = url + "&format=" + format
- url = url + "&sample_rate=" + strconv.Itoa(sampleRate)
- // voice 发音人,可选,默认是xiaoyun。
- // url = url + "&voice=" + "xiaoyun"
- // volume 音量,范围是0~100,可选,默认50。
- // url = url + "&volume=" + strconv.Itoa(50)
- // speech_rate 语速,范围是-500~500,可选,默认是0。
- // url = url + "&speech_rate=" + strconv.Itoa(0)
- // pitch_rate 语调,范围是-500~500,可选,默认是0。
- // url = url + "&pitch_rate=" + strconv.Itoa(0)
- /**
- * 发送HTTPS GET请求,处理服务端的响应。
- */
- response, err := http.Get(url)
- if err != nil {
- fmt.Println("The GET request failed!")
- panic(err)
- }
- defer response.Body.Close()
- contentType := response.Header.Get("Content-Type")
- body, _ := io.ReadAll(response.Body)
- if contentType == "audio/mpeg" {
- file, _ := os.Create(audioSaveFile)
- defer file.Close()
- file.Write([]byte(body))
- // fmt.Println("The GET request succeed!")
- } else {
- // ContentType 为 null 或者为 "application/json"
- statusCode := response.StatusCode
- fmt.Println("The HTTP statusCode: " + strconv.Itoa(statusCode))
- fmt.Println("The GET request failed: " + string(body))
- }
- }
- func _tts_getToken() {
- client, err := sdk.NewClientWithAccessKey("cn-shanghai", os.Getenv("AKID"), os.Getenv("AKKEY"))
- if err != nil {
- panic(err)
- }
- request := requests.NewCommonRequest()
- request.Method = "POST"
- request.Domain = "nls-meta.cn-shanghai.aliyuncs.com"
- request.ApiName = "CreateToken"
- request.Version = "2019-02-28"
- response, err := client.ProcessCommonRequest(request)
- if err != nil {
- panic(err)
- }
- var tr TokenResult
- err = json.Unmarshal([]byte(response.GetHttpContentString()), &tr)
- if err == nil {
- fmt.Println(tr.Token.Id)
- fmt.Println(tr.Token.ExpireTime)
- } else {
- fmt.Println(err)
- }
- envContent, err := os.ReadFile(".env")
- if err != nil {
- fmt.Println("Error reading .env file")
- return
- }
- re1 := regexp.MustCompile(`TOKEN=".*"`)
- newContent := re1.ReplaceAllString(string(envContent), fmt.Sprintf(`TOKEN="%s"`, tr.Token.Id))
- re := regexp.MustCompile(`TOKENEXPIRE=".*"`)
- newContent = re.ReplaceAllString(string(newContent), fmt.Sprintf(`TOKENEXPIRE="%d"`, tr.Token.ExpireTime))
- err = os.WriteFile(".env", []byte(newContent), 0644)
- if err != nil {
- fmt.Println("Error reading .env file")
- return
- }
- }
|