Build Telegram Bot with Dart with Televerse đŚ
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 /start
command. 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 â¤ď¸