List of helpers in the library
Our library is mainly a bridge between your application and Telegram Bot API.
However, to simplify your life, we also provide a set of additional helpers methods and services, listed below.
For more advanced features, you can look at high-level bot frameworks constructed around our library
Message and format helpers
message.MessageLink(): Returns the t.me/... link to this message, ornullif the message was not in a Supergroup or Channelmessage.IsServiceMessage: Detect service messages vs content messagesmessage.ToMarkdown()to convert the message to Markdown format (Not recommended)message.ToHtml()to convert the message to HTML format (Recommended)Markdown.Escape()to escape reserved Markdown characters in a stringHtmlText.Escape()to escape reserved HTML characters in a stringHtmlText.ToPlain()to convert HTML string to plain text (removing tags)HtmlText.PlainLength()to get the number of characters of plain text from HTMLHtmlText.Truncate()to truncate HTML string to a number of plain-text characters (while preserving the formatting)bot.SendHtml()to send HTML-formatted messages, with support for sending photos/videos and keyboards from one string
Easier information
chat.ToString()&user.ToString()to easily print/log information about the chat/userChatMemberhas propertiesIsAdminandIsInChatto simplify testing if the user is an admin or currently inside the chatChatMemberhas propertyExpireDate(generic equivalent forUntilDatesubclass properties)ChatMemberRestrictedhas a propertyIsMutedto quickly determine if the user cannot send any type of message
Updates
bot.DropPendingUpdates()to clear the pending updates queueUpdate.AllTypesis a constant array containing allUpdateTypes, usable withGetUpdates/SetWebhookbot.OnMessage/bot.OnUpdateevents to easily subscribe to messages or updates (these automatically start a background task to poll for updates)
Telegram files
bot.GetInfoAndDownloadFileto get file information and download it in a single callTelegramBotClient.GetFileIdType(fileId)to determine the type of object stored behind a FileId (photo, video, etc)
Simplified constructors and implicit conversions
We've added easier ways to construct various instances from other types, especially when passing arguments to methods:
ChatPermissions(bool)andChatAdministratorRights(bool)constructors to set all Can* fields to the specified valueReactionTypefrom an emoji (string) or a customEmojiId (long)ReplyParametersfrom a messageId (int), or aMessageclass, so you can pass these directly for thereplyParameters:argumentLinkPreviewOptionsfrom aboolwheretruemeans to disable the previewLinkPreviewOptionsfrom astringURL to show preview for this linkLabeledPricefrom tuple(string label, long amount)BotCommandfrom tuple(string command, string description)BotCommandScopehas several static methods to construct scopesInputFilefrom astring(fileId or URL), or aStream, or a received media file, ornull
Examples:
await bot.RestrictChatMember(chatId, userId, new ChatPermissions(true)); // unmute
await bot.SetMessageReaction(msg.Chat, msg.Id, ["👍"]);
await bot.SendMessage(msg.Chat, "Visit t.me/tgbots_dotnet", replyParameters: msg, linkPreviewOptions: true);
await bot.SendInvoice(chatId, "Product", "Description", "ProductID", "XTR", [("Price", 500)]);
await Bot.SetMyCommands([("/start", "Start the bot"), ("/privacy", "Privacy policy")], BotCommandScope.AllPrivateChats());
await bot.SendPhoto(msg.Chat, "https://picsum.photos/310/200.jpg");
await bot.SendVideo(msg.Chat, msg.Video, "Sending your video back");
Reply Markup
Keyboards can be easily constructed by passing directly the following type of objects for the replyMarkup: parameter:
| Type | Meaning |
|---|---|
string | single keyboard text button |
string[] or List<string> | keyboard text buttons on one row |
string[][] or List<List<string>> | multiple keyboard text buttons |
KeyboardButton | single keyboard button |
KeyboardButton[] orList<KeyboardButton> | multiple keyboard buttons on one row |
KeyboardButton[][] orList<List<KeyboardButton>> orIEnumerable<KeyboardButton>[] | multiple keyboard buttons |
InlineKeyboardButton | single inline button |
InlineKeyboardButton[] orList<InlineKeyboardButton> | inline buttons on 1 row |
InlineKeyboardButton[][] orList<List<InlineKeyboardButton>> orIEnumerable<InlineKeyboardButton>[] | multiple inline buttons |
Additionally, InlineKeyboardButton can be implicitly constructed from a tuple (string text, string callbackOrUrl) for Callback or Url buttons
await bot.SendMessage(msg.Chat, "Visit our website", replyMarkup: InlineKeyboardButton.WithUrl("Click here", "https://telegrambots.github.io/book/"));
await bot.SendMessage(botOwnerId, $"Annoying user: {msg.From}", replyMarkup: new InlineKeyboardButton[]
{ ("Ban him", $"BAN {msg.From.Id}"), ("Mute him", $"MUTE {msg.From.Id}") });
await bot.SendMessage(msg.Chat, "Keyboard buttons:", replyMarkup: new string[] { "MENU", "INFO", "LANGUAGE" });
Constructing dynamically
ReplyKeyboardMarkup & InlineKeyboardMarkup have methods to help you construct keyboards dynamically:
var replyMarkup = new InlineKeyboardMarkup()
.AddButton(InlineKeyboardButton.WithUrl("Link to Repository", "https://github.com/TelegramBots/Telegram.Bot"))
.AddNewRow().AddButton("callback").AddButton("caption", "data")
.AddNewRow("with", "three", "buttons")
.AddNewRow().AddButtons("A", "B", InlineKeyboardButton.WithSwitchInlineQueryCurrentChat("switch"));
And you can use new ReplyKeyboardMarkup(true) to resize the reply keyboard.
Mini-App and Login widget validation
AuthHelpers.ParseValidateDatashould be used to confirm the authenticity of data received along Telegram's Mini-Apps or the Login Widget javascript requests