telegram/bot
Building a bot with the Bot API: messages, buttons, webhooks and a polling loop.
import telegram.bot
To build a bot, get a token from BotFather and make one with NewBot. A bot has two ways of taking messages: Poll, which asks Telegram itself and suits testing and simple servers, or a webhook, where Telegram POSTs the messages to your server.
With a webhook you can send the answer straight in the body of the HTTP response; the Reply... functions build that JSON text. Set a secret with SetWebhookSecret and check its header on every request.
Types
User
struct User| Name | Type | Description |
|---|---|---|
id | i64 = 0 | The id. |
is_bot | bool = false | It is a bot. |
first_name | str = "" | The first name. |
last_name | str = "" | The last name. |
username | str = "" | The user name. |
language_code | str = "" | The language of the user, such as fa. |
import telegram.bot
func main:
text := `{"update_id":10,"message":{"message_id":5,"date":1700000000,"text":"/start hello","chat":{"id":42,"type":"private","first_name":"Maryam","username":"maryam"},"from":{"id":42,"is_bot":false,"first_name":"Maryam","language_code":"en"},"reply_to_message":{"message_id":4,"from":{"id":7,"first_name":"Ali"}}}}`
update := bot.ParseUpdate(text)
println update.update_id, update.has_message, update.has_callback_query
m := update.message
println m.message_id, m.date, m.text, m.chat.id, m.chat.chat_type, m.chat.first_name, m.chat.username
println m.from_user.id, m.from_user.is_bot, m.from_user.language_code, m.reply_to.message_id, m.reply_to.user_id, m.reply_to.user_name
println bot.IsCommand(m.text), bot.CommandName(m.text), bot.CommandArgs(m.text)
println bot.IsCommand("hello"), bot.CommandName("/help@my_bot")
all := bot.ParseUpdates(`{"ok":true,"result":[{"update_id":11,"callback_query":{"id":"cq1","data":"yes","from":{"id":42,"first_name":"Maryam"},"message":{"message_id":9,"chat":{"id":42,"type":"private"}}}},{"update_id":12,"inline_query":{"id":"iq1","query":"book","offset":"","from":{"id":42,"first_name":"Maryam"}}}]}`)
println all.len()
q := all[0].callback_query
println all[0].has_callback_query, q.id, q.data, q.from_user.first_name, q.has_message, q.message.message_id
typed := all[1].inline_query
println all[1].has_inline_query, typed.id, typed.query, typed.offset.len()
println bot.ParseUser(`{"id":1,"first_name":"x","last_name":"y","is_bot":true}`).last_name
println bot.ParseChat(`{"id":-100,"type":"supergroup","title":"the group"}`).title
println bot.ParseMessage(`{"message_id":1,"caption":"a photo","chat":{"id":1}}`).caption
println bot.ParseCallbackQuery(`{"id":"q","data":"d"}`).data, bot.ParseInlineQuery(`{"id":"i","query":"q"}`).query
println bot.ParseUpdate(`{"update_id":13,"channel_post":{"message_id":1,"text":"news","chat":{"id":-5}}}`).channel_post.text
mut row1 := Vector {} as Vector<str>
row1.push(bot.InlineButton("yes", "yes"))
row1.push(bot.InlineButton("no", "no"))
mut row2 := Vector {} as Vector<str>
row2.push(bot.InlineButtonURL("the site", "https://salamlang.ir"))
mut rows := Vector {} as Vector<str>
rows.push(bot.Row(row1))
rows.push(bot.Row(row2))
println bot.InlineKeyboardMarkup(rows)
mut plain := Vector {} as Vector<str>
plain.push(bot.KeyboardButton("menu"))
mut plain_rows := Vector {} as Vector<str>
plain_rows.push(bot.Row(plain))
println bot.ReplyKeyboardMarkup(plain_rows)
println bot.RemoveKeyboard(), bot.ForceReply()
println bot.BotCommand("start", "start it")
robot := bot.NewBot("123:ABC")
println bot.FileURL(robot, "photos/file_1.jpg")
println bot.ReplyMessage(42, "hello")
mut options := bot.SendOptions {}
options.parse_mode = "HTML"
options.reply_to_message_id = 5
options.disable_notification = true
println bot.ReplyMessageOptions(42, "<b>hello</b>", options)
println bot.ReplyAnswerCallbackQuery("cq1", "noted", false)
println bot.ReplyChatAction(42, "typing")
println bot.ReplyEditMessageText(42, 9, "updated", bot.RemoveKeyboard())
println bot.SECRET_HEADER
endChat
struct Chat| Name | Type | Description |
|---|---|---|
id | i64 = 0 | The id; negative for groups. |
chat_type | str = "" | The type: private, group, supergroup or channel. |
title | str = "" | The title of the group or channel. |
username | str = "" | The user name. |
first_name | str = "" | The first name. |
last_name | str = "" | The last name. |
The example for this item is shown with the ones above: telegram-bot-Parse.salam
ReplyTo
struct ReplyTo| Name | Type | Description |
|---|---|---|
message_id | i64 = 0 | The id of that message. |
user_id | i64 = 0 | The id of its sender. |
user_name | str = "" | The name of its sender. |
import telegram.bot
import env
func handle(update: bot.Update):
if not update.has_message:
ret
end
println update.message.from_user.first_name, update.message.text
end
func main:
robot := bot.NewBot(env.Get("TELEGRAM_TOKEN"))
me := bot.GetMe(robot)
if not bot.Ok(me):
println me.error_code, me.description, me.http_status, me.http_err
ret
end
println me.ok, me.result
chat := 42 as i64
_ := bot.SendMessage(robot, chat, "hello")
_ := bot.SendMessage(robot, "@my_channel", "fresh news")
mut options := bot.SendOptions {}
options.parse_mode = "Markdown"
options.reply_markup = bot.RemoveKeyboard()
_ := bot.SendMessageOptions(robot, chat, "*important*", options)
_ := bot.SendPhoto(robot, chat, "https://example.com/a.jpg", "a photo")
_ := bot.SendDocument(robot, chat, "BQACAgQAAx", "")
_ := bot.SendVideo(robot, chat, "https://example.com/v.mp4", "")
_ := bot.SendAudio(robot, chat, "https://example.com/a.mp3", "")
_ := bot.SendVoice(robot, chat, "AwACAgQ", "")
_ := bot.SendSticker(robot, chat, "CAACAgI")
_ := bot.SendLocation(robot, chat, 35.6997, 51.338)
_ := bot.SendContact(robot, chat, "+989120000000", "Ali")
_ := bot.SendChatAction(robot, chat, "typing")
_ := bot.EditMessageText(robot, chat, 10, "edited")
_ := bot.ForwardMessage(robot, chat, 43, 11)
_ := bot.PinChatMessage(robot, chat, 10)
_ := bot.UnpinChatMessage(robot, chat, 10)
_ := bot.DeleteMessage(robot, chat, 10)
_ := bot.AnswerCallbackQuery(robot, "cq1", "noted")
_ := bot.AnswerInlineQuery(robot, "iq1", "[]")
file := bot.GetFile(robot, "AgACAgQ")
println file.result.len() > 0
_ := bot.GetChat(robot, chat)
_ := bot.GetChatMemberCount(robot, chat)
_ := bot.GetChatMember(robot, chat, 7)
_ := bot.BanChatMember(robot, chat, 7)
_ := bot.UnbanChatMember(robot, chat, 7)
_ := bot.LeaveChat(robot, -100)
mut commands := Vector {} as Vector<str>
commands.push(bot.BotCommand("start", "start it"))
_ := bot.SetMyCommands(robot, commands)
_ := bot.SetWebhook(robot, "https://example.com/hook")
_ := bot.SetWebhookSecret(robot, "https://example.com/hook", "my-secret")
_ := bot.GetWebhookInfo(robot)
_ := bot.DeleteWebhook(robot)
mut params := HashMap {} as HashMap<str, str>
params.insert("chat_id", "42")
_ := bot.Call(robot, "getChatAdministrators", params)
updates := bot.GetUpdates(robot, 0, 10, 30)
println bot.ParseUpdates(updates.result).len(), robot.token.len() > 0
bot.Poll(robot, 30, (update: bot.Update):
handle(update)
end)
endMessage
struct Message| Name | Type | Description |
|---|---|---|
message_id | i64 = 0 | The id. |
date | i64 = 0 | The time in Unix seconds. |
chat | Chat | The chat. |
from_user | User | The sender. |
text | str = "" | The text. |
caption | str = "" | The caption of a photo or file. |
reply_to | ReplyTo | The message that was replied to. |
The example for this item is shown with the ones above: telegram-bot-Parse.salam
CallbackQuery
struct CallbackQuery| Name | Type | Description |
|---|---|---|
id | str = "" | The id; answer with it. |
from_user | User | The user. |
message | Message | The message the button was in. |
has_message | bool = false | It has a message. |
data | str = "" | The data of the button. |
The example for this item is shown with the ones above: telegram-bot-Parse.salam
InlineQuery
struct InlineQuery@bot.| Name | Type | Description |
|---|---|---|
id | str = "" | The id. |
from_user | User | The user. |
query | str = "" | The text. |
offset | str = "" | The paging position. |
The example for this item is shown with the ones above: telegram-bot-Parse.salam
Update
struct Update| Name | Type | Description |
|---|---|---|
update_id | i64 = 0 | The id; pass one more than it to the next GetUpdates. |
message | Message | The message. |
has_message | bool = false | It has a message. |
channel_post | Message | A channel post. |
has_channel_post | bool = false | It has a channel post. |
callback_query | CallbackQuery | A button press. |
has_callback_query | bool = false | It has a button press. |
inline_query | InlineQuery | An inline query. |
has_inline_query | bool = false | It has an inline query. |
The example for this item is shown with the ones above: telegram-bot-Parse.salam
ApiResponse
struct ApiResponse| Name | Type | Description |
|---|---|---|
ok | bool = false | It succeeded. |
result | str = "" | The result as JSON. |
description | str = "" | The error description. |
error_code | i64 = 0 | The Telegram error code. |
http_status | int = 0 | The HTTP status code. |
http_err | str = "" | The network error. |
The example for this item is shown with the ones above: telegram-bot-Bot.salam
SendOptions
struct SendOptions| Name | Type | Description |
|---|---|---|
parse_mode | str = "" | The text format: HTML or MarkdownV2. |
disable_notification | bool = false | Send it silently. |
reply_to_message_id | i64 = 0 | Reply to this message. |
reply_markup | str = "" | The keyboard as JSON. |
The example for this item is shown with the ones above: telegram-bot-Parse.salam
Bot
struct Bot| Name | Type | Description |
|---|---|---|
token | str = "" | The token from BotFather; keep it secret. |
The example for this item is shown with the ones above: telegram-bot-Parse.salam
Constants and variables
SECRET_HEADER
const SECRET_HEADER: str = "X-Telegram-Bot-Api-Secret-Token"import telegram.bot
import net.http
import net.router
func webhook(ctx: i64):
if http.Ctx_header(ctx, bot.SECRET_HEADER) != "my-secret":
http.Ctx_status(ctx, 403)
http.Ctx_text(ctx, "forbidden")
ret
end
update := bot.ParseUpdate(http.Ctx_body(ctx))
if update.has_message and bot.IsCommand(update.message.text):
answer := "the command " + bot.CommandName(update.message.text) + " arrived"
http.Ctx_json(ctx, bot.ReplyMessage(update.message.chat.id, answer))
else update.has_callback_query:
http.Ctx_json(ctx, bot.ReplyAnswerCallbackQuery(update.callback_query.id, "all right", true))
else:
http.Ctx_text(ctx, "ok")
end
end
func main:
mut r := router.NewRouter()
router.Post(r, "/hook", webhook)
mut s := http.NewServer(19632)
http.Use(s, r)
_ := http.RunBackground(s)
mut headers := http.NewHeaders()
headers.insert(bot.SECRET_HEADER, "my-secret")
headers.insert("Content-Type", "application/json")
a := http.PostWith("http://127.0.0.1:19632/hook", `{"update_id":1,"message":{"message_id":2,"text":"/start","chat":{"id":42,"type":"private"}}}`, headers)
println http.Status(a), http.Body(a)
b := http.PostWith("http://127.0.0.1:19632/hook", `{"update_id":2,"callback_query":{"id":"cq9","data":"x","from":{"id":42}}}`, headers)
println http.Body(b)
c := http.Post("http://127.0.0.1:19632/hook", "{}")
println http.Status(c)
endFunctions
ParseUser
func ParseUser(raw: str): UserThe example for this item is shown with the ones above: telegram-bot-Parse.salam
ParseChat
func ParseChat(raw: str): ChatThe example for this item is shown with the ones above: telegram-bot-Parse.salam
ParseMessage
func ParseMessage(raw: str): MessageThe example for this item is shown with the ones above: telegram-bot-Parse.salam
ParseCallbackQuery
func ParseCallbackQuery(raw: str): CallbackQueryThe example for this item is shown with the ones above: telegram-bot-Parse.salam
ParseInlineQuery
func ParseInlineQuery(raw: str): InlineQueryThe example for this item is shown with the ones above: telegram-bot-Parse.salam
ParseUpdate
func ParseUpdate(raw: str): UpdateThe example for this item is shown with the ones above: telegram-bot-Parse.salam
ParseUpdates
func ParseUpdates(raw: str): Vector<Update>getUpdates into a list of updates.The example for this item is shown with the ones above: telegram-bot-Parse.salam
NewBot
func NewBot(token: str): BotThe example for this item is shown with the ones above: telegram-bot-Parse.salam
Ok
func Ok(resp: ApiResponse): boolThe example for this item is shown with the ones above: telegram-bot-Bot.salam
Call
func Call(bot: Bot, method: str, params: HashMap<str, str>): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
GetMe
func GetMe(bot: Bot): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
GetUpdates
func GetUpdates(bot: Bot, offset: i64, limit: i64, timeout: i64): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
SendMessage
func SendMessage(bot: Bot, chat_id: i64, text: str): ApiResponse@channel.The example for this item is shown with the ones above: telegram-bot-Bot.salam
SendMessage
func SendMessage(bot: Bot, chat_id: str, text: str): ApiResponse@channel.The example for this item is shown with the ones above: telegram-bot-Bot.salam
SendMessageOptions
func SendMessageOptions(bot: Bot, chat_id: i64, text: str, opts: SendOptions): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
SendPhoto
func SendPhoto(bot: Bot, chat_id: i64, photo: str, caption: str): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
SendDocument
func SendDocument(bot: Bot, chat_id: i64, document: str, caption: str): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
SendVideo
func SendVideo(bot: Bot, chat_id: i64, video: str, caption: str): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
SendAudio
func SendAudio(bot: Bot, chat_id: i64, audio: str, caption: str): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
SendVoice
func SendVoice(bot: Bot, chat_id: i64, voice: str, caption: str): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
SendSticker
func SendSticker(bot: Bot, chat_id: i64, sticker: str): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
SendLocation
func SendLocation(bot: Bot, chat_id: i64, latitude: f64, longitude: f64): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
SendContact
func SendContact(bot: Bot, chat_id: i64, phone_number: str, first_name: str): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
SendChatAction
func SendChatAction(bot: Bot, chat_id: i64, action: str): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
EditMessageText
func EditMessageText(bot: Bot, chat_id: i64, message_id: i64, text: str): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Parse.salam
DeleteMessage
func DeleteMessage(bot: Bot, chat_id: i64, message_id: i64): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
ForwardMessage
func ForwardMessage(bot: Bot, chat_id: i64, from_chat_id: i64, message_id: i64): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
PinChatMessage
func PinChatMessage(bot: Bot, chat_id: i64, message_id: i64): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
UnpinChatMessage
func UnpinChatMessage(bot: Bot, chat_id: i64, message_id: i64): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
AnswerCallbackQuery
func AnswerCallbackQuery(bot: Bot, callback_query_id: str, text: str): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
AnswerInlineQuery
func AnswerInlineQuery(bot: Bot, inline_query_id: str, results: str): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
GetFile
func GetFile(bot: Bot, file_id: str): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
FileURL
func FileURL(bot: Bot, file_path: str): strThe example for this item is shown with the ones above: telegram-bot-Parse.salam
GetChat
func GetChat(bot: Bot, chat_id: i64): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
GetChatMemberCount
func GetChatMemberCount(bot: Bot, chat_id: i64): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
GetChatMember
func GetChatMember(bot: Bot, chat_id: i64, user_id: i64): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
LeaveChat
func LeaveChat(bot: Bot, chat_id: i64): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
BanChatMember
func BanChatMember(bot: Bot, chat_id: i64, user_id: i64): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
UnbanChatMember
func UnbanChatMember(bot: Bot, chat_id: i64, user_id: i64): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
SetWebhook
func SetWebhook(bot: Bot, url: str): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
DeleteWebhook
func DeleteWebhook(bot: Bot): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
GetWebhookInfo
func GetWebhookInfo(bot: Bot): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
BotCommand
func BotCommand(command: str, description: str): strThe example for this item is shown with the ones above: telegram-bot-Parse.salam
SetMyCommands
func SetMyCommands(bot: Bot, commands: Vector<str>): ApiResponseThe example for this item is shown with the ones above: telegram-bot-Bot.salam
InlineButton
func InlineButton(text: str, callback_data: str): strThe example for this item is shown with the ones above: telegram-bot-Parse.salam
InlineButtonURL
func InlineButtonURL(text: str, url: str): strThe example for this item is shown with the ones above: telegram-bot-Parse.salam
KeyboardButton
func KeyboardButton(text: str): strThe example for this item is shown with the ones above: telegram-bot-Parse.salam
Row
func Row(buttons: Vector<str>): strThe example for this item is shown with the ones above: telegram-bot-Parse.salam
InlineKeyboardMarkup
func InlineKeyboardMarkup(rows: Vector<str>): strThe example for this item is shown with the ones above: telegram-bot-Parse.salam
ReplyKeyboardMarkup
func ReplyKeyboardMarkup(rows: Vector<str>): strThe example for this item is shown with the ones above: telegram-bot-Parse.salam
RemoveKeyboard
func RemoveKeyboard(): strThe example for this item is shown with the ones above: telegram-bot-Parse.salam
ForceReply
func ForceReply(): strThe example for this item is shown with the ones above: telegram-bot-Parse.salam
IsCommand
func IsCommand(text: str): bool/.The example for this item is shown with the ones above: telegram-bot-Parse.salam
CommandName
func CommandName(text: str): str/ and without @bot.The example for this item is shown with the ones above: telegram-bot-Parse.salam
CommandArgs
func CommandArgs(text: str): strThe example for this item is shown with the ones above: telegram-bot-Parse.salam
Poll
func Poll(bot: Bot, timeout: i64, handler: func(Update))The example for this item is shown with the ones above: telegram-bot-Bot.salam
SetWebhookSecret
func SetWebhookSecret(bot: Bot, url: str, secret_token: str): ApiResponseSECRET_HEADER header; reject forged requests with it.The example for this item is shown with the ones above: telegram-bot-Bot.salam
ReplyMessage
func ReplyMessage(chat_id: i64, text: str): strThe example for this item is shown with the ones above: telegram-bot-Webhook.salam
ReplyMessageOptions
func ReplyMessageOptions(chat_id: i64, text: str, opts: SendOptions): strThe example for this item is shown with the ones above: telegram-bot-Parse.salam
ReplyEditMessageText
func ReplyEditMessageText(chat_id: i64, message_id: i64, text: str, reply_markup: str): strThe example for this item is shown with the ones above: telegram-bot-Parse.salam
ReplyAnswerCallbackQuery
func ReplyAnswerCallbackQuery(callback_query_id: str, text: str, show_alert: bool): strThe example for this item is shown with the ones above: telegram-bot-Webhook.salam
ReplyChatAction
func ReplyChatAction(chat_id: i64, action: str): strThe example for this item is shown with the ones above: telegram-bot-Parse.salam