telegram_push.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package telegram_push
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "pmail/config"
  7. "pmail/dto/parsemail"
  8. "pmail/utils/context"
  9. "strings"
  10. log "github.com/sirupsen/logrus"
  11. )
  12. type TelegramPushHook struct {
  13. chatId string
  14. botToken string
  15. httpsEnabled int
  16. webDomain string
  17. }
  18. func (w *TelegramPushHook) SendBefore(ctx *context.Context, email *parsemail.Email) {
  19. }
  20. func (w *TelegramPushHook) SendAfter(ctx *context.Context, email *parsemail.Email, err map[string]error) {
  21. }
  22. func (w *TelegramPushHook) ReceiveParseBefore(email []byte) {
  23. }
  24. func (w *TelegramPushHook) ReceiveParseAfter(email *parsemail.Email) {
  25. if w.chatId == "" || w.botToken == "" {
  26. return
  27. }
  28. w.sendUserMsg(nil, email)
  29. }
  30. type SendMessageRequest struct {
  31. ChatID string `json:"chat_id"`
  32. Text string `json:"text"`
  33. ReplyMarkup ReplyMarkup `json:"reply_markup"`
  34. ParseMode string `json:"parse_mode"`
  35. }
  36. type ReplyMarkup struct {
  37. InlineKeyboard [][]InlineKeyboardButton `json:"inline_keyboard"`
  38. }
  39. type InlineKeyboardButton struct {
  40. Text string `json:"text"`
  41. URL string `json:"url"`
  42. }
  43. func (w *TelegramPushHook) sendUserMsg(ctx *context.Context, email *parsemail.Email) {
  44. url := w.webDomain
  45. if w.httpsEnabled > 1 {
  46. url = "http://" + url
  47. } else {
  48. url = "https://" + url
  49. }
  50. sendMsgReq, _ := json.Marshal(SendMessageRequest{
  51. ChatID: w.chatId,
  52. Text: fmt.Sprintf("📧<b>%s</b>&#60;%s&#62;\n\n%s", email.Subject, email.From.EmailAddress, string(email.Text)),
  53. ParseMode: "HTML",
  54. ReplyMarkup: ReplyMarkup{
  55. InlineKeyboard: [][]InlineKeyboardButton{
  56. {
  57. {
  58. Text: "查收邮件",
  59. URL: url,
  60. },
  61. },
  62. },
  63. },
  64. })
  65. _, err := http.Post(fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", w.botToken), "application/json", strings.NewReader(string(sendMsgReq)))
  66. if err != nil {
  67. log.WithContext(ctx).Errorf("telegram push error %+v", err)
  68. }
  69. }
  70. func NewTelegramPushHook() *TelegramPushHook {
  71. ret := &TelegramPushHook{
  72. botToken: config.Instance.TgBotToken,
  73. chatId: config.Instance.TgChatId,
  74. webDomain: config.Instance.WebDomain,
  75. httpsEnabled: config.Instance.HttpsEnabled,
  76. }
  77. return ret
  78. }