Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stop Telegram contact that have blocked the channel bot #436

Merged
merged 1 commit into from
Apr 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 60 additions & 17 deletions handlers/telegram/telegram.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package telegram

import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
Expand Down Expand Up @@ -131,7 +132,16 @@ func (h *handler) receiveMessage(ctx context.Context, channel courier.Channel, w
return handlers.WriteMsgsAndResponse(ctx, h, []courier.Msg{msg}, w, r)
}

func (h *handler) sendMsgPart(msg courier.Msg, token string, path string, form url.Values, keyboard *ReplyKeyboardMarkup) (string, *courier.ChannelLog, error) {
type mtResponse struct {
Ok bool `json:"ok" validate:"required"`
ErrorCode int `json:"error_code"`
Description string `json:"description"`
Result struct {
MessageID int64 `json:"message_id"`
} `json:"result"`
}

func (h *handler) sendMsgPart(msg courier.Msg, token string, path string, form url.Values, keyboard *ReplyKeyboardMarkup) (string, *courier.ChannelLog, bool, error) {
// either include or remove our keyboard
if keyboard == nil {
form.Add("reply_markup", `{"remove_keyboard":true}`)
Expand All @@ -142,7 +152,7 @@ func (h *handler) sendMsgPart(msg courier.Msg, token string, path string, form u
sendURL := fmt.Sprintf("%s/bot%s/%s", apiURL, token, path)
req, err := http.NewRequest(http.MethodPost, sendURL, strings.NewReader(form.Encode()))
if err != nil {
return "", nil, err
return "", nil, false, err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

Expand All @@ -151,19 +161,22 @@ func (h *handler) sendMsgPart(msg courier.Msg, token string, path string, form u
// build our channel log
log := courier.NewChannelLogFromRR("Message Sent", msg.Channel(), msg.ID(), rr).WithError("Message Send Error", err)

// was this request successful?
ok, err := jsonparser.GetBoolean([]byte(rr.Body), "ok")
if err != nil || !ok {
return "", log, errors.Errorf("response not 'ok'")
}
response := &mtResponse{}
err = json.Unmarshal(rr.Body, response)

if err != nil || !response.Ok {
if response.ErrorCode == 403 && response.Description == "Forbidden: bot was blocked by the user" {
return "", log, true, errors.Errorf("response not 'ok'")

}
return "", log, false, errors.Errorf("response not 'ok'")

// grab our message id
externalID, err := jsonparser.GetInt([]byte(rr.Body), "result", "message_id")
if err != nil {
return "", log, errors.Errorf("no 'result.message_id' in response")
}

return strconv.FormatInt(externalID, 10), log, nil
if response.Result.MessageID > 0 {
return strconv.FormatInt(response.Result.MessageID, 10), log, false, nil
}
return "", log, true, errors.Errorf("no 'result.message_id' in response")
}

// SendMsg sends the passed in message, returning any error
Expand Down Expand Up @@ -205,7 +218,13 @@ func (h *handler) SendMsg(ctx context.Context, msg courier.Msg) (courier.MsgStat
"text": []string{msg.Text()},
}

externalID, log, err := h.sendMsgPart(msg, authToken, "sendMessage", form, msgKeyBoard)
externalID, log, botBlocked, err := h.sendMsgPart(msg, authToken, "sendMessage", form, msgKeyBoard)
if botBlocked {
status.SetStatus(courier.MsgFailed)
channelEvent := h.Backend().NewChannelEvent(msg.Channel(), courier.StopContact, msg.URN())
err = h.Backend().WriteChannelEvent(ctx, channelEvent)
return status, err
}
status.SetExternalID(externalID)
hasError = err != nil
status.AddLog(log)
Expand All @@ -227,7 +246,13 @@ func (h *handler) SendMsg(ctx context.Context, msg courier.Msg) (courier.MsgStat
"photo": []string{mediaURL},
"caption": []string{caption},
}
externalID, log, err := h.sendMsgPart(msg, authToken, "sendPhoto", form, attachmentKeyBoard)
externalID, log, botBlocked, err := h.sendMsgPart(msg, authToken, "sendPhoto", form, attachmentKeyBoard)
if botBlocked {
status.SetStatus(courier.MsgFailed)
channelEvent := h.Backend().NewChannelEvent(msg.Channel(), courier.StopContact, msg.URN())
err = h.Backend().WriteChannelEvent(ctx, channelEvent)
return status, err
}
status.SetExternalID(externalID)
hasError = err != nil
status.AddLog(log)
Expand All @@ -238,7 +263,13 @@ func (h *handler) SendMsg(ctx context.Context, msg courier.Msg) (courier.MsgStat
"video": []string{mediaURL},
"caption": []string{caption},
}
externalID, log, err := h.sendMsgPart(msg, authToken, "sendVideo", form, attachmentKeyBoard)
externalID, log, botBlocked, err := h.sendMsgPart(msg, authToken, "sendVideo", form, attachmentKeyBoard)
if botBlocked {
status.SetStatus(courier.MsgFailed)
channelEvent := h.Backend().NewChannelEvent(msg.Channel(), courier.StopContact, msg.URN())
err = h.Backend().WriteChannelEvent(ctx, channelEvent)
return status, err
}
status.SetExternalID(externalID)
hasError = err != nil
status.AddLog(log)
Expand All @@ -249,7 +280,13 @@ func (h *handler) SendMsg(ctx context.Context, msg courier.Msg) (courier.MsgStat
"audio": []string{mediaURL},
"caption": []string{caption},
}
externalID, log, err := h.sendMsgPart(msg, authToken, "sendAudio", form, attachmentKeyBoard)
externalID, log, botBlocked, err := h.sendMsgPart(msg, authToken, "sendAudio", form, attachmentKeyBoard)
if botBlocked {
status.SetStatus(courier.MsgFailed)
channelEvent := h.Backend().NewChannelEvent(msg.Channel(), courier.StopContact, msg.URN())
err = h.Backend().WriteChannelEvent(ctx, channelEvent)
return status, err
}
status.SetExternalID(externalID)
hasError = err != nil
status.AddLog(log)
Expand All @@ -260,7 +297,13 @@ func (h *handler) SendMsg(ctx context.Context, msg courier.Msg) (courier.MsgStat
"document": []string{mediaURL},
"caption": []string{caption},
}
externalID, log, err := h.sendMsgPart(msg, authToken, "sendDocument", form, attachmentKeyBoard)
externalID, log, botBlocked, err := h.sendMsgPart(msg, authToken, "sendDocument", form, attachmentKeyBoard)
if botBlocked {
status.SetStatus(courier.MsgFailed)
channelEvent := h.Backend().NewChannelEvent(msg.Channel(), courier.StopContact, msg.URN())
err = h.Backend().WriteChannelEvent(ctx, channelEvent)
return status, err
}
status.SetExternalID(externalID)
hasError = err != nil
status.AddLog(log)
Expand Down
8 changes: 8 additions & 0 deletions handlers/telegram/telegram_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,14 @@ var defaultSendTestCases = []ChannelSendTestCase{
ResponseBody: `{ "ok": false }`, ResponseStatus: 403,
PostParams: map[string]string{"text": `Error`, "chat_id": "12345"},
SendPrep: setSendURL},
{Label: "Stopped Contact Code",
Text: "Stopped Contact", URN: "telegram:12345",
Status: "F",
ResponseBody: `{ "ok": false, "error_code":403, "description":"Forbidden: bot was blocked by the user"}`, ResponseStatus: 403,
PostParams: map[string]string{"text": `Stopped Contact`, "chat_id": "12345"},
SendPrep: setSendURL,
Stopped: true},

{Label: "Send Photo",
Text: "My pic!", URN: "telegram:12345", Attachments: []string{"image/jpeg:https://foo.bar/image.jpg"},
Status: "W",
Expand Down