Language: English | Русский | Español | Português | Türkçe | Deutsch | Français | Bahasa Indonesia | العربية | فارسی | Oʻzbek | हिन्दी | 中文 | اردو | Tagalog | አማርኛ

← Home

Go Telegram Bot API: get chat_id

In Go Telegram bots, you get chat_id and user_id from the update. Here are examples for common libraries.

Using go-telegram-bot-api/telegram-bot-api

func handleUpdate(bot *tgbotapi.BotAPI, update tgbotapi.Update) {
    if update.Message != nil {
        chatID := update.Message.Chat.ID
        userID := update.Message.From.ID
        msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("Chat ID: %d, User ID: %d", chatID, userID))
        bot.Send(msg)
    }
}

Using tucnak/telebot

bot.Handle("/hello", func(c tele.Context) error {
    chatID := c.Chat().ID
    userID := c.Sender().ID
    return c.Send(fmt.Sprintf("Chat ID: %d, User ID: %d", chatID, userID))
})

From callback query

// telegram-bot-api
if update.CallbackQuery != nil {
    chatID := update.CallbackQuery.Message.Chat.ID
    userID := update.CallbackQuery.From.ID
    // ...
}

// telebot
bot.Handle(tele.OnCallback, func(c tele.Context) error {
    chatID := c.Chat().ID
    userID := c.Sender().ID
    return c.Respond()
})

Debugging with @print_id_bot

Use @print_id_bot to inspect the raw update:

Forward a message to the bot and send /dump to see the exact format.

FAQ

How do I get chat_id when the bot is added to a group?

When a user sends a message, your handler receives the update with Message.Chat.ID. Or add @print_id_bot and send /id to get it manually.

Can I use int64 for chat_id?

Yes. In Go, Telegram IDs are typically int64. Use the type your library provides.

Where is channel_post?

Check update.ChannelPost. For channel posts, ChannelPost.Chat.ID is the channel ID.

Does the update structure match the Telegram API?

Yes. Libraries parse the JSON from the API. Use /dump in @print_id_bot to see the raw structure.

What if From is nil?

For channel_post, there is no From. Check for nil before accessing.


Use @print_id_bot /dump to inspect update structure for Go bots.

Open @print_id_bot


Related pages