From 01dd2c622f66d2e9a6db7c57893ac4fc35824810 Mon Sep 17 00:00:00 2001 From: Valeriy Selitskiy <239034+iamwavecut@users.noreply.github.com> Date: Thu, 7 Nov 2024 14:07:30 +0100 Subject: [PATCH] noop: create examples --- bot_test.go | 179 +---------------------------- examples/polling_echo.go | 73 ++++++++++++ examples/polling_inline_query.go | 43 +++++++ examples/webhook_custom_handler.go | 86 ++++++++++++++ examples/webhook_echo.go | 65 +++++++++++ 5 files changed, 268 insertions(+), 178 deletions(-) create mode 100644 examples/polling_echo.go create mode 100644 examples/polling_inline_query.go create mode 100644 examples/webhook_custom_handler.go create mode 100644 examples/webhook_echo.go diff --git a/bot_test.go b/bot_test.go index d61a73b5..0e98e38a 100644 --- a/bot_test.go +++ b/bot_test.go @@ -1,14 +1,12 @@ package tgbotapi import ( - "net/http" "os" "testing" "time" ) const ( - TestToken = "153667468:AAHlSHlMqSt1f_uFmVRJbm5gntu2HI4WW8I" ChatID = 76918703 Channel = "@tgbotapitest" SupergroupChatID = -1001120141283 @@ -35,7 +33,7 @@ func (t testLogger) Printf(format string, v ...interface{}) { } func getBot(t *testing.T) (*BotAPI, error) { - bot, err := NewBotAPI(TestToken) + bot, err := NewBotAPI(os.Getenv("TEST_TOKEN")) bot.Debug = true logger := testLogger{t} @@ -671,154 +669,6 @@ func TestSendWithMediaGroupAudio(t *testing.T) { } } -func ExampleNewBotAPI() { - bot, err := NewBotAPI("MyAwesomeBotToken") - if err != nil { - panic(err) - } - - bot.Debug = true - - log.Printf("Authorized on account %s", bot.Self.UserName) - - u := NewUpdate(0) - u.Timeout = 60 - - updates := bot.GetUpdatesChan(u) - - // Optional: wait for updates and clear them if you don't want to handle - // a large backlog of old messages - time.Sleep(time.Millisecond * 500) - updates.Clear() - - for update := range updates { - if update.Message == nil { - continue - } - - log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) - - msg := NewMessage(update.Message.Chat.ID, update.Message.Text) - msg.ReplyParameters.MessageID = update.Message.MessageID - - bot.Send(msg) - } -} - -func ExampleNewWebhook() { - bot, err := NewBotAPI("MyAwesomeBotToken") - if err != nil { - panic(err) - } - - bot.Debug = true - - log.Printf("Authorized on account %s", bot.Self.UserName) - - wh, err := NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, FilePath("cert.pem")) - - if err != nil { - panic(err) - } - - _, err = bot.Request(wh) - - if err != nil { - panic(err) - } - - info, err := bot.GetWebhookInfo() - - if err != nil { - panic(err) - } - - if info.LastErrorDate != 0 { - log.Printf("failed to set webhook: %s", info.LastErrorMessage) - } - - updates := bot.ListenForWebhook("/" + bot.Token) - go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil) - - for update := range updates { - log.Printf("%+v\n", update) - } -} - -func ExampleWebhookHandler() { - bot, err := NewBotAPI("MyAwesomeBotToken") - if err != nil { - panic(err) - } - - bot.Debug = true - - log.Printf("Authorized on account %s", bot.Self.UserName) - - wh, err := NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, FilePath("cert.pem")) - - if err != nil { - panic(err) - } - - _, err = bot.Request(wh) - if err != nil { - panic(err) - } - info, err := bot.GetWebhookInfo() - if err != nil { - panic(err) - } - if info.LastErrorDate != 0 { - log.Printf("[Telegram callback failed]%s", info.LastErrorMessage) - } - - http.HandleFunc("/"+bot.Token, func(w http.ResponseWriter, r *http.Request) { - update, err := bot.HandleUpdate(r) - if err != nil { - log.Printf("%+v\n", err.Error()) - } else { - log.Printf("%+v\n", *update) - } - }) - - go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil) -} - -func ExampleInlineConfig() { - bot, err := NewBotAPI("MyAwesomeBotToken") // create new bot - if err != nil { - panic(err) - } - - log.Printf("Authorized on account %s", bot.Self.UserName) - - u := NewUpdate(0) - u.Timeout = 60 - - updates := bot.GetUpdatesChan(u) - - for update := range updates { - if update.InlineQuery == nil { // if no inline query, ignore it - continue - } - - article := NewInlineQueryResultArticle(update.InlineQuery.ID, "Echo", update.InlineQuery.Query) - article.Description = update.InlineQuery.Query - - inlineConf := InlineConfig{ - InlineQueryID: update.InlineQuery.ID, - IsPersonal: true, - CacheTime: 0, - Results: []interface{}{article}, - } - - if _, err := bot.Request(inlineConf); err != nil { - log.Println(err) - } - } -} - func TestDeleteMessage(t *testing.T) { bot, _ := getBot(t) @@ -1021,33 +871,6 @@ func TestCommands(t *testing.T) { } } -// TODO: figure out why test is failing -// -// func TestEditMessageMedia(t *testing.T) { -// bot, _ := getBot(t) - -// msg := NewPhoto(ChatID, "tests/image.jpg") -// msg.Caption = "Test" -// m, err := bot.Send(msg) - -// if err != nil { -// t.Error(err) -// } - -// edit := EditMessageMediaConfig{ -// BaseEdit: BaseEdit{ -// ChatID: ChatID, -// MessageID: m.MessageID, -// }, -// Media: NewInputMediaVideo(FilePath("tests/video.mp4")), -// } - -// _, err = bot.Request(edit) -// if err != nil { -// t.Error(err) -// } -// } - func TestPrepareInputMediaForParams(t *testing.T) { media := []interface{}{ NewInputMediaPhoto(FilePath("tests/image.jpg")), diff --git a/examples/polling_echo.go b/examples/polling_echo.go new file mode 100644 index 00000000..c9852e0c --- /dev/null +++ b/examples/polling_echo.go @@ -0,0 +1,73 @@ +package main + +import ( + "log" + "time" + + api "github.com/OvyFlash/telegram-bot-api" +) + +// func main() { polling_echo() } + +func polling_echo() { + bot, err := api.NewBotAPI("MyAwesomeBotToken") + if err != nil { + panic(err) + } + + bot.Debug = true + + log.Printf("Authorized on account %s", bot.Self.UserName) + + updateConfig := api.NewUpdate(0) + updateConfig.Timeout = 60 + + // Empty list allows all updates excluding + // UpdateTypeChatMember, UpdateTypeMessageReaction and UpdateTypeMessageReactionCount + updateConfig.AllowedUpdates = []string{ + api.UpdateTypeMessage, + api.UpdateTypeEditedMessage, + api.UpdateTypeChannelPost, + api.UpdateTypeEditedChannelPost, + api.UpdateTypeBusinessConnection, + api.UpdateTypeBusinessMessage, + api.UpdateTypeEditedBusinessMessage, + api.UpdateTypeDeletedBusinessMessages, + api.UpdateTypeMessageReaction, + api.UpdateTypeMessageReactionCount, + api.UpdateTypeInlineQuery, + api.UpdateTypeChosenInlineResult, + api.UpdateTypeCallbackQuery, + api.UpdateTypeShippingQuery, + api.UpdateTypePreCheckoutQuery, + api.UpdateTypePurchasedPaidMedia, + api.UpdateTypePoll, + api.UpdateTypePollAnswer, + api.UpdateTypeMyChatMember, + api.UpdateTypeChatMember, + api.UpdateTypeChatJoinRequest, + api.UpdateTypeChatBoost, + api.UpdateTypeRemovedChatBoost, + } + + updatesChannel := bot.GetUpdatesChan(updateConfig) + + // Optional: wait for updates and clear them if you don't want to handle + // a large backlog of old messages + time.Sleep(time.Millisecond * 500) + updatesChannel.Clear() + + for update := range updatesChannel { + if update.Message == nil { + continue + } + + log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) + + // Send an echo reply to the message + msg := api.NewMessage(update.Message.Chat.ID, update.Message.Text) + msg.ReplyParameters.MessageID = update.Message.MessageID + + bot.Send(msg) + } +} diff --git a/examples/polling_inline_query.go b/examples/polling_inline_query.go new file mode 100644 index 00000000..1591f3fe --- /dev/null +++ b/examples/polling_inline_query.go @@ -0,0 +1,43 @@ +package main + +import ( + "log" + + api "github.com/OvyFlash/telegram-bot-api" +) + +// func main() { polling_inline_query() } + +func polling_inline_query() { + bot, err := api.NewBotAPI("MyAwesomeBotToken") // create new bot + if err != nil { + panic(err) + } + + log.Printf("Authorized on account %s", bot.Self.UserName) + + updateConfig := api.NewUpdate(0) + updateConfig.Timeout = 60 + + updatesChannel := bot.GetUpdatesChan(updateConfig) + + for update := range updatesChannel { + if update.InlineQuery == nil { // if no inline query, skip update + continue + } + + article := api.NewInlineQueryResultArticle(update.InlineQuery.ID, "Echo", update.InlineQuery.Query) + article.Description = update.InlineQuery.Query + + inlineConfig := api.InlineConfig{ + InlineQueryID: update.InlineQuery.ID, + IsPersonal: true, + CacheTime: 0, + Results: []interface{}{article}, + } + + if _, err := bot.Request(inlineConfig); err != nil { + log.Println(err) + } + } +} diff --git a/examples/webhook_custom_handler.go b/examples/webhook_custom_handler.go new file mode 100644 index 00000000..cdf98230 --- /dev/null +++ b/examples/webhook_custom_handler.go @@ -0,0 +1,86 @@ +package main + +import ( + "log" + "net/http" + "sync" + + api "github.com/OvyFlash/telegram-bot-api" +) + +// func main() { webhook_custom_handler() } + +func webhook_custom_handler() { + bot, err := api.NewBotAPI("MyAwesomeBotToken") + if err != nil { + panic(err) + } + + bot.Debug = true + + log.Printf("Authorized on account %s", bot.Self.UserName) + + // Listen for updates from the webhook and handle them yourself + http.HandleFunc("/"+bot.Token, func(w http.ResponseWriter, r *http.Request) { + update, err := bot.HandleUpdate(r) + if err != nil { + log.Printf("%+v\n", err.Error()) + } else { + log.Printf("%+v\n", *update) + } + + if update.Message == nil { + return + } + + log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) + + // Send an echo reply to the message + msg := api.NewMessage(update.Message.Chat.ID, update.Message.Text) + msg.ReplyParameters.MessageID = update.Message.MessageID + + bot.Send(msg) + }) + + waitGroup := sync.WaitGroup{} + + waitGroup.Add(1) + go func() { + defer waitGroup.Done() + if err := http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil); err != nil { + log.Printf("Error listening on TLS: %v", err) + } + }() + + // Set the webhook + webHook, err := api.NewWebhookWithCert("https://your-bot-host-url/"+bot.Token, api.FilePath("cert.pem")) + if err != nil { + panic(err) + } + if err != nil { + panic(err) + } + + apiResponse, err := bot.Request(webHook) + if err != nil { + panic(err) + } + + if apiResponse.Ok { + log.Printf("Webhook set successfully") + } else { + log.Printf("Failed to set webhook: %s", apiResponse.Description) + } + + info, err := bot.GetWebhookInfo() + if err != nil { + panic(err) + } + + if info.LastErrorDate != 0 { + log.Printf("Failed to get webhook info: %s", info.LastErrorMessage) + } + + // Wait for the server to terminate + waitGroup.Wait() +} diff --git a/examples/webhook_echo.go b/examples/webhook_echo.go new file mode 100644 index 00000000..2be84bcc --- /dev/null +++ b/examples/webhook_echo.go @@ -0,0 +1,65 @@ +package main + +import ( + "log" + "net/http" + + api "github.com/OvyFlash/telegram-bot-api" +) + +// func main() { webhook_echo() } + +func webhook_echo() { + bot, err := api.NewBotAPI("MyAwesomeBotToken") + if err != nil { + panic(err) + } + + bot.Debug = true + + log.Printf("Authorized on account %s", bot.Self.UserName) + + // Listen for updates from the webhook + updates := bot.ListenForWebhook("/" + bot.Token) + go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil) + + // Set the webhook + webHook, err := api.NewWebhookWithCert("https://your-bot-host-url/"+bot.Token, api.FilePath("cert.pem")) + if err != nil { + panic(err) + } + + apiResponse, err := bot.Request(webHook) + if err != nil { + panic(err) + } + + if apiResponse.Ok { + log.Printf("Webhook set successfully") + } else { + log.Printf("Failed to set webhook: %s", apiResponse.Description) + } + + info, err := bot.GetWebhookInfo() + if err != nil { + panic(err) + } + + if info.LastErrorDate != 0 { + log.Printf("Failed to get webhook info: %s", info.LastErrorMessage) + } + + for update := range updates { + if update.Message == nil { + continue + } + + log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) + + // Send an echo reply to the message + msg := api.NewMessage(update.Message.Chat.ID, update.Message.Text) + msg.ReplyParameters.MessageID = update.Message.MessageID + + bot.Send(msg) + } +}