Skip to content

Commit

Permalink
telegram/bot: register GET endpoint to test webhook
Browse files Browse the repository at this point in the history
The call to get "GET <Webhook.URL.Path>/<Token>" will return HTTP status
200 with JSON body '{"code":200,"message":"OK"}'.

This endpoint is to check if the bot server is really running.
  • Loading branch information
shuLhan committed Apr 16, 2024
1 parent a1b5275 commit f319122
Showing 1 changed file with 41 additions and 5 deletions.
46 changes: 41 additions & 5 deletions api/telegram/bot/bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"fmt"
"log"
"net/http"
"net/url"
"path"
"strconv"
"time"
Expand Down Expand Up @@ -414,6 +415,8 @@ func (bot *Bot) startWebhook() (err error) {

// createServer start the HTTP server for receiving Update.
func (bot *Bot) createServer() (err error) {
var logp = `createServer`

var serverOpts = libhttp.ServerOptions{
Address: bot.opts.Webhook.ListenAddress,
}
Expand All @@ -434,20 +437,42 @@ func (bot *Bot) createServer() (err error) {

bot.webhook, err = libhttp.NewServer(serverOpts)
if err != nil {
return fmt.Errorf("createServer: %w", err)
return fmt.Errorf(`%s: %w`, logp, err)
}

var epToken = libhttp.Endpoint{
var webhookURL *url.URL

webhookURL, err = url.Parse(bot.opts.Webhook.URL)
if err != nil {
return fmt.Errorf(`%s: %w`, logp, err)
}

var fullPath = path.Join(webhookURL.Path, bot.opts.Token)

var ep = libhttp.Endpoint{
Method: libhttp.RequestMethodGet,
Path: fullPath,
RequestType: libhttp.RequestTypeNone,
ResponseType: libhttp.ResponseTypeJSON,
Call: bot.handleWebhookGet,
}

err = bot.webhook.RegisterEndpoint(ep)
if err != nil {
return fmt.Errorf(`%s: %w`, logp, err)
}

ep = libhttp.Endpoint{
Method: libhttp.RequestMethodPost,
Path: "/" + bot.opts.Token,
Path: fullPath,
RequestType: libhttp.RequestTypeJSON,
ResponseType: libhttp.ResponseTypeNone,
Call: bot.handleWebhook,
}

err = bot.webhook.RegisterEndpoint(epToken)
err = bot.webhook.RegisterEndpoint(ep)
if err != nil {
return fmt.Errorf("createServer: %w", err)
return fmt.Errorf(`%s: %w`, logp, err)
}

return nil
Expand Down Expand Up @@ -476,6 +501,17 @@ func (bot *Bot) handleWebhook(epr *libhttp.EndpointRequest) (resBody []byte, err
return resBody, nil
}

func (bot *Bot) handleWebhookGet(_ *libhttp.EndpointRequest) (resBody []byte, err error) {
var res = libhttp.EndpointResponse{}
res.Code = 200
res.Message = `OK`
resBody, err = json.Marshal(&res)
if err != nil {
return nil, err
}
return resBody, nil
}

func (bot *Bot) handleUpdateCommand(update Update) bool {
ok := update.Message.parseCommandArgs()
if !ok {
Expand Down

0 comments on commit f319122

Please sign in to comment.