kefu/wechatbot/lib/tools.go

178 lines
3.8 KiB
Go
Raw Normal View History

2024-12-10 02:50:12 +00:00
package lib
import (
"bytes"
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"html"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os/exec"
"regexp"
"runtime"
"strings"
)
// 打开浏览器
func Open(url string) error {
var (
cmd string
args []string
)
switch runtime.GOOS {
case "windows":
cmd, args = "cmd", []string{"/c", "start"}
case "darwin":
cmd = "open"
default:
// "linux", "freebsd", "openbsd", "netbsd"
cmd = "xdg-open"
}
args = append(args, url)
return exec.Command(cmd, args...).Start()
}
// 发送http post请求数据为form
func PostForm(url string, data url.Values) (string, error) {
resp, err := http.PostForm(url, data)
if err != nil {
return "", err
}
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(content), nil
}
/*
*
去除html标签过滤html标签
*/
func TrimHtml(src string) string {
// 使用正则表达式删除HTML标签
re := regexp.MustCompile(`(?m)<[^>]+>`)
withoutTags := re.ReplaceAllString(src, "")
// 解码HTML实体并去除左右的空格
return strings.TrimSpace(html.UnescapeString(withoutTags))
}
// md5加密
func Md5(src string) string {
m := md5.New()
m.Write([]byte(src))
res := hex.EncodeToString(m.Sum(nil))
return res
}
func WriteToEnvFile(data map[string]string, filePath string) error {
// 读取原始文件内容
content, err := ioutil.ReadFile(filePath)
if err != nil {
return err
}
lines := strings.Split(string(content), "\n")
updatedLines := make([]string, 0)
// 遍历每一行
for _, line := range lines {
if len(line) > 0 {
parts := strings.SplitN(line, "=", 2)
key := strings.TrimSpace(parts[0])
// 检查是否需要更新的键
if value, exists := data[key]; exists {
line = fmt.Sprintf("%s=%s", key, value)
delete(data, key) // 从待更新数据中删除已更新的键
}
}
updatedLines = append(updatedLines, line)
}
// 追加未更新的键值对
for key, value := range data {
updatedLines = append(updatedLines, fmt.Sprintf("%s=%s", key, value))
}
// 将更新后的内容写回文件
err = ioutil.WriteFile(filePath, []byte(strings.Join(updatedLines, "\n")), 0644)
if err != nil {
return err
}
return nil
}
func ContainsAny(str string, substrs []string) bool {
for _, substr := range substrs {
if strings.Contains(str, substr) {
return true
}
}
return false
}
func AskGPT(apiBase, apiKey, apiModel, visitorId, question string) (string, error) {
apiBase = strings.TrimRight(apiBase, "/")
apiBase = strings.TrimRight(apiBase, "/v1")
apiBase = apiBase + "/v1"
if apiModel == "" {
apiModel = "gpt-3.5-turbo-16k"
}
url := apiBase + "/chat/completions"
data := map[string]interface{}{
"model": apiModel,
}
if strings.Contains(apiKey, "fastgpt-") || strings.Contains(apiKey, "gofly-") {
data["chatId"] = visitorId
}
data["messages"] = []map[string]interface{}{
{
"role": "user",
"content": question,
},
}
jsonData, err := json.Marshal(data)
if err != nil {
log.Println("Error marshaling JSON:", err)
return "", err
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
log.Println("Error creating request:", err)
return "", err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+apiKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil || resp.StatusCode != 200 {
log.Println("Error making request:", err)
return "", err
}
// 在处理 API 响应的部分
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Println("Error reading response body:", err)
return "", err
}
// 现在body 包含了 API 响应的 JSON 数据,你可以对其进行处理
return string(body), nil
}