Funogram: Writing Telegram Bots In F#
Getting started with a new .NET Telegram Bot API library
Telegram is a secure instant messaging service providing a platform that allows creating bots — the Telegram Bot API. A Bot is a Telegram account operated by software. There are Bot API implementations for almost every popular programming language, including Python, JavaScript, and C#. 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.
Getting Started
First, we need to download .NET Core SDK and an IDE we’d like to use — Visual Studio, Rider, or Visual Studio Code with Ionide plugin. To initialize a simple F# console application, we use .NET CLI:
dotnet new console --lang F#
Then we need to install Funogram and download the 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 through 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 every update 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:
dotnet run
Handling Commands
Now it’s time to extend the functionality of our bot. Let’s teach him to greet users. The Funogram library 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 theExtCore.Control
module.
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 Async.Start
function.
Now our Telegram bot can greet users!
Further Learning
Funogram sources are available on GitHub. The complete Telegram Bot API reference can be found here, F# types and functions — here and here. If you get the Unable to read data from the transport connection
exception, then it seems that Telegram is blocked in your country and you may need to set up a proxy. If you have any additional questions, feel free to ask the community on Slack or Telegram!