Build Telegram Bot with Dart with Televerse 🐦

Sreelal TS
5 min readApr 16, 2023
Banner

Finally, you’re here, after endless googling and pub.dev searches, you’re right here into this story. I just want to greet you, “Hello Dear Dev!”.

You’re here and there’s only one obvious reason for that. You 💙 Dart! You do it with passion. You don’t want to leave Dart and go for another language to write a Telegram bot. You’re welcome home, dear!

Introduction

I’ve been facing the same phase you’re in right now. I wanted a Dart package to be able to write high-quality Telegram bots. As we all do, I went to pub.dev and searched “telegram bot”. One package caught my attention. You guessed it right, TeleDart. It was a good experience. But, coming from grammY, I couldn’t really be tailored with TeleDart for long. And you know what they say:

if you don’t see a solution exist, create one

Televerse 🪐

I wanted an all-powerful tool to build efficient bots, but it should be as simple as a novice developer can build their own bot with it. I started building it and came up with what you’re about to see. Special thanks to my lovely girlfriend who suggested the name Televerse! ❤️

Let’s begin

First things first, you need to create a Dart/Flutter project where you’ll be building your bot.

dart create my_awesome_bot

Now open up your pubspec.yaml file and get Televerse.

dependencies:
televerse: ^1.5.6

Now go to @BotFather and send /newbot to create your bot. Obtain the Bot TOKEN from the BotFather.

Quick Decision Break

Let’s pause for a while and think about the bot we’re building.

Action Plan 1: Our bot should greet the user well. Who doesn’t like to be greeted by their name?

Action Plan 2: Once the conversation started, the bot should ask the user who’s their favorite Avenger! ⚡️ Also, gives the user a set of options to choose from. We can use an Inline Keyboard or Keyboard for this.

Action Plan 3: Let’s stick with the Keyboard. Now, when the user sends back an option, we’ll send a GIF related to the selected option.

Enough talking, show me some code! 👨🏻‍💻

Yes yes, we’re about there. Let’s get our hands dirty with code.

When it’s a very simple project, I don’t really care about the initial Dart project structure and I can just code everything up in the bin/my_awesome_bot.dart file itself. So, I’m going to head over to the project and delete both my test/ and lib/ directories. Here we go. Real coding starts right here, right now.

First, we want to create a bot instance. The Televerse class itself is the one you should be looking for. Import the Televerse library, and create your bot instance by passing the BOT TOKEN obtained from @BotFather.

import 'package:televerse/televerse.dart';

void main(List<String> arguments) {
Bot bot = Bot("<YOUR BOT TOKEN HERE>");
}

Now, to start listening to updates. You can simply call bot.start() method.

Action Plan 1: Greet the user

You already know this, when a user starts a conversation with the bot it always happens with the /start command. So, let’s create our first handler for incoming /start commands. Televerse provides a set of powerful methods which you can make use of to listen for particular events. Here, commands. We have Televerse.command a method just for that. The command() method accepts two parameters. One is a Pattern that defines which particular incoming command should be the handler triggered for.

Good news! You don’t have to use Televerse.command a method to listen to the /startcommand. Since commands /start, /settings, /help are very usual, you can simply use Televerse.start, Televerse.settings, Televerse.help methods respectively just for these. One thing to note the Televerse.start method is used to start listening to updates and to attach a command listener for the /start command, both combined together.

This is how evolution happened :)

That’s another bit of talk. Now get back to the code: we can use the start method to set up the listener for the /start command as follows:

To set up a command listener you should pass a callback function that accepts a special type of parameter called Context parameter. The context parameter gives you relevant information about the incoming message. Since /start command is a message. You’ll receive a parameter of the type MessageContext .

bot.start((ctx){
final name = ctx.message.from?.firstName ?? "Anonymous";
ctx.reply("Hello $name!");
});

You’re more than ready to start your test flight. Run the following command in the terminal, go to your bot on Telegram, and send /start.

dart run

Yayy!!! Your first bot with Televerse is up and running! 🎉

Action Plan 2

Ask the user who’s their favorite Avenger and show the options Keyboard. Choice selection with Keyboards is indeed an amazing feature of Telegram. Building Keyboards are never a pain again. With Televerse, you can use the Keyboard class just for that.

Let’s look at how to create a Keyboard simply, and use it. Keep this inside the (ctx) { … } callback function.

Keyboard optionsKeyboard = Keyboard()
.addText("Iron Man")
.addText("Captain America")
.row()
.addText("Thor")
.addText("Hulk")
.row()
.addText("Black Widow")
.resized();

ctx.reply(
"Who's your favorite Avenger?",
replyMarkup: optionsKeyboard,
);

I bet you’ll love to see what you came up with. Restart the Dart process and send /start again.

Action Plan 3

Get the user input, and send a related GIF back. For this, let’s first create a Map of related GIFs that we’ll send to our users. Let’s hardcode for this time. I’ve copied some GIPHY links for that.

  Map<String, String> gifs = {
"Iron Man": "https://media.giphy.com/media/8xomIW1DRelmo/giphy.gif",
"Captain America": "https://media.giphy.com/media/qadvd1vBaZBBu/giphy.gif",
"Thor": "https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExYWViZDdiN2Q0YWQzZDQ2ZDQyOWE1ZjYxZWZhZTQwMDA5ZjJmMGZiMCZjdD1n/qWoubkSvQxN1C/giphy.gif",
"Hulk": "https://media.giphy.com/media/xFBnkMvpTM6m4/giphy.gif",
"Black Widow": "https://media.giphy.com/media/fcGuamXXetf5S/giphy.gif",
"Oh no": "https://media.giphy.com/media/9Fticsj7froxbpd5Sg/giphy.gif",
};

After that, we need to match the user input right? Lemme introduce you to one of the powerful Televerse methods — Televerse.hears . hears does exactly what it says, when it hears a message that matches the passed RegEx, the particular callback function will be triggered. Easy, right?

And when you’re dealing with RegEx when a match is found all the matches will be stored right inside the context object as ctx.matches. So, we can use the following code to complete our third action plan.

final regexp = RegExp(r"^(Iron Man|Captain America|Thor|Hulk|Black Widow)$");

bot.hears(regexp, (ctx) {
final hero = ctx.matches?[0].group(0) ?? "Oh no";

final gif = gifs[hero] ?? gifs["Oh no"]!;

ctx.replyWithAnimation(InputFile.fromUrl(gif));
});

You can see the full code for this bot at our TeleverseExamples repository on GitHub!

TADAA!!!! 🚀

Congratulations on building your first bot with Televerse!

There are many more methods and getters that can make your life much easier. I hope you had a great time learning something new.

If you find Televerse is worth your time, please consider starring us on GitHub.

Outro!

I wanna mention the community behind Televerse. You can surely jump in any time you love to. We have an active group on Telegram where we can discuss the project, and doubts, and build things together. Once again, you’re more welcome :)

Telegram Group: @TeleverseDart

Thank you so much for reading ❤️

--

--

Sreelal TS

codes • dreams • thoughts . 💙 Organizer, Flutter Kozhikode 🥇 Platinum Product Expert at Google PE Program #Flutter #GDGKozhikode