The purpose of this guide is to make a simple telegram bot, which replies with a compliment for each and every message that it receives.
Create a bot in telegram
- Look for a bot named BotFather t.me/botfather . This bot is used to create bots in telegram.
- There enter
/newbot
- Enter a unique name for your bot, ex -
complimentrbot
- Then you will get a message with the
bot link
andbot token
to access the bot.
Telegram Echo Bot
Get the basic example of telegram echo bot from here
In the example, change the MyAwesomeBotToken
to the actual bot token which we got in the above step.
Use the Complimentr api to get the compliments
complimentr.com/api (check this link to see the API response).
Now, we write a function in our main.go called getCompliment()
.
func getCompliment() (string, error) {
// make a get call to the api endpoint
resp, err := http.Get("https://complimentr.com/api")
if err != nil {
return "", err
}
defer resp.Body.Close()
// read the body in bytes
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
m := make(map[string]string)
// convert json data into a map
err = json.Unmarshal(body, &m)
if err != nil {
return "", err
}
// return the compliment string
return m["compliment"], nil
}
Now, we can modify the echo bot to reply with a compliment.
c, err := getCompliment()
if err!=nil{
fmt.Println("Error while getting compliment")
continue
}
msg := tgbotapi.NewMessage(update.Message.Chat.ID, c)
Final Code
package main
import (
"encoding/json"
"io/ioutil"
"fmt"
"os"
"log"
"net/http"
"github.com/go-telegram-bot-api/telegram-bot-api"
)
func getCompliment() (string, error) {
resp, err := http.Get("https://complimentr.com/api")
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
m := make(map[string]string)
err = json.Unmarshal(body, &m)
if err != nil {
return "", err
}
return m["compliment"], nil
}
func main() {
token := os.Getenv("TELEGRAM_TOKEN")
bot, err := tgbotapi.NewBotAPI(token)
if err != nil {
log.Panic(err)
}
bot.Debug = true
log.Printf("Authorized on account %s", bot.Self.UserName)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := bot.GetUpdatesChan(u)
for update := range updates {
if update.Message == nil { // ignore any non-Message Updates
continue
}
log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)
c, err := getCompliment()
if err!=nil{
fmt.Println("Error while getting compliment")
continue
}
msg := tgbotapi.NewMessage(update.Message.Chat.ID, c)
msg.ReplyToMessageID = update.Message.MessageID
bot.Send(msg)
}
}