Funogram: Writing Telegram Bots In F#

Telegram is a secure instant messaging service, providing a platform allowing for third-party developers to create bots — Telegram Bot API. A Bot is a Telegram account operated by software. There are Bot API implementations for almost every popular programming language — Python, JavaScript, 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 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:

dotnet run

Handling Commands

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 ExtCore.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.

A simple Telegram bot listening to ‘/hello’ commands and responding ‘Hello, %username%!’

Now our Telegram bot can greet users!

Telegram bot greets ‘/hello’ command issuer

Further Learning

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!