A 4 Minute Guide to Creating Telegram Bot in Go

A step by step guide for new Go programmers

Jane Kozhevnikova
Dev Genius

--

I have been thinking about creating bots for Telegram. I use Telegram a lot, so I got many ideas to help me to simplify my routines. One of these ideas is especially useful for language learners — a dictionary.

In this guide, we are going to discuss how to create a dictionary bot for Telegram. I tried to make this material as easy as possible. I divided the entire programming process into several small steps:

  1. We look for an English dictionary API,
  2. Then create the bot and generate a Telegram token with @BotFather.
  3. After that, we start coding by authorizing our bot and receiving a message from the chat.
  4. Then, we use the found dictionary API for requesting and receiving word meanings.
  5. Format the received word.
  6. And to send this to the chat.

In the following picture you see how the bot is working when the user sends a word:

Pic.1. Bot’s work when the user sends a word

› Looking for Dictionary API

For this project, I found a free Google Dictionary API. We will read only the meaning, definition and example fields from the full response.

› Getting Token

Search for @BotFather in Telegram. Open a chat. Type /newbot in the chat. Choose a name for your new bot. I named our bot English_Dictionary. Then, think about a username. I chose @dictionary_eng_bot.

When you find an available username, @BotFather will automatically send you the token to access the Telegram API. Never share this token with anyone otherwise the token can be compromised.

› Authorizing Bot

We read sensitive credentials through environment variables. Then, we create a new BotAPI instance, which accepts the given token.

›› Review Progress

To build and execute the code use the following command:

$ token=x go run main.go

If the connection has been established, you should see the message “Authorized on account your_telegram_username”. If the connection is failed, you see the message “Unable to connect to the Telegram API”.

At this step, we check that the bot has been authorized.

› Getting Incoming Word

All the information from the user we get through updates. There are two methods for this: getUpdates() and getUpdatesChan(). We use getUpdatesChan() because this method returns a channel which “waits for updates”.

To configure the updates request we create a new UpdateConfig instance. UpdateConfig contains offset, limit and timeout fields. For simplicity’s sake we zero these parameters.

config := tgbotapi.UpdateConfig{}
updates, err := bot.GetUpdatesChan(config)
if err != nil {
return err
}

In the preceding code updates is the channel for storing responses from the Telegram API.

for update := range updates {
// here we will process the word from the user
}

update.Message.Text is the incoming word.

›› Review Progress

Try to get the word from the chat and print it on your screen.

Change the code:

for update := range updates {
fmt.Println(“word:”, update.Message.Text)
}

Find the bot in Telegram, press Start and type a word. In your command line, you will see the word that you have sent to the chat.

› Working with Request and Response

In the following code, we make a request, read all the body of the response, parse the JSON-encoded data, and store this data in the WordInfo struct.

The requestWord() function is omitted here. See the full code.

After getting the response, we check the status code. If the status code is 200 OK, we receive the word information.

If the status code is not equal to 200 OK, the response does not contain the required data. This can happen for many reasons. For example, when the word does not exist, or the word is misspelt. Return error in code.

›› Review Progress

Change main():

After the “receivedWord:” you get a struct filled with the word information.

› Formatting Message

Below is the JSON-encoded WordInfo slice of structs, because a word can have many meanings, definitions and examples.

In the following function, we iterate over WordInfo to find the definitions, meanings, and examples.

›› Review Progress

To see that the word’s parameters we get are correct, update main():

After the code execution you will see the message in the command line in the following format:

Part of speech:
Definition:
Example:

The getWordInfo() function returns nil and error when the word either does not exist or is misspelt. To check this problem, you can type a wrong word and see the message in the chat.

› Sending Results

We create a message config with the tgbotapi.NewMessage() method. We need two arguments for this: update.Message.Chat.ID or where we need to send the message and the wordParams or what we need to send to the user. Then, send the message config to the user with the bot.Send() method as in the following example:

msg := tgbotapi.NewMessage(update.Message.Chat.ID, wordParams)		_, err = bot.Send(msg)
if err != nil {
log.Println("Unable to send message:", err)
return
}

›› Review Progress

Update your code:

Full Code

--

--