In this Tutorial we will build a Telegram Bot that fetch Quote from a Website and send it to Telegram.
For Basic Knowledge and How BOT is build inside telegram: Follow these Instructions
https://core.telegram.org/bots/tutorial
Imports
import (
"encoding/json"
"log"
"net/http"
"strconv"
"time"
"github.com/go-co-op/gocron"
"github.com/hashicorp/go-hclog"
tgBOT "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
Step -1
First we will fetch a quote from a URL
https://zenquotes.io/api/random
This Website give us JSON response of Some Random Quotes You can See it in your Browser.
Than based on JSON Objects we will get from this website we will build our Data Model
type RandomQuotes struct {
Quote string `json:"q"`
Author string `json:"a"`
}
This JSON model will provide us Quote as well as Author same as the JSON Object we will get from our URL
func FetchQuote() string {
// fetch the result from the website
resp, err := http.Get("https://zenquotes.io/api/random")
// if we end up any errors for http errors - e.g if we hit the url too many times
if err != nil {
log.Fatalln(err)
}
// than we will close the response - defer means this line of code will execute at the end of function
defer resp.Body.Close()
// storage for quote we will get
var quotes []RandomQuotes
// than we will decode the JSON Object BODY Response
json.NewDecoder(resp.Body).Decode("es)
// if we get response like for example if we get QUOTE Response
// we will return it as TEXT Object
if len(quotes) > 0 {
println(quotes[0].Quote + " - " + quotes[0].Author)
return quotes[0].Quote + " - " + quotes[0].Author
}
// Otherwise Empty String
return ""
}
Step -2
func QuoteURL(message string) {
// Here we will directly Call the TELEGRAM sendMessage API that means we don't hve to use any warper
var URL string = "https://api.telegram.org/bot" + apiTOKEN + "/sendMessage?chat_id=" + strconv.Itoa(chatID) + "&text=" + message
// is the message we will enter if it's not empty
if message != "" {
// we will get the JSON response
resp, err := http.Get(URL)
if err != nil {
log.Fatalln(err)
}
// Than we will close the response
defer resp.Body.Close()
}
}
Step -3
GoCorn is a Library that will call the api after every 10 Send and send response to our Telegram
var apiTOKEN string = "123456789:AAE8zD_pYDH8DkDKeaOYUIPKIfczHGHGSHEI"
var chatID int = 123244576774
func QuoteBOT() {
logger := NewLogger()
s := gocron.NewScheduler(time.UTC)
// Reset limit send mail for users.
_, err := s.Every(10).Seconds().Do(func() {
logger.Info("calling URL....")
// get message from getQuote function
message := FetchQuote()
QuoteURL(message)
})
if err != nil {
logger.Error("Error scheduling limit data", "error", err)
return
}
// s.StartAsync()
s.StartBlocking()
}
Bonus
If you wanna use TELEGRAM Wrapper for API calling Skip the
Step 3
go get "github.com/go-telegram-bot-api/telegram-bot-api/v5"
updates := bot.GetUpdatesChan(updateConfig)
for update := range updates {
if update.Message == nil {
continue
}
data, dataErr := FetchQuote()
if dataErr != nil {
log.Fatal(dataErr)
}
println(data)
message := tgBOT.NewMessage(update.Message.Chat.ID, data)
bot.Send(message)
}
Basic Loging
// NewLogger returns a new logger instance
func NewLogger() hclog.Logger {
logger := hclog.New(&hclog.LoggerOptions{
Name: "telegram-bot-service",
Level: hclog.LevelFromString("DEBUG"),
})
return logger
}
Final Thoughts:
Building a Basic BOT is really simple but based on use case it can be very complex and advance. For more advance cases I will post some more content. Like How to implement Trading BOT, Finance BOT etc.
Top comments (0)