1
0
mirror of synced 2024-11-25 05:06:03 +03:00

sending text stub

This commit is contained in:
DmitryZagorulko 2018-06-20 16:14:51 +03:00
parent f8577e9efd
commit de6ee9462a
5 changed files with 144 additions and 94 deletions

View File

@ -1 +1 @@
alter table mg_user rename to user; alter table mg_user rename to users;

View File

@ -69,9 +69,9 @@ func (c Connection) getBotsByClientID() Bots {
return b return b
} }
func getBotByChannelAndCID(connectionID int, ch uint64) *Bot { func getBot(cid int, ch uint64) *Bot {
var bot Bot var bot Bot
orm.DB.First(&bot, "connection_id = ? AND channel = ?", connectionID, ch) orm.DB.First(&bot, "connection_id = ? AND channel = ?", cid, ch)
return &bot return &bot
} }

View File

@ -15,6 +15,7 @@ import (
"github.com/aws/aws-sdk-go/service/s3/s3manager" "github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/getsentry/raven-go" "github.com/getsentry/raven-go"
"github.com/go-telegram-bot-api/telegram-bot-api" "github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/nicksnyder/go-i18n/v2/i18n"
"github.com/retailcrm/mg-transport-api-client-go/v1" "github.com/retailcrm/mg-transport-api-client-go/v1"
) )
@ -76,112 +77,118 @@ func telegramWebhookHandler(w http.ResponseWriter, r *http.Request, token string
var client = v1.New(c.MGURL, c.MGToken) var client = v1.New(c.MGURL, c.MGToken)
if update.Message != nil { if update.Message != nil {
if update.Message.Text != "" { if update.Message.Text == "" {
nickname := update.Message.From.UserName setLocale(update.Message.From.LanguageCode)
user := getUserByExternalID(update.Message.From.ID) update.Message.Text = localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: getMessageID(update.Message)})
}
if update.Message.From.UserName == "" { nickname := update.Message.From.UserName
nickname = update.Message.From.FirstName user := getUserByExternalID(update.Message.From.ID)
}
if user.Expired(config.UpdateInterval) || user.ID == 0 { if update.Message.From.UserName == "" {
fileID, fileURL, err := GetFileIDAndURL(b.Token, update.Message.From.ID) nickname = update.Message.From.FirstName
if err != nil { }
raven.CaptureErrorAndWait(err, nil)
logger.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if fileID != user.UserPhotoID && fileURL != "" { if user.Expired(config.UpdateInterval) || user.ID == 0 {
picURL, err := UploadUserAvatar(fileURL) fileID, fileURL, err := GetFileIDAndURL(b.Token, update.Message.From.ID)
if err != nil {
raven.CaptureErrorAndWait(err, nil)
logger.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
user.UserPhotoID = fileID
user.UserPhotoURL = picURL
}
if user.ExternalID == 0 {
user.ExternalID = update.Message.From.ID
}
err = user.save()
if err != nil {
raven.CaptureErrorAndWait(err, nil)
logger.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
if config.Debug {
logger.Debugf("telegramWebhookHandler user %v", user)
}
snd := v1.SendData{
Message: v1.SendMessage{
Message: v1.Message{
ExternalID: strconv.Itoa(update.Message.MessageID),
Type: "text",
Text: update.Message.Text,
},
SentAt: time.Now(),
},
User: v1.User{
ExternalID: strconv.Itoa(update.Message.From.ID),
Nickname: nickname,
Firstname: update.Message.From.FirstName,
Avatar: user.UserPhotoURL,
Lastname: update.Message.From.LastName,
Language: update.Message.From.LanguageCode,
},
Channel: b.Channel,
ExternalChatID: strconv.FormatInt(update.Message.Chat.ID, 10),
}
data, st, err := client.Messages(snd)
if err != nil { if err != nil {
raven.CaptureErrorAndWait(err, nil) raven.CaptureErrorAndWait(err, nil)
logger.Error(token, err.Error(), st, data) logger.Error(err)
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
return return
} }
if config.Debug { if fileID != user.UserPhotoID && fileURL != "" {
logger.Debugf("telegramWebhookHandler Type: SendMessage, Bot: %v, Message: %v, Response: %v", b.ID, snd, data) picURL, err := UploadUserAvatar(fileURL)
if err != nil {
raven.CaptureErrorAndWait(err, nil)
logger.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
user.UserPhotoID = fileID
user.UserPhotoURL = picURL
} }
if user.ExternalID == 0 {
user.ExternalID = update.Message.From.ID
}
err = user.save()
if err != nil {
raven.CaptureErrorAndWait(err, nil)
logger.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
if config.Debug {
logger.Debugf("telegramWebhookHandler user %v", user)
}
snd := v1.SendData{
Message: v1.SendMessage{
Message: v1.Message{
ExternalID: strconv.Itoa(update.Message.MessageID),
Type: "text",
Text: update.Message.Text,
},
SentAt: time.Now(),
},
User: v1.User{
ExternalID: strconv.Itoa(update.Message.From.ID),
Nickname: nickname,
Firstname: update.Message.From.FirstName,
Avatar: user.UserPhotoURL,
Lastname: update.Message.From.LastName,
Language: update.Message.From.LanguageCode,
},
Channel: b.Channel,
ExternalChatID: strconv.FormatInt(update.Message.Chat.ID, 10),
}
data, st, err := client.Messages(snd)
if err != nil {
raven.CaptureErrorAndWait(err, nil)
logger.Error(token, err.Error(), st, data)
w.WriteHeader(http.StatusInternalServerError)
return
}
if config.Debug {
logger.Debugf("telegramWebhookHandler Type: SendMessage, Bot: %v, Message: %v, Response: %v", b.ID, snd, data)
} }
} }
if update.EditedMessage != nil { if update.EditedMessage != nil {
if update.EditedMessage.Text != "" { if update.EditedMessage.Text == "" {
snd := v1.UpdateData{ setLocale(update.EditedMessage.From.LanguageCode)
Message: v1.UpdateMessage{ update.EditedMessage.Text = localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: getMessageID(update.Message)})
Message: v1.Message{ }
ExternalID: strconv.Itoa(update.EditedMessage.MessageID),
Type: "text", snd := v1.UpdateData{
Text: update.EditedMessage.Text, Message: v1.UpdateMessage{
}, Message: v1.Message{
ExternalID: strconv.Itoa(update.EditedMessage.MessageID),
Type: "text",
Text: update.EditedMessage.Text,
}, },
Channel: b.Channel, },
} Channel: b.Channel,
}
data, st, err := client.UpdateMessages(snd) data, st, err := client.UpdateMessages(snd)
if err != nil { if err != nil {
raven.CaptureErrorAndWait(err, nil) raven.CaptureErrorAndWait(err, nil)
logger.Error(token, err.Error(), st, data) logger.Error(token, err.Error(), st, data)
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
return return
} }
if config.Debug { if config.Debug {
logger.Debugf("telegramWebhookHandler Type: UpdateMessage, Bot: %v, Message: %v, Response: %v", b.ID, snd, data) logger.Debugf("telegramWebhookHandler Type: UpdateMessage, Bot: %v, Message: %v, Response: %v", b.ID, snd, data)
}
} }
} }
@ -229,7 +236,7 @@ func mgWebhookHandler(w http.ResponseWriter, r *http.Request) {
uid, _ := strconv.Atoi(msg.Data.ExternalMessageID) uid, _ := strconv.Atoi(msg.Data.ExternalMessageID)
cid, _ := strconv.ParseInt(msg.Data.ExternalChatID, 10, 64) cid, _ := strconv.ParseInt(msg.Data.ExternalChatID, 10, 64)
b := getBotByChannelAndCID(c.ID, msg.Data.ChannelID) b := getBot(c.ID, msg.Data.ChannelID)
if b.ID == 0 || !b.Active { if b.ID == 0 || !b.Active {
logger.Error(msg.Data.ChannelID, "mgWebhookHandler: missing or deactivated") logger.Error(msg.Data.ChannelID, "mgWebhookHandler: missing or deactivated")
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
@ -377,3 +384,26 @@ func UploadUserAvatar(url string) (picURLs3 string, err error) {
return return
} }
func getMessageID(data *tgbotapi.Message) string {
switch {
case data.Sticker != nil:
return "sticker"
case data.Audio != nil:
return "audio"
case data.Contact != nil:
return "contact"
case data.Document != nil:
return "document"
case data.Location != nil:
return "location"
case data.Video != nil:
return "video"
case data.Voice != nil:
return "voice"
case data.Photo != nil:
return "photo"
default:
return "undefined"
}
}

View File

@ -28,3 +28,13 @@ error_adding_bot: Error while adding bot
error_save: An error occurred while saving, contact technical support error_save: An error occurred while saving, contact technical support
missing_credentials: "Necessary credentials: {{.Credentials}}" missing_credentials: "Necessary credentials: {{.Credentials}}"
error_activity_mg: Check the activity with MessageGateway in CRM settings error_activity_mg: Check the activity with MessageGateway in CRM settings
sticker: "[sticker]"
audio: "[audio file]"
contact: "[contact]"
document: "[document]"
location: "[location]"
video: "[video]"
voice: "[voice message]"
photo: "[image]"
undefined: "[undefined message format]"

View File

@ -28,3 +28,13 @@ error_adding_bot: Ошибка при добавлении бота
error_save: Ошибка при сохранении, обратитесь в службу технической поддержки error_save: Ошибка при сохранении, обратитесь в службу технической поддержки
missing_credentials: "Необходимые методы: {{.Credentials}}" missing_credentials: "Необходимые методы: {{.Credentials}}"
error_activity_mg: Проверьте активность интеграции с MessageGateway в настройках CRM error_activity_mg: Проверьте активность интеграции с MessageGateway в настройках CRM
sticker: "[стикер]"
audio: "[аудио файл]"
contact: "[контакт]"
document: "[документ]"
location: "[местонахождение]"
video: "[видео]"
voice: "[голосовое сообщение]"
photo: "[изображение]"
other: "[неопределенный формат сообщения]"