Funogram: Writing Telegram Bots In F#
Funogram is a strictly-typed Telegram Bot API wrapper built completely in F# — a cross-platform functional-first programming language. If you are new to F#, check this guide to get started. In this article, we are going to build our first Telegram Bot using F#, Funogram and .NET Core.
dotnet new console --lang F#
Then we need to install Funogram and download missing packages:
dotnet add package Funogram && dotnet restore
From that point we can start writing F# code!
Creating a Listener
The easiest way to communicate with Telegram servers is long-polling. Long-polling is an emulation of pushing data, implemented by repeated polling with a delayed response. The good news is, that Funogram takes care of this for us and the only thing we have to do is to invoke the
startBot function— so all updates received from Telegram will trigger our handler.
Note that we don’t have to specify the type of function parameter
context explicitly (it is
Funogram.Bot.UpdateContext indeed), the compiler analyzes our code and infers types for us.
bot-token is a Telegram Bot token received from Bot Father. Let’s run our code to see if everything goes well:
Now it’s time to extend the functionality of our bot. Let’s teach him to greet users. The Funogram libary uses Option Monads for handling optional Telegram API response values instead of nullability. To simplify our codebase and to avoid huge pattern matching nestings we can install the ExtCore library and use a MaybeBuilder from
dotnet add package ExtCore && dotnet restore
If you are new to monads and computation expressions, this article may help you get started. Funogram provides
Funogram.Api.processCommands function allowing us to link commands to handlers.
sendMessage constructs a request to Telegram Bot API, and
api builds an asynchronous operation we need to start using
Now our Telegram bot can greet users!
Funogram sources are available on GitHub. A simple Telegram bot written using the library can be found here. The complete Telegram Bot API reference can be found here, F# types and functions — here and here. If you have any questions, feel free to ask the community on Slack or Telegram!