How to create a gamebot in Telegram with nodejs
On October 3, 2016, well-known instant messaging app Telegram launched its gaming platform based on bots that allows video games inside chats.
If you take a look at its introduction to the gaming platform for developers, you’ll find that the technology behind this is HTML5. We’re very happy to see companies like Telegram supporting web standards as the base technology to offer video games to their users. At WiMi5, we’ve been supporting the web as the best option for creating multiplatform content that can be distributed instantly for years. In fact, it’s already become the next video game platform, and decisions like Telegram’s are proof of that.
We immediately got to work and created a bot specifically to serve some of the games created with our HTML5 game creation tool. Now, we’d like to share that experience with you and tell you how to create your own Telegram gamebot.
How do Telegram bots work?
The best idea is to read this introduction to bots for developers, but we’re going to try to explain, or give an overview on, rather, how the bot-based gaming platform works.
Telegram allows you to create bots. When you create a bot, all you’re really doing is creating a special account that receives orders, messages, or user queries from Telegram and answers them. But, in order to answer them, the bot redirects these petitions to a piece of software that you have to develop and execute on your servers, which will then return the reply to the bot so that it will give it to the Telegram user.
On the other hand, you can also create games and assign them to a bot. When you create a Telegram game, what you’re really doing is creating a container for that game’s information: its title, brief description, image, animated .gif (optional), and a short name that will be its identifier.
In a given moment, a Telegram user will ask our bot to play that game. The bot will send the petition to our software, which will reply to the bot with a message to visually present the game with an image and a “start game” button. When the user presses that button, your software will receive the petition, and send back to the bot a URL or web address that contains that game. At that moment, the bot will take the use to that webpage (inside the Telegram app, which has a built-in browser), where the user can finally start playing.
There are more options, such as sending or receiving records, sharing games, etc., but we’ll leave that for another article. In this one, we’re going to focus on understanding how the gaming platform works. For that, we’re going to create a bot that will let us play a game.
1: Creating a bot in Telegram
To create a bot, you have to talk to another bot called @BotFather. Yes, yes, you need a bot to create bots! 😉 Write @BotFather in any chat, or follow this link, and you’ll be able to start a conversation with @BotFather.
To ask it to create a new bot, in the chat conversation with @BotFather, write the command /newbot and answer the simple questions @BotFather asks you.
Once the bot is created, @BotFather will give you a token that you’ll use in your app to contact your bot, as well as a link to your bot that you can use to access it.
2: Creating a game in Telegram and associating it to our bot
To create a game, we also have to talk with @BotFather.
Before creating a game, you must activate the inline mode in the bot you’re going to associate with your game. It’s very easy: just send the command /setinline to @BotFather. It’ll ask what bot you want to put into inline mode; just reply with your bot’s username (don’t forget to put the @ in front!).
Once inline mode is turned on, use the /newgame command to create your game and associate it to your bot. After accepting the rules, respond to a series of questions that @BotFather will ask you, upload an image, and your game will be created!
At this point, like we said before, your game is only an information container: the title, brief description, game photo, an optional animated .gif, and a short name.
@BotFather, after creating the game, will remind you that the game’s short name will be its game identifier when you use Telegram’s API for bots. It will also give you a link to the same so that you can share the game in chats.
3: Creating your software
Now the time has come to give your bot the intelligence it needs to let Telegram users play your game in their chats.
You’ll need to go to the API for Bots, and there, use some of the many libraries that are available. In Telegram, you can find this page, that has excellent bot examples, and libraries based on the main programming languages. In this example, we’re going to be using nodejs along with the Node-Telegram-bot library.
In this library’s own documentation, it explains how to install it and how to create a nodejs app that will answer your bot’s petitions, so use that same structure in your prototype. Simply decide what messages our bot’s going to “understand” and what replies to give, and implement them in your software.
There are two ways to receive messages: commands and queries, or “long polling” and “webhooks”. The differences are explained here. To keep things simple, just stick with “long polling”. In any case, the library we’re using allows either method to be implemented.
Our bot is simply going to understand the start command, which is received whenever a player starts a bot, the play <game_name> command, and inline queries.
To start, you need to add in the chosen library:
Then, create an instance of TelegramBot that will put that library at our disposal, setting up the parameters for your token and for the long polling settings to work in.
This is the moment to give your bot intelligence. Every time a Telegram user writes a command, it will be managed with the onText function in the library.
The onText function expects two parameters: a regular expression and a function. When the message written by the user coincides with the regular expression, the function is run.
Start with the /start command, which we’ll reply to with a greeting that will include the user’s name. Remember that when creating a regular expression, the / always goes at the start of a command.
In the library’s documentation, you’ll see that the sendMessage function expects the chat identifier (which comes from the message we received from Telegram), and the text that we want to send as a parameter. Also, a series of options can be included that you can read in the documentation about sendMessage in the Telegram API. We, for example, have given the message an HTML format, and we included parse_mode as an extra option.
Next, implement the command /play <game_short_name>.
Our regular expression expects /play followed by anything. Our function receives the message and in a second parameter an array with two texts. The second text is all you’ll receive after /play. Check that it matches with your game’s short name. If it doesn’t, send send a message explaining that that game doesn’t exist. If it does match, send out a keyboard with two buttons, one so the user can play the game, and another so the user can share it in other chats.
This time, use the library’s sendGame function. As parameters, it expects the chat id and the games’ short name. Once again, there are other options you can read about in sendGame in the Telegram API. We’re going to use one of them, reply_markup, to send the keyboard. If we didn’t do that, Telegram would automatically add a “play game” button. We’ll send a JSON as a string called InlineKeyboardMarkup, which is in itself an array, InlineKeyboardButton. At this point, there’s a problem in the documentation when it explains the callback_game parameter. According to the documentation, it must contain a CallbackGame that doesn’t need any content. We need to thank Ludei in this article for clearing up how to include the “play game” button; that is, for including a string in JSON format that contains game_short_name. On the other hand, the “share game” button requires our game’s URL.
When the user clicks on the play button, we’ll receive a CallbackQuery, which we’ll manage with the on function for the callback_query event in the library..
On this occasion, our callback for this event will receive an object with the query’s data as a parameter. If this includes the game_short_name property, that will mean it’s a query to play one of our games. Now is the time to reply with our game’s URL, or with an apology if we can’t find the desired game. So, use the answerCallbackQuery function in the library, which needs to send the received query’s id, two parameters related to notifications and alerts that, to keep things simple, today we won’t use, and after, like always, a series of options we can read about in the answerCallbackQuery in the Telegram API. We’re using the url property to send our game’s URL. Once this reply reaches the user, the Telegram app will open our game in its built-in browser.
To finish, we’re going to include a simple handling of inline queries. If a Telegram user writes the name of our bot in a chat, we’ll receive an inline query. Also, from that moment on, every character the user writes or deletes will trigger a new inline query. To manage this, use the on function for the inline_query event in the library.
To reply, use the answerInlineQuery function in the library, which must send the id of the received query, an array of the results, and a series of options you can read about in the answerInlineQuery in the Telegram API.
The results, as you can see in the InlineQueryResult documentation, can be of several types; in our case, they’d be the InlineQueryResultGame type. To keep the example simple, we’ll send “0” as an id and not send a reply_markup.
Our reply is always going to be a list with our games; in this case, the only one we’ve created. But you need to know that in the iq parameter (which is inline query) that we receive in our callback, there is a property called query that has the text that the user has written after our bot’s name. We could use this text to search for games that contain that text and respond to the query with only those games.
Now, all we have to do is run our app so that Telegram users can chat with our bot and, more importantly, enjoy our game.
4: Testing our bot
To play it, we’ll need to run our app on servers capable of supporting millions of queries from Telegram users who want to play our games. But in the testing phase, we can run it straight from our machine, as long as it’s connected to the internet.
Once our app is running, we’re going to access our bot from Telegram. So, write the name of our bot in any chat window, and then select that name. This will start a chat with our bot, and will automatically run our /start command. Check out the greeting we programmed 😉 :
Next, let’s try to play a game that doesn’t exist by writing /play fakegame in the chat window. Then we’ll get the expected response; that is, a message telling us that game doesn’t exist.
Now let’s try to play our test game by writing /play TestGame and, yes, it will show our game’s info along with buttons marked “play” and “share”.
If we press the “share” button, we’ll be able to share it with other Telegram chats, and if we press “play”, our game will open in Telegram’s built-in browser.
Finally, if we write our bot’s name in any chat, the inline queries will automatically turn on, and in our case, we’ll see our only game, which is the reply we programmed.
In the next article, we’ll see how to send scores from our game to other Telegram chats, and how to query our bot about the highest scores in a chat to show them in our game.
02/12/2016 / Kiko Almeida / 3
Instant Games: the beginning of the ‘The Web as a gaming platform’ Instant Games on Facebook Messenger: the HTML5 game wave has arrived
3 thoughts on “How to create a gamebot in Telegram with nodejs”
says:07/07/2017 at 1:02 am
Thanks for sharing the article, through this post, I know more about how Telegram bots work.Reply
says:12/09/2017 at 6:48 am
Thank you for this information on to create bot for the game on HTML5 platform with some examples of coding. Nice one! but how can i show highscores in telegram bot?Reply
says:31/10/2017 at 12:19 am
I hope we can add a port on this question soon.Reply