slash.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. package function
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "log"
  7. "net/http"
  8. "net/url"
  9. "os"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/JamZYM/golagrange/api"
  15. "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
  16. "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
  17. "github.com/shirou/gopsutil/v4/cpu"
  18. "github.com/shirou/gopsutil/v4/disk"
  19. "github.com/shirou/gopsutil/v4/mem"
  20. )
  21. func Func_bvdl(msg_text string, connBot api.WsBot, user_id int) {
  22. bv := strings.Replace(msg_text, "/bvdl ", "", 1)
  23. info, err := http.Post("http://"+os.Getenv("HOST")+":"+os.Getenv("BVDLPORT")+"/api/info?bv="+bv, "application/json", nil)
  24. if err != nil {
  25. connBot.Send_private_msg(user_id, "请求失败")
  26. fmt.Println(err)
  27. } else {
  28. defer info.Body.Close()
  29. var jsondata map[string]interface{}
  30. data, _ := io.ReadAll(info.Body)
  31. json.Unmarshal(data, &jsondata)
  32. if jsondata["isSingle"].(bool) {
  33. title := jsondata["videos"].(map[string]interface{})["1"].(map[string]interface{})["title"].(string)
  34. fmt.Println("http://" + os.Getenv("HOST") + ":" + os.Getenv("BVDLPORT") + "/api/download?bv=" + bv + "&title=" + title)
  35. // qbv := url.QueryEscape(bv)
  36. qbv := bv
  37. // qtitle := url.QueryEscape(title)
  38. qtitle := title
  39. geturl := "http://" + os.Getenv("HOST") + ":" + os.Getenv("BVDLPORT") + "/api/download?bv=" + qbv + "&title=" + qtitle
  40. result, err := http.Get(geturl)
  41. if err != nil {
  42. connBot.Send_private_msg(user_id, "下载失败")
  43. fmt.Println(err)
  44. } else {
  45. fmt.Print(result.Body)
  46. connBot.Send_private_msg(user_id, title)
  47. }
  48. } else {
  49. connBot.Send_private_msg(user_id, "该视频包含多个合集,请选择需要下载的集数(0为全选)")
  50. videoList := make(map[int]interface{})
  51. for page, video := range jsondata["videos"].(map[string]interface{}) {
  52. title := video.(map[string]interface{})["title"].(string)
  53. // qbv := url.QueryEscape(bv + "?p=" + page)
  54. qbv := bv + "?p=" + page
  55. // qtitle := url.QueryEscape(title)
  56. qtitle := title
  57. geturl := "http://" + os.Getenv("HOST") + ":" + os.Getenv("BVDLPORT") + "/api/download?bv=" + qbv + "&title=" + qtitle
  58. // fmt.Println(geturl)
  59. pageInt, err := strconv.Atoi(page)
  60. if err != nil {
  61. connBot.Send_private_msg(user_id, "下载失败")
  62. fmt.Println(err)
  63. break
  64. }
  65. if videoList[pageInt] == nil {
  66. videoList[pageInt] = make(map[string]interface{})
  67. }
  68. videoList[pageInt].(map[string]interface{})["title"] = title
  69. videoList[pageInt].(map[string]interface{})["geturl"] = geturl
  70. }
  71. for page := 1; page <= len(videoList); page++ {
  72. connBot.Send_private_msg(user_id, fmt.Sprintf("%v. %v", page, videoList[page].(map[string]interface{})["title"].(string)))
  73. }
  74. timeout := false
  75. go func() {
  76. time.Sleep(90 * time.Second)
  77. timeout = true
  78. }()
  79. temp_connBot := api.WebsocketBot(os.Getenv("HOST"), os.Getenv("PORT"), os.Getenv("PATH"))
  80. defer temp_connBot.Wsconn.Close()
  81. for {
  82. if timeout {
  83. fmt.Println("timeout")
  84. temp_connBot.Send_private_msg(user_id, "回复超时,取消下载")
  85. break
  86. }
  87. time.Sleep(1 * time.Second)
  88. _, messageBytes, err := temp_connBot.Wsconn.ReadMessage()
  89. if err != nil {
  90. log.Println("read:", err)
  91. return
  92. }
  93. var message map[string]interface{}
  94. json.Unmarshal(messageBytes, &message)
  95. if message["post_type"] == "message" {
  96. if (message["message_type"].(string) == "private") && (user_id == int(message["user_id"].(float64))) && (message["message"].([]interface{})[0].(map[string]interface{})["type"].(string) == "text") {
  97. msg_text := message["message"].([]interface{})[0].(map[string]interface{})["data"].(map[string]interface{})["text"].(string)
  98. if msg_text == "0" {
  99. temp_connBot.Send_private_msg(user_id, "即将下载全部分集")
  100. for page := 1; page <= len(videoList); page++ {
  101. _, err = http.Get(videoList[page].(map[string]interface{})["geturl"].(string))
  102. if err != nil {
  103. connBot.Send_private_msg(user_id, "下载失败")
  104. fmt.Println(err)
  105. }
  106. // fmt.Println(videoList[page].(map[string]interface{})["geturl"].(string))
  107. }
  108. temp_connBot.Send_private_msg(user_id, "下载完成")
  109. break
  110. }
  111. }
  112. } else {
  113. }
  114. }
  115. }
  116. }
  117. }
  118. func Func_serverStatus(connBot api.WsBot, user_id int) {
  119. _mem, err := mem.VirtualMemory()
  120. _cpu, _ := cpu.Percent(time.Second, false)
  121. _disk, _ := disk.Usage("/")
  122. // _net, _ := net.IOCounters(true)
  123. // response_text := fmt.Sprintf("内存: %v%%,\nCPU:%v%%,\n磁盘:%v%%", fmt.Sprintf("%.1f", _mem.UsedPercent), fmt.Sprintf("%.1f", _cpu[0]), fmt.Sprintf("%.1f", _disk.UsedPercent))
  124. response_text := fmt.Sprintf("内存: %v%%,CPU:%v%%,磁盘:%v%%", fmt.Sprintf("%.1f", _mem.UsedPercent), fmt.Sprintf("%.1f", _cpu[0]), fmt.Sprintf("%.1f", _disk.UsedPercent))
  125. println(response_text)
  126. if err != nil {
  127. connBot.Send_private_msg(user_id, "服务器异常")
  128. } else {
  129. connBot.Send_private_msg(user_id, "服务器状态:")
  130. connBot.Send_private_msg(user_id, response_text)
  131. }
  132. }
  133. type TokenResult struct {
  134. ErrMsg string
  135. Token struct {
  136. UserId string
  137. Id string
  138. ExpireTime int64
  139. }
  140. }
  141. func Func_TTS(connBot api.WsBot, id int, msg_text string, isGroup bool, file_id int) {
  142. msg_text = strings.Replace(msg_text, "/tts ", "", 1)
  143. currentTime := time.Now().Unix()
  144. expireTime, _ := strconv.Atoi(os.Getenv("TOKENEXPIRE"))
  145. if currentTime > int64(expireTime) {
  146. _tts_getToken()
  147. }
  148. var appkey string = os.Getenv("APPKEY")
  149. var token string = os.Getenv("TOKEN")
  150. var text string = msg_text
  151. var textUrlEncode = text
  152. textUrlEncode = url.QueryEscape(textUrlEncode)
  153. textUrlEncode = strings.Replace(textUrlEncode, "+", "%20", -1)
  154. textUrlEncode = strings.Replace(textUrlEncode, "*", "%2A", -1)
  155. textUrlEncode = strings.Replace(textUrlEncode, "%7E", "~", -1)
  156. var audioSaveFile string = "temp/audio/" + strconv.Itoa(file_id) + ".wav"
  157. absoluteDir, _ := os.Getwd()
  158. var absoluteFile string = "file://" + absoluteDir + "/" + audioSaveFile
  159. var format string = "wav"
  160. var sampleRate int = 16000
  161. _tts_processGETRequest(appkey, token, textUrlEncode, audioSaveFile, format, sampleRate)
  162. if isGroup {
  163. connBot.Send_group_msg(id, "[CQ:record,file="+absoluteFile+"]")
  164. } else {
  165. connBot.Send_private_msg(id, "[CQ:record,file="+absoluteFile+"]")
  166. }
  167. }
  168. func _tts_processGETRequest(appkey string, token string, text string, audioSaveFile string, format string, sampleRate int) {
  169. /**
  170. * 设置HTTPS GET请求:
  171. * 1.使用HTTPS协议
  172. * 2.语音识别服务域名:nls-gateway-cn-shanghai.aliyuncs.com
  173. * 3.语音识别接口请求路径:/stream/v1/tts
  174. * 4.设置必须请求参数:appkey、token、text、format、sample_rate
  175. * 5.设置可选请求参数:voice、volume、speech_rate、pitch_rate
  176. */
  177. var url string = "https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/tts"
  178. url = url + "?appkey=" + appkey
  179. url = url + "&token=" + token
  180. url = url + "&text=" + text
  181. url = url + "&format=" + format
  182. url = url + "&sample_rate=" + strconv.Itoa(sampleRate)
  183. // voice 发音人,可选,默认是xiaoyun。
  184. // url = url + "&voice=" + "xiaoyun"
  185. // volume 音量,范围是0~100,可选,默认50。
  186. // url = url + "&volume=" + strconv.Itoa(50)
  187. // speech_rate 语速,范围是-500~500,可选,默认是0。
  188. // url = url + "&speech_rate=" + strconv.Itoa(0)
  189. // pitch_rate 语调,范围是-500~500,可选,默认是0。
  190. // url = url + "&pitch_rate=" + strconv.Itoa(0)
  191. /**
  192. * 发送HTTPS GET请求,处理服务端的响应。
  193. */
  194. response, err := http.Get(url)
  195. if err != nil {
  196. fmt.Println("The GET request failed!")
  197. panic(err)
  198. }
  199. defer response.Body.Close()
  200. contentType := response.Header.Get("Content-Type")
  201. body, _ := io.ReadAll(response.Body)
  202. if contentType == "audio/mpeg" {
  203. file, _ := os.Create(audioSaveFile)
  204. defer file.Close()
  205. file.Write([]byte(body))
  206. // fmt.Println("The GET request succeed!")
  207. } else {
  208. // ContentType 为 null 或者为 "application/json"
  209. statusCode := response.StatusCode
  210. fmt.Println("The HTTP statusCode: " + strconv.Itoa(statusCode))
  211. fmt.Println("The GET request failed: " + string(body))
  212. }
  213. }
  214. func _tts_getToken() {
  215. client, err := sdk.NewClientWithAccessKey("cn-shanghai", os.Getenv("AKID"), os.Getenv("AKKEY"))
  216. if err != nil {
  217. panic(err)
  218. }
  219. request := requests.NewCommonRequest()
  220. request.Method = "POST"
  221. request.Domain = "nls-meta.cn-shanghai.aliyuncs.com"
  222. request.ApiName = "CreateToken"
  223. request.Version = "2019-02-28"
  224. response, err := client.ProcessCommonRequest(request)
  225. if err != nil {
  226. panic(err)
  227. }
  228. var tr TokenResult
  229. err = json.Unmarshal([]byte(response.GetHttpContentString()), &tr)
  230. if err == nil {
  231. fmt.Println(tr.Token.Id)
  232. fmt.Println(tr.Token.ExpireTime)
  233. } else {
  234. fmt.Println(err)
  235. }
  236. envContent, err := os.ReadFile(".env")
  237. if err != nil {
  238. fmt.Println("Error reading .env file")
  239. return
  240. }
  241. re1 := regexp.MustCompile(`TOKEN=".*"`)
  242. newContent := re1.ReplaceAllString(string(envContent), fmt.Sprintf(`TOKEN="%s"`, tr.Token.Id))
  243. re := regexp.MustCompile(`TOKENEXPIRE=".*"`)
  244. newContent = re.ReplaceAllString(string(newContent), fmt.Sprintf(`TOKENEXPIRE="%d"`, tr.Token.ExpireTime))
  245. err = os.WriteFile(".env", []byte(newContent), 0644)
  246. if err != nil {
  247. fmt.Println("Error reading .env file")
  248. return
  249. }
  250. }