How to adapt HTML5 games to be published on Telegram

The Announcement

On October 3rd, Telegram published its gaming platform. Now, the bots are able to launch HTML5 games inside Telegram and share your score with your friends. @gamebot and @gamee were the two first bots announced and Ludei is not going to be the last when it comes to HTML5.

The Rules

When creating a game with @BotFather, he will make you accept a series of rules:

  1. You will not implement any ads or any external links on your custom URL pages.
  2. You will not invite users to pay for any services provided on custom URL pages.
  3. You will not use any data collected over the course of user interaction with your custom URLs for spamming Telegram users.
  4. You will not transfer any Telegram data collected over the course of user interaction with your custom URLs to any third parties.
  5. In order to protect the privacy of Telegram users, your custom URL pages must not set any cookies.

Now, those are some serious rules that made us change some things in our games.

Due to these rules we had to remove every way of promoting the rest of our games and every social media integration like Twitter or Facebook. Thankfully, we didn’t collect any information for third parties neither used cookies in our games -removing all that sounds like a headache.

Game Rules by @BotFather

Game rules by @BotFather

Sharing the games

The first thing you notice when reading the technical post is the script you have to include inside your games. It is a rather short script. This is because launching a game inside Telegram means opening a URL, provided by our bot, in the webview of Telegram. Our game should need hardly any changes.

<script src="https://telegram.org/js/games.js"></script>

This script provides us with the TelegramGameProxy.shareScore() method, which is used to share the game (but not a score, weird) with Telegram chats. It works like the usual share button in Telegram, there is no complexity with this part. We added a button with the shareScore() function at the result screen of each game in case you don’t know what to do with it.

Sending scores

The name “shareScore“ is quite confusing since you can’t even pass it a parameter to share. To actually send a score you should also read our post about a game bot creation. The game must send the score to the bot (with a HTTP POST, in our case) and the bot is responsible of notifying Telegram of our score. But how does the bot know who we are when it receives it? We solved this problem sending along the score a number of identifiers the bot previously added to the URL of the page. These identifiers are always userId (identifies the user) and either inlineId (if the bot was summoned with an inline call), or the pair chatId and messageId. The necessary ones are in the request Telegram sends to our bot when a user taps the play button.

Update scores in Telegram

@ludeiBot updates scores in Telegram

To sum it up: the user activates the play button, Telegram asks our bot for a URL to open and sends the identifications of the user, the bot returns a URL containing those identifiers in a query, and finally, our game can send the score and the identifiers of the user so the bot can update the rankings.

Detecting Telegram

At this point we have a game that can be published to Telegram, but why would we use two versions of the source code of our game? We still want to be able to promote our games if the user plays at ludei.net. If we can know when the game is executing as a Telegram game we can serve it from its original server to Telegram. Any special change we made for Telegram just has to follow a condition.

At first we tried checking window.TelegramWebviewProxy !== undefined  (like Telegram does in its script), but somehow TelegramWebviewProxy is undefined even inside the Telegram webview, so in the end, we just check if the URL contains the identifiers of Telegram our bot adds. In our case the identifiers were query parameters because our games already had a method to parse them. Although they could have been hash parameter too; Telegram exposes an object containing them.

Testing your game

The last thing to do is testing. Most of the testing can be done easily like with any web page development: set up a local server and open the URL in your devices. But we found some resolution problems when Telegram launched the games. Some elements appeared several times larger than when using a typical browser app. Therefore, one last advice from us is to create a minimal test bot, capable of just launching the games, enough to be able to fix any bug that might appear only in Telegram.

Our games

Check out our games (please open the following links on your mobile device):

How to create a game bot and publish your HTML5 games on Telegram

At Ludei we love HTML5 games, that’s what our motto is. That’s us. We have developed a lot of HTML5 games, from showcases to test our Cocoon.io platform to fully featured games, with 20M+ downloads. On October 3rd the Telegram team announced its gaming platform, a ready to play, easy to build, social and lightweight solution to provide digital entertainment to Telegram users (like us, the Ludei team). As Telegram’sg announcement tells us: “the underlying technology is HTML5…” , we may have an idea here; grass is green.

html5_logo_512

After we checked the examples provided and the documentation, we decided that our bot (@ludeiBot) should be capable of serving our games, setting the user’s score and answering inline queries. All this while being a social bot, that is, our bot and our games can and are going to be easily shareable on Telegram itself. Let’s start!

For the bot creation you must contact @BotFather, answer all the questions wisely and you will have your bot available to the world. 

Botfather logo

Botfather logo

 

When your bot is correctly created you have to register your games on Telegram. A name, a short name, a description and a correctly sized photo is enough for Telegram’s “/newgame” command.

First of all, how are we going to access the Telegram API? A fast Google search returns lots of good and reliable (frequently updated) libraries written in the most modern programming languages. We can choose what to use, there is no problem here. We chose TelegramsBots Java library and the Java programming language.

There are two kinds of Telegram bots depending on how they receive Telegram’s updates. The long polling and webhook bots, for the first prototype, lets keep it simple (KIS(S)). The webhook server requires a server accessible by Telegram while the long-polling bot doesn’t, so we chose the long-polling method for the prototype.

telegram_logo

The first command a bot receives from any user is the “/start” command. Is there a better way to start learning the API? From there we move to our own defined commands, “/list”, “/play” and “/random”.

The list command shows our list of games, so we need to store them before answering the command request but, what is the information needed to send a game to a user on Telegram? The only properties needed to send a game are where to send it and what game we are sending, the “chatId” and the game “short name” (the same we registered when creating our game).

With that information stored on the server, we send a list of games using a custom Telegram keyboard to let the user graphically select the desired game.

Telegram's inline keyboard.

Telegram’s inline keyboard.

When a user taps on one of the buttons we defined, the text written on that button is sent back to the server. We process that message and if it follows a concrete arbitrary pattern (“▶️ gameShortName” in our case) we answer the request which executes the”/play” command of our bot.

The “/play” command does the proper game sending process. To do so, we just call Telegram’s API indicating the chatId and the game’s shortname. We also send a custom inline keyboard in this response with two buttons. The first button must, as the documentation indicates, always be the play button.

We had some problems sending this button because we were a little confused by the documentation stating that the “CallbackGame” value is just “a placeholder, currently holds no information”. When trying to set the callback game with this empty placeholder the button (as our logic expected) doesn’t do anything at all.

After reading our Telegram API library source code, we discovered that a proper game callback does contain some values and after setting up a JSON with a unique field “game_short_name” the button works. Please, check the following code snippet:

The “play with friends” button just shares a URL the way the API shares any other URL:

The last command is “/random”, that just selects a random game and sends it back to the channel it was requested from. Internally, it calls the “/play” command again with the game shortname parameter filled (yay, code reuse!).

There is also another topic: the inline queries. Just name our bot @ludeiBot and after writing this, hit space and start writing anything. If one of our games contains the string you have introduced then that game will appear immediately so you can tap and start playing it.

This can be done thanks to Telegram’s inline mode. Each time a user enters a new character, Telegram sends us a new inline query. We get the query text and look for a game containing that text, we collect all the matching games and we send them back before the user can even notice what is happening.

Wait; a request each time a user changes a character, how many requests are we going to process? Can we answer all those requests fast enough for a nice user experience? We use Amazon’s Lambda for other internal services and we have some experience with it, could our bot be hosted in this extremely useful service?

Again, after a fast search we found lots of tutorials helping us with this concrete need , we just need to set Telegram’s webhook location to an Amazon API Gateway endpoint that launches a Lambda function calling our bot with the received update from Telegram.

Just one Amazon Lambda function is enough to receive all the messages from Telegram, process them and answer all the requests. And all this is done in less than 70 ms without spending too much time on code optimization (this could surely be faster) and without losing time and resources dealing with lateral escalation.

amazon-api-gateway-and-aws-lambda

Another message that must be processed is the callbackQuery that is being produced when the user taps the “play solo” button of our game message. When the user taps the button, we receive a callbackQuery from the Telegram API containing the tapped game shortName parameter indicating which game the user has selected as well as other parameters.

In order to let the user play, we must then answer this callback with the game’s URL and then Telegram will redirect the user to the game’s site and display it in a webview-like environment.

The last requirement is the score sharing functionality. In order to send a score to Telegram’s API, we have to receive the userId of the player who is scoring, and either both the chatId and the messageId from the chat the game is being played on or only the inlineMessageId from which the game has been launched from.

All this parameters are received in the callbackQuery call after the user taps the “play solo” button. Coincidence?, Sherlock doesn’t think that. When answering the callbackQuery you can specify a custom game URL, so you can include the needed parameters in the URL as query parameters.

From the server perspective, we should receive a POST request to the Amazon API Gateway endpoint containing the needed parameters (the userId, both the chatId and the messageId or the inlineId only).

With this information all we need to do is call the setGameScore method on Telegram’s API setting the needed parameters and voilá. The score is shared in the user’s chat room and when the game is shared again in the same chat you can see a beautiful leaderboard instead of the game description.

Ok. Wait, what!? Let’s review how we managed Telegram’s game lifecycle:

  • First of all, a user requests a game through the “/play” command, pressing a button after a “/list” command is issued or through an inline query.
  • When we receive the request, we answer the request with the sendGame function of the API setting our own buttons.
  • When the user taps the “Play solo” button a callbackQuery is received, we must answer this query by sending the URL of our game. It is useful to also send the needed parameters to use the setScore endpoint.
  • When you score in the game a request is received in the server with the needed information to use the setScore function.

Checkout our published games here:

Jumping submarine

Angry piano

iBasket

Sumon

The End Of The Wrappers? I Don’t Think So!

It’s official: HTML5 is hot once again. For the past year, many of the wishes that all HTML5 developers have been waiting for have finally come true. All major browsing technologies support the main HTML5 features that make this technology a great option to develop beautiful desktop sites and compelling mobile apps. The latest addition to the list of iOS 8 with its official support for WebGL and improved webview called WKWebView with Nitro JIT acceleration, has been widely applauded by the community. And there are plenty of other reasons to be happy if you are an HTML5 developer, as the runtime environment that will run your app or game is a major issue that has been holding back the widespreading of the web as a major development platform (specially on mobile) for the last years.

There are many articles out there around performance benchmarks of the current browsers. Chromium based solutions for Android, Internet Explorer supporting the main HTML5 specifications (and auto updating itself quite regularly), plenty of great app development frameworks, … the list of good news is long. And here at Ludei, we are glad that, finally, all the pieces are starting to come together. But (there is always a but ;)), we have been reading much about a concept we do not agree with, and is the apocaliptic calling to “the end of the wrapping technologies” for mobile web applications. Ludei has been providing great tools and technology for HTML5 developers for the last couple of years.

Ludei’s developer community has grown strong to 50,000 developers and more than 4,500 apps published on mobile markets. We are going to continue to provide a great development experience and the best tools and runtimes as long as they continue to come out to the market. But there is a reality we still know about: building compelling mobile web apps is not simple. And we are not just talking about developing the app itself. Some frameworks are getting mature, some are starting to show their potential, but there is a detail worth mentioning: the mobile space is not the same as desktop web app development.

  1. First of all, mobile users are used to and feel comfortable with app stores, so they want apps. Building an app is not a major issue, but still, lots of web developers do not want to face all the hassle of installing native SDKs, compile applications and moreover, update multiple tools to be able to create their final mobile apps.
  2. But not only this, successful apps need access to native SDKs and mobile features that may vary from one platform to the other, or even from one store to the other. We are talking about in-app payments, ad networks, push notifications, social network SDK integrations, etc.
  3. Additionally (and sadly), there is still not one runtime environment solution that fits all and not plenty of good tools to test and debug apps on mobile. At Ludei, we have developed our own HTML5 runtime environments (Canvas+ and WebView+) and we also provide access to use the system web browsing technologies. This way, developers can choose what works best for them depending on their app. Even our canvas only technology, Canvas+, has plenty of advantages that some other technologies do not have for some type of apps (mainly games): low footprint, advanced memory management, extensions, accelerated physics, full control over the runtime (crucial for some customers), etc.

All these features are what wrapping technologies like Ludei’s CocoonJS or Apache Cordova provide: A productive way of testing, creating and monetizing HTML5 mobile apps. The bottom line is, that we are far from a mobile browser only app and game market. App stores on mobile will continue to exist, and actually, that’s the beauty of HTML5, your product can exist in both environments (as a browser based discoverable app and a mobile app store app). Mobile web app development is here to stay and grow and wrapping technologies are far from being at their end, moreover, in our opinion, they are at their infancy.

The future of the CocoonJS Cordova Command Line Interface (CLI)

A couple of months ago we published our CocoonJS Command Line Interface (CLI) that let’s you compile Cordova based projects, which benefit from the Webview+ runtime. Today we want to share with you an approximation of what’s coming to the CocoonJS CLI in the following months.

One of the main tasks we are currently developing is the integration of the command line with our cloud. This will allow you to download projects locally and upload them back to Ludei’s cloud compiler, so the compilations you make with the CLI use all the project data you already have stored in the cloud compiler (e.g., your Facebook tokens, MoPub ad units…).

Another exciting change coming to the command line is the possibility of using Crosswalk as an alternative runtime environment. Crosswalk will join the current Webview+ and Canvas+ as another execution environment for applications made with Cordova/CocoonJS. The main benefit of using Crosswalk is that it has Android binaries for x86, so Android devices running Android 4.x x86 enjoy all the features of a modern browser specifically suited for the underlying CPU.

We will also update the HelloWorldApp/DeviceReady demo that is created when you make a project using “$ CocoonJS create”, so that this new sample app will use different features of the Webview+/Crosswalk to demonstrate the potential of these runtimes.

But remember that you can already benefit from the following features with the current version of CocoonJS CLI.

Already available features of the CocoonJS Cordova CLI

  • The CocoonJS-CLI is agnostic to a specific cordova 3.x version.
  • The Webview+ provides a chromium-based environment for your HTML5 hybrid apps. It will deliver all the power of Chrome and the same look and feel across every Android device on the market. As we promised, Android fragmentation is over!
  • Remote debugging

At this point, these are the tasks that are already in development and you’ll be able to use in the following months.

Roadmap for the upcoming months

  1. Integration with the Ludei’s file system API. (which let’s the user upload it’s local project and compile it in the cloud). No more hassle of setting up and updating the Cordova environment locally.
  2. Different execution environments support (either Canvas+, WebView+, Crosswalk or whatever environment may come in the future) thanks to the compilation in the cloud.
  3. Cloud project management from the command line.
  4. Live reload. This is a great feature that will allow that by just saving a source code file on the server, let the CocoonJS client be aware of the change and update itself “automagically”,  saving tons of time during development.

It seems that the CocoonJS Cordova Command Line Interface will bring many brand new features to our platform, what do you think?

CocoonJS 2.0, now ready for HTML5 Apps! Introducing the Phonegap Killer

We have some really incredible news to share with you. Usually, we’d tell you about all the amazing updates that we’ve made to CocoonJS. But, this time it’s different. The new version of CocoonJS, 2.0, is live and it allows users to compile HTML5 apps! Starting today, current Phonegap users have a better and faster alternative! 

Screen Shot 2014-04-03 at 13.50.38

In order to use it, all you have to do is select the new CocoonJS version in your project when you are ready to compile it inside the DevPortal. Please note that this version is still in beta so we will allow you to still use the previous 1.4.7 version of CocoonJS. 

But, let’s explain a bit more about this new version. With CocoonJS 2.0 you can compile your project in the Canvas+ -our accelerated canvas, the best choice to accelerate your game-, or WebView+ -the Chromium-based WebView able to run DOM-based games and apps-. This is great because you can take advantage of each environment: Canvas+ to accelerate and WebView+ to dodge the fragmentation problems HTML5 app developers have when deploying to mobile using other technologies.

With this new step, it doesn’t matter what kind of HTML5 project you are working on: with Ludei’s CocoonJS you can deploy it cross-platform with no headaches because you don’t need to make code changes. Your app or game will work like a charm on all mobile devices and with the full native advantages. CocoonJS is moving the HTML5 development to the next level: finally, all HTML5 projects are first-class native citizens on mobile.

We’re super excited about this launch and happy to be able to offer our developers many other features:

– New launcher design
– Android remote debugging
– Bug fixes
– And much more… (take a look at the full change log on Help Center)

If you haven’t already, sign up for CocoonJS for FREE.

Bonus: We’ve also entirely transformed our website, so check it out here.

Ludei at Apps World North America 2014

Apps world was centered all around the popular world of mobile apps. It was quite a successful event as the plethora of developers, attendees and other exhibitors flocked to Ludei’s booth 18! People were quite impressed by our booth design, setup, and demos! Our booth even showcased what wonders our technology can do for developers on iOS, Android, Kindle, Ouya, and more! We don’t just say HTML5. FASTER. EVERYWHERE, we show it!   

Without doubt, it was a great opportunity for us, as we recently just announced our big news that CocoonJS will now be available for not only games, but also for apps!

Live Ludei’s presence at Apps World vicariously through these pictures! Enjoy!

Setting up our amazing booth!

Setting up our amazing booth!

Meeting with a potential client

Meeting with a potential client

Meeting with another attendee!

Meeting with another attendee!

Attendees flocking to view the spectacular demos

Attendees flocking to view the spectacular demos

The new and improved CocoonJS is coming for your HTML5 games and now also apps!

We have some much awaited news! As you know, CocoonJS wasan incredible cross platform for only games…up until now at least. The future is now and Ludei has been working hard to make CocoonJS an awesome platform for not only games, but for all kind of HTML5 apps. Exciting, isn’t it? Our entire team is thrilled about expanding our platform to support what everyone’s been waiting for: cross platform development for all kinds of HTML5 projects, even apps! We know you probably got that tingly, exciting feel just itching to use this new and improved CocoonJS for apps and games.

This is a big achievement for us and opens new doors to a whole amazing world of opportunities for you as a developer. You can now focus your development projects on all types of apps and work with Ludei and our cloud and tools for test and deployment, CocoonJS, to publish them across iOS, Android, and more! This web based development will work with native features and with absolutely no code changes. Code once. Publish everywhere. That’s our motto; it’s as simple as that.

You must be excited to know when you’ll be able to use CocoonJS to create your amazing apps. Hang tight and stay tuned- it’s coming soon ;). Before we make this available for everyone, we’re going to be opening up a private beta and we’ll send you more information by email. Interested in learning more? All you have to do is provide us with your email and if you qualify, you’ll get more info, tips, and tricks straight to your inbox.

CocoonJS is really the easiest way to have your web based app on mobile. You’ll save a ton of time…and..well, you know what they say..time = money! Don’t wait, start using CocoonJS for both games and apps!

Do you want more information? Sign up!