Browse Source

feat: add webhook in group chat

pull/94/head v4.7.3
Aldino Kemal 3 years ago
parent
commit
bd71730d07
  1. 2
      src/cmd/root.go
  2. 2
      src/config/settings.go
  3. 46
      src/pkg/whatsapp/whatsapp.go

2
src/cmd/root.go

@ -39,7 +39,7 @@ func init() {
rootCmd.PersistentFlags().StringVarP(&config.AppOs, "os", "", config.AppOs, `os name --os <string> | example: --os="Chrome"`) rootCmd.PersistentFlags().StringVarP(&config.AppOs, "os", "", config.AppOs, `os name --os <string> | example: --os="Chrome"`)
rootCmd.PersistentFlags().StringVarP(&config.AppBasicAuthCredential, "basic-auth", "b", config.AppBasicAuthCredential, "basic auth credential | -b=yourUsername:yourPassword") rootCmd.PersistentFlags().StringVarP(&config.AppBasicAuthCredential, "basic-auth", "b", config.AppBasicAuthCredential, "basic auth credential | -b=yourUsername:yourPassword")
rootCmd.PersistentFlags().StringVarP(&config.WhatsappAutoReplyMessage, "autoreply", "", config.WhatsappAutoReplyMessage, `auto reply when received message --autoreply <string> | example: --autoreply="Don't reply this message"`) rootCmd.PersistentFlags().StringVarP(&config.WhatsappAutoReplyMessage, "autoreply", "", config.WhatsappAutoReplyMessage, `auto reply when received message --autoreply <string> | example: --autoreply="Don't reply this message"`)
rootCmd.PersistentFlags().StringVarP(&config.WhatsappAutoReplyWebhook, "webhook", "w", config.WhatsappAutoReplyMessage, `auto reply when received message --webhook <string> | example: --webhook="https://yourcallback.com/callback"`)
rootCmd.PersistentFlags().StringVarP(&config.WhatsappWebhook, "webhook", "w", config.WhatsappWebhook, `forward event to webhook --webhook <string> | example: --webhook="https://yourcallback.com/callback"`)
} }
func runRest(_ *cobra.Command, _ []string) { func runRest(_ *cobra.Command, _ []string) {

2
src/config/settings.go

@ -22,7 +22,7 @@ var (
WhatsappLogLevel = "ERROR" WhatsappLogLevel = "ERROR"
WhatsappAutoReplyMessage string WhatsappAutoReplyMessage string
WhatsappAutoReplyWebhook string
WhatsappWebhook string
WhatsappSettingMaxFileSize int64 = 50000000 // 50MB WhatsappSettingMaxFileSize int64 = 50000000 // 50MB
WhatsappSettingMaxVideoSize int64 = 100000000 // 100MB WhatsappSettingMaxVideoSize int64 = 100000000 // 100MB
) )

46
src/pkg/whatsapp/whatsapp.go

@ -22,6 +22,7 @@ import (
"mime" "mime"
"net/http" "net/http"
"os" "os"
"regexp"
"strings" "strings"
"sync/atomic" "sync/atomic"
"time" "time"
@ -208,15 +209,17 @@ func handler(rawEvt interface{}) {
} }
} }
if !isGroupJid(evt.Info.Chat.String()) && !strings.Contains(evt.Info.SourceString(), "broadcast") {
if config.WhatsappAutoReplyMessage != "" {
_, _ = cli.SendMessage(context.Background(), evt.Info.Sender, &waProto.Message{Conversation: proto.String(config.WhatsappAutoReplyMessage)})
}
if config.WhatsappAutoReplyMessage != "" &&
!isGroupJid(evt.Info.Chat.String()) &&
!strings.Contains(evt.Info.SourceString(), "broadcast") {
_, _ = cli.SendMessage(context.Background(), evt.Info.Sender, &waProto.Message{Conversation: proto.String(config.WhatsappAutoReplyMessage)})
}
if config.WhatsappAutoReplyWebhook != "" {
if err := sendAutoReplyWebhook(evt); err != nil {
logrus.Error("Failed to send webhoook", err)
}
if config.WhatsappWebhook != "" &&
!strings.Contains(evt.Info.SourceString(), "broadcast") &&
!isFromMySelf(evt.Info.SourceString()) {
if err := forwardToWebhook(evt); err != nil {
logrus.Error("Failed forward to webhook", err)
} }
} }
case *events.Receipt: case *events.Receipt:
@ -257,8 +260,9 @@ func handler(rawEvt interface{}) {
} }
} }
func sendAutoReplyWebhook(evt *events.Message) error {
logrus.Info("Sending webhook to", config.WhatsappAutoReplyWebhook)
// forwardToWebhook is a helper function to forward event to webhook url
func forwardToWebhook(evt *events.Message) error {
logrus.Info("Forwarding event to webhook:", config.WhatsappWebhook)
client := &http.Client{Timeout: 10 * time.Second} client := &http.Client{Timeout: 10 * time.Second}
imageMedia := evt.Message.GetImageMessage() imageMedia := evt.Message.GetImageMessage()
stickerMedia := evt.Message.GetStickerMessage() stickerMedia := evt.Message.GetStickerMessage()
@ -352,7 +356,7 @@ func sendAutoReplyWebhook(evt *events.Message) error {
return pkgError.WebhookError(fmt.Sprintf("Failed to marshal body: %v", err)) return pkgError.WebhookError(fmt.Sprintf("Failed to marshal body: %v", err))
} }
req, err := http.NewRequest(http.MethodPost, config.WhatsappAutoReplyWebhook, bytes.NewBuffer(postBody))
req, err := http.NewRequest(http.MethodPost, config.WhatsappWebhook, bytes.NewBuffer(postBody))
if err != nil { if err != nil {
return pkgError.WebhookError(fmt.Sprintf("error when create http object %v", err)) return pkgError.WebhookError(fmt.Sprintf("error when create http object %v", err))
} }
@ -363,10 +367,30 @@ func sendAutoReplyWebhook(evt *events.Message) error {
return nil return nil
} }
// isGroupJid is a helper function to check if the message is from group
func isGroupJid(jid string) bool { func isGroupJid(jid string) bool {
return strings.Contains(jid, "@g.us") return strings.Contains(jid, "@g.us")
} }
// isFromMySelf is a helper function to check if the message is from my self (logged in account)
func isFromMySelf(jid string) bool {
return extractPhoneNumber(jid) == extractPhoneNumber(cli.Store.ID.String())
}
// extractPhoneNumber is a helper function to extract the phone number from a JID
func extractPhoneNumber(jid string) string {
regex := regexp.MustCompile(`\d+`)
// Find all matches of the pattern in the JID
matches := regex.FindAllString(jid, -1)
// The first match should be the phone number
if len(matches) > 0 {
return matches[0]
}
// If no matches are found, return an empty string
return ""
}
// DownloadMedia is a helper function to download media from whatsapp
func DownloadMedia(storageLocation string, mediaFile whatsmeow.DownloadableMessage) (path string, err error) { func DownloadMedia(storageLocation string, mediaFile whatsmeow.DownloadableMessage) (path string, err error) {
if mediaFile == nil { if mediaFile == nil {
logrus.Info("Skip download because data is nil") logrus.Info("Skip download because data is nil")

Loading…
Cancel
Save