main.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "os"
  7. "os/signal"
  8. "path/filepath"
  9. "strings"
  10. "time"
  11. "github.com/eryajf/chatgpt-dingtalk/pkg/dingbot"
  12. "github.com/eryajf/chatgpt-dingtalk/pkg/logger"
  13. "github.com/eryajf/chatgpt-dingtalk/pkg/process"
  14. "github.com/eryajf/chatgpt-dingtalk/public"
  15. "github.com/xgfone/ship/v5"
  16. )
  17. func init() {
  18. public.InitSvc()
  19. logger.InitLogger(public.Config.LogLevel)
  20. }
  21. func main() {
  22. Start()
  23. }
  24. func Start() {
  25. app := ship.Default()
  26. app.Route("/").POST(func(c *ship.Context) error {
  27. var msgObj dingbot.ReceiveMsg
  28. err := c.Bind(&msgObj)
  29. if err != nil {
  30. return ship.ErrBadRequest.New(fmt.Errorf("bind to receivemsg failed : %v", err))
  31. }
  32. // 先校验回调是否合法
  33. if !public.CheckRequest(c.GetReqHeader("timestamp"), c.GetReqHeader("sign")) {
  34. logger.Warning("该请求不合法,可能是其他企业或者未经允许的应用调用所致,请知悉!")
  35. return nil
  36. }
  37. // 再校验回调参数是否有价值
  38. if msgObj.Text.Content == "" || msgObj.ChatbotUserID == "" {
  39. logger.Warning("从钉钉回调过来的内容为空,根据过往的经验,或许重新创建一下机器人,能解决这个问题")
  40. return ship.ErrBadRequest.New(fmt.Errorf("从钉钉回调过来的内容为空,根据过往的经验,或许重新创建一下机器人,能解决这个问题"))
  41. }
  42. // 去除问题的前后空格
  43. msgObj.Text.Content = strings.TrimSpace(msgObj.Text.Content)
  44. // 打印钉钉回调过来的请求明细,调试时打开
  45. logger.Debug(fmt.Sprintf("dingtalk callback parameters: %#v", msgObj))
  46. if public.Config.ChatType != "0" && msgObj.ConversationType != public.Config.ChatType {
  47. logger.Info(fmt.Sprintf("🙋 %s使用了禁用的聊天方式", msgObj.SenderNick))
  48. _, err = msgObj.ReplyToDingtalk(string(dingbot.MARKDOWN), "**🤷 抱歉,管理员禁用了这种聊天方式,请选择其他聊天方式与机器人对话!**")
  49. if err != nil {
  50. logger.Warning(fmt.Errorf("send message error: %v", err))
  51. return err
  52. }
  53. return nil
  54. }
  55. // 不在允许群组,不在允许用户(包括在黑名单),满足任一条件,拒绝会话;管理员不受限制
  56. if (!public.JudgeGroup(msgObj.GetChatTitle()) || !public.JudgeUsers(msgObj.SenderStaffId)) && !public.JudgeAdminUsers(msgObj.SenderStaffId) {
  57. logger.Info(fmt.Sprintf("🙋 %s身份信息未被验证通过", msgObj.SenderNick))
  58. _, err = msgObj.ReplyToDingtalk(string(dingbot.MARKDOWN), "**🤷 抱歉,您的身份信息未被认证通过,无法使用机器人对话功能。**\n>如需继续使用,请联系管理员申请访问权限。")
  59. if err != nil {
  60. logger.Warning(fmt.Errorf("send message error: %v", err))
  61. return err
  62. }
  63. return nil
  64. }
  65. if len(msgObj.Text.Content) == 1 || msgObj.Text.Content == "帮助" {
  66. // 欢迎信息
  67. _, err := msgObj.ReplyToDingtalk(string(dingbot.MARKDOWN), public.Config.Help)
  68. if err != nil {
  69. logger.Warning(fmt.Errorf("send message error: %v", err))
  70. return ship.ErrBadRequest.New(fmt.Errorf("send message error: %v", err))
  71. }
  72. } else {
  73. logger.Info(fmt.Sprintf("🙋 %s发起的问题: %#v", msgObj.SenderNick, msgObj.Text.Content))
  74. // 除去帮助之外的逻辑分流在这里处理
  75. switch {
  76. case strings.HasPrefix(msgObj.Text.Content, "#图片"):
  77. return process.ImageGenerate(&msgObj)
  78. case strings.HasPrefix(msgObj.Text.Content, "#查对话"):
  79. return process.SelectHistory(&msgObj)
  80. case strings.HasPrefix(msgObj.Text.Content, "#域名"):
  81. return process.DomainMsg(&msgObj)
  82. case strings.HasPrefix(msgObj.Text.Content, "#证书"):
  83. return process.DomainCertMsg(&msgObj)
  84. default:
  85. msgObj.Text.Content, err = process.GeneratePrompt(msgObj.Text.Content)
  86. // err不为空:提示词之后没有文本 -> 直接返回提示词所代表的内容
  87. if err != nil {
  88. _, err = msgObj.ReplyToDingtalk(string(dingbot.TEXT), msgObj.Text.Content)
  89. if err != nil {
  90. logger.Warning(fmt.Errorf("send message error: %v", err))
  91. return err
  92. }
  93. return nil
  94. }
  95. return process.ProcessRequest(&msgObj)
  96. }
  97. }
  98. return nil
  99. })
  100. // 解析生成后的图片
  101. app.Route("/images/:filename").GET(func(c *ship.Context) error {
  102. filename := c.Param("filename")
  103. root := "./data/images/"
  104. return c.File(filepath.Join(root, filename))
  105. })
  106. // 解析生成后的历史聊天
  107. app.Route("/history/:filename").GET(func(c *ship.Context) error {
  108. filename := c.Param("filename")
  109. root := "./data/chatHistory/"
  110. return c.File(filepath.Join(root, filename))
  111. })
  112. // 直接下载文件
  113. app.Route("/download/:filename").GET(func(c *ship.Context) error {
  114. filename := c.Param("filename")
  115. root := "./data/chatHistory/"
  116. return c.Attachment(filepath.Join(root, filename), "")
  117. })
  118. // 服务器健康检测
  119. app.Route("/").GET(func(c *ship.Context) error {
  120. //返回消息优雅一点,告诉用户欢迎使用ding ding机器人服务 服务状态oK
  121. return c.JSON(http.StatusOK, map[string]interface{}{
  122. "status": "ok",
  123. "msg": "欢迎使用钉钉机器人",
  124. })
  125. })
  126. port := ":" + public.Config.Port
  127. srv := &http.Server{
  128. Addr: port,
  129. Handler: app,
  130. }
  131. // Initializing the server in a goroutine so that
  132. // it won't block the graceful shutdown handling below
  133. go func() {
  134. logger.Info("🚀 The HTTP Server is running on", port)
  135. if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  136. logger.Fatal("listen: %s\n", err)
  137. }
  138. }()
  139. // Wait for interrupt signal to gracefully shutdown the server with
  140. // a timeout of 5 seconds.
  141. quit := make(chan os.Signal, 1)
  142. // kill (no param) default send syscall.SIGTERM
  143. // kill -2 is syscall.SIGINT
  144. // kill -9 is syscall.SIGKILL but can't be catch, so don't need add it
  145. // signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
  146. signal.Notify(quit, os.Interrupt)
  147. <-quit
  148. logger.Info("Shutting down server...")
  149. // 5秒后强制退出
  150. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  151. defer cancel()
  152. if err := srv.Shutdown(ctx); err != nil {
  153. logger.Fatal("Server forced to shutdown:", err)
  154. }
  155. logger.Info("Server exiting!")
  156. }