1
0
mirror of synced 2024-11-22 04:26:01 +03:00

make route for MG webhook

This commit is contained in:
Alex Lushpai 2018-05-28 18:08:15 +03:00
parent cd6c64e6da
commit 7ebadf753e
4 changed files with 96 additions and 0 deletions

9
event.go Normal file
View File

@ -0,0 +1,9 @@
package main
type EventMessage struct {
ChannelID uint64 `json:"channel_id"`
ExternalID int `json:"external_id,omitempty"`
ChatID int64 `json:"chat_id"`
Message string `json:"message,omitempty"`
Type string `json:"type"`
}

View File

@ -37,6 +37,17 @@ func getBotByToken(token string) *Bot {
return &bot
}
func getBotByChannel(ch uint64) *Bot {
var bot Bot
orm.DB.First(&bot, "channel = ?", ch)
return &bot
}
func (b *Bot) createBot() error {
return orm.DB.Create(b).Error
}
func (b *Bot) setBotActivity() error {
return orm.DB.Model(b).Where("token = ?", b.Token).Update("Active", !b.Active).Error
}

View File

@ -557,6 +557,81 @@ func validateCrmSettings(c Connection) error {
return nil
}
func mgWebhookHandler(w http.ResponseWriter, r *http.Request) {
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
raven.CaptureErrorAndWait(err, nil)
logger.Error(err)
return
}
var msg EventMessage
err = json.Unmarshal(bytes, &msg)
if err != nil {
raven.CaptureErrorAndWait(err, nil)
logger.Error(err)
return
}
b := getBotByChannel(msg.ChannelID)
if b.ID == 0 {
logger.Error(msg.ChannelID, "missing")
return
}
if !b.Active {
logger.Error(msg.ChannelID, "deactivated")
return
}
bot, err := tgbotapi.NewBotAPI(b.Token)
if err != nil {
raven.CaptureErrorAndWait(err, nil)
logger.Error(err)
}
bot.Debug = true
if msg.Type == "message_sent" {
msg, err := bot.Send(tgbotapi.NewMessage(msg.ChatID, msg.Message))
if err != nil {
logger.Error(err)
w.WriteHeader(http.StatusBadRequest)
return
}
logger.Debugf("%v", msg)
w.WriteHeader(http.StatusOK)
w.Write([]byte("Message sent"))
}
if msg.Type == "message_updated" {
msg, err := bot.Send(tgbotapi.NewEditMessageText(msg.ChatID, msg.ExternalID, msg.Message))
if err != nil {
logger.Error(err)
w.WriteHeader(http.StatusBadRequest)
return
}
logger.Debugf("%v", msg)
w.WriteHeader(http.StatusOK)
w.Write([]byte("Message updated"))
}
if msg.Type == "message_deleted" {
msg, err := bot.Send(tgbotapi.NewDeleteMessage(msg.ChatID, msg.ExternalID))
if err != nil {
logger.Error(err)
w.WriteHeader(http.StatusBadRequest)
return
}
logger.Debugf("%v", msg)
w.WriteHeader(http.StatusOK)
w.Write([]byte("Message deleted"))
}
}
func getAPIClient(url, key string) (*v5.Client, error, int) {
client := v5.New(url, key)

View File

@ -15,6 +15,7 @@ import (
func setTransportRoutes() {
http.HandleFunc("/telegram/", makeHandler(telegramWebhookHandler))
http.HandleFunc("/webhook/", mgWebhookHandler)
}
// GetBotInfo function