Sending Messages using Telegram Bot and Go Language

  ·   3 min read

In the world of messaging and communication, Telegram has emerged as a popular messaging app that offers an API for developers to build bots for various tasks, including sending messages. In this article, we will explore how to send messages using a Telegram bot implemented in the Go programming language.

Overview

Telegram bots are third-party applications that run inside the Telegram environment. They can be used for a variety of use cases, including notifications, reminders, and even automated responses. To interact with the Telegram Bot API, we will use the net/http package for HTTP requests and the encoding/json package for JSON handling in Go.

Prerequisites

  • Go installed on your machine (preferably version 1.16 or higher)
  • A Telegram account
  • Create a Telegram Bot using the BotFather and get the bot token

Step 1: Create a Telegram Bot

  1. Open the Telegram app and search for the user “BotFather”.
  2. Start a chat with BotFather and use the command /newbot.
  3. Follow the instructions to set a name and username for your bot.
  4. Once created, you will receive a token that you will use to access the Telegram Bot API. Keep this token safe.

Step 2: Set Up Your Go Environment

Initialize your Go project:

mkdir telegram-bot
cd telegram-bot
go mod init telegram-bot

Step 3: Write the Go Program

Here’s a basic Go program that sends a message using your Telegram bot:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
)

const telegramAPIURL = "https://api.telegram.org/bot"

type Message struct {
    ChatID    string `json:"chat_id"`
    Text      string `json:"text"`
}

func sendMessage(botToken, chatID, text string) error {
    url := fmt.Sprintf("%s%s/sendMessage", telegramAPIURL, botToken)

    message := Message{
        ChatID: chatID,
        Text:   text,
    }

    jsonMessage, err := json.Marshal(message)
    if err != nil {
        return fmt.Errorf("failed to marshal message: %w", err)
    }

    resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonMessage))
    if err != nil {
        return fmt.Errorf("failed to send message: %w", err)
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        return fmt.Errorf("received non-200 response: %s", resp.Status)
    }

    return nil
}

func main() {
    botToken := "YOUR_TELEGRAM_BOT_TOKEN" // replace with your bot token
    chatID := "CHAT_ID"                    // replace with your chat ID
    message := "Hello from Go Telegram Bot!"

    err := sendMessage(botToken, chatID, message)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
    } else {
        fmt.Println("Message sent successfully!")
    }
}

Step 4: Replace Variables

Before running the script, make sure to replace YOUR_TELEGRAM_BOT_TOKEN with the token received from BotFather and CHAT_ID with your chat ID. To get your chat ID, you can use the Telegram API or receive it through an interaction with the bot.

Step 5: Run the Application

Run the Go application with the following command:

go run main.go

If everything is set up correctly, you should see “Message sent successfully!” in the terminal, and the message will appear in the specified Telegram chat.

Conclusion

This article presented a straightforward approach to sending messages using a Telegram bot and Go programming language. Using the Telegram Bot API provides an efficient way to create automated messaging functionalities in your applications. With this foundational example, you can expand your bot’s capabilities, such as receiving messages, responding to commands, and integrating with other services.

References

Feel free to explore additional functionalities provided by the Telegram Bot API and enhance your bot’s capabilities accordingly!