main.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package main
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "log"
  6. "net/http"
  7. "strings"
  8. "github.com/eryajf/chatgpt-dingtalk/gtp"
  9. "github.com/eryajf/chatgpt-dingtalk/public"
  10. "github.com/eryajf/chatgpt-dingtalk/service"
  11. )
  12. var UserService service.UserServiceInterface
  13. func init() {
  14. UserService = service.NewUserService()
  15. }
  16. func main() {
  17. // 定义一个处理器函数
  18. handler := func(w http.ResponseWriter, r *http.Request) {
  19. data, err := ioutil.ReadAll(r.Body)
  20. if err != nil {
  21. http.Error(w, err.Error(), http.StatusBadRequest)
  22. return
  23. }
  24. // TODO: 校验请求
  25. // fmt.Println(r.Header)
  26. var msgObj = new(public.ReceiveMsg)
  27. err = json.Unmarshal(data, &msgObj)
  28. if err != nil {
  29. log.Printf("unmarshal request body failed: %v\n", err)
  30. }
  31. err = ProcessRequest(*msgObj)
  32. if err != nil {
  33. log.Printf("process request failed: %v\n", err)
  34. }
  35. }
  36. // 创建一个新的 HTTP 服务器
  37. server := &http.Server{
  38. Addr: ":8090",
  39. Handler: http.HandlerFunc(handler),
  40. }
  41. // 启动服务器
  42. log.Print("Start Listen On ", server.Addr)
  43. err := server.ListenAndServe()
  44. if err != nil {
  45. log.Fatal(err)
  46. }
  47. }
  48. func ProcessRequest(rmsg public.ReceiveMsg) error {
  49. // 获取问题的答案
  50. reply, err := gtp.Completions(rmsg.Text.Content)
  51. if err != nil {
  52. log.Printf("gtp request error: %v \n", err)
  53. _, err = rmsg.ReplyText("机器人太累了,让她休息会儿,过一会儿再来请求。")
  54. if err != nil {
  55. log.Printf("send message error: %v \n", err)
  56. return err
  57. }
  58. log.Printf("request openai error: %v\n", err)
  59. return err
  60. }
  61. if reply == "" {
  62. return nil
  63. }
  64. // 回复@我的用户
  65. reply = strings.TrimSpace(reply)
  66. reply = strings.Trim(reply, "\n")
  67. atText := "@" + rmsg.SenderNick + "\n" + " "
  68. // 设置上下文
  69. if UserService.ClearUserSessionContext(rmsg.SenderID, rmsg.Text.Content) {
  70. _, err = rmsg.ReplyText(atText + "上下文已经清空了,你可以问下一个问题啦。")
  71. if err != nil {
  72. log.Printf("response user error: %v \n", err)
  73. return err
  74. }
  75. }
  76. UserService.SetUserSessionContext(rmsg.SenderID, rmsg.Text.Content, reply)
  77. replyText := atText + reply
  78. _, err = rmsg.ReplyText(replyText)
  79. if err != nil {
  80. log.Printf("send message error: %v \n", err)
  81. return err
  82. }
  83. return nil
  84. }