Chat Bots in Go: Writing a Fast and Reliable Assistant from Scratch

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Why Go is the Ideal Choice for Chat Bots?

\n\n

If you've ever written a chat bot in Python, you know: it works. But when the load grows to thousands of requests per second, Python starts to "think." Go (or Golang) is designed not to think — it just does. High performance, built-in networking, goroutines (lightweight threads), and minimal memory consumption make Go the best language for creating high-load chat bots.

\n\n

In this guide, we will create a full-fledged Telegram bot in Go that will handle commands, work with the API, and scale easily. You'll get not just theory, but ready-to-run code that you can launch in 5 minutes.

\n\n

What Are We Going to Build?

\n\n

Our Go bot will be able to:

\n
    \n
  • Respond to the /start command with a greeting.
  • \n
  • Accept text messages and return them in uppercase (an echo bot with "character").
  • \n
  • Handle errors and log actions.
  • \n
  • Work via the Telegram Bot API (the most popular scenario for chat bots).
  • \n
\n\n

All code will be written in pure Go without third-party libraries (only the standard library and HTTP client) so you understand how everything works "under the hood."

\n\n

Step 1: Setting Up the Environment

\n\n

Make sure you have Go installed (version 1.21+). You can check with the command:

\n\n
go version
\n\n

Create a new directory for the project and initialize the module:

\n\n
mkdir go-chat-bot\ncd go-chat-bot\ngo mod init github.com/yourname/go-chat-bot
\n\n

You will need a bot token. If you don't have one:

\n
    \n
  1. Write to Telegram @BotFather.
  2. \n
  3. Send the command /newbot and follow the instructions.
  4. \n
  5. Copy the received token (it looks like this: 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11).
  6. \n
\n\n

Save the token in an environment variable (never store tokens in code!):

\n\n
export BOT_TOKEN="your_token_here"
\n\n

Step 2: Basic Bot Structure in Go

\n\n

Create a file main.go. We'll start with a simple HTTP server that will receive updates from Telegram. Go is ideal for this thanks to the built-in net/http package.

\n\n
package main\n\nimport (\n    "encoding/json"\n    "fmt"\n    "io"\n    "log"\n    "net/http"\n    "os"\n    "strings"\n)\n\n// Update — структура входящего обновления от Telegram\ntype Update struct {\n    UpdateID int `json:"update_id"`\n    Message  struct {\n        Text string `json:"text"`\n        Chat struct {\n            ID int64 `json:"id"`\n        } `json:"chat"`\n    } `json:"message"`\n}\n\nfunc main() {\n    botToken := os.Getenv("BOT_TOKEN")\n    if botToken == "" {\n        log.Fatal("BOT_TOKEN not set")\n    }\n\n    http.HandleFunc("/webhook", func(w http.ResponseWriter, r *http.Request) {\n        handleWebhook(w, r, botToken)\n    })\n\n    log.Println("Bot started on :8080")\n    log.Fatal(http.ListenAndServe(":8080", nil))\n}\n\nfunc handleWebhook(w http.ResponseWriter, r *http.Request, token string) {\n    body, err := io.ReadAll(r.Body)\n    if err != nil {\n        log.Printf("Error reading request body: %v", err)\n        http.Error(w, "Bad Request", http.StatusBadRequest)\n        return\n    }\n    defer r.Body.Close()\n\n    var update Update\n    if err := json.Unmarshal(body, &update); err != nil {\n        log.Printf("Error parsing JSON: %v", err)\n        http.Error(w, "Bad JSON", http.StatusBadRequest)\n        return\n    }\n\n    // If the message is empty — ignore it\n    if update.Message.Text == "" {\n        return\n    }\n\n    log.Printf("Received message: %s", update.Message.Text)\n\n    // Form the reply\n    var replyText string\n    if strings.HasPrefix(update.Message.Text, "/start") {\n        replyText = "Hello! I am a bot in Go. Write"                

Blogs

Book Recommendations