Communicating with your server

Although the Instant Games SDK provides Player-specific data storage and Leaderboard storage, you may wish to store some information on your own web server — especially if building a game bot.

In this section, you will learn how to use the Instant Games SDK and the Messenger Bot platform for Instant Games to build and communicate with your backend infrastructure.

Download Sample Code

We have a sample app where you can try the code below. It allows you to save data to a backend service, as well as send payloads to and from the game bot.

Download Communication Demo (.zip)

The sample code contains two folders: client/ and server/. The server folder contains a sample Node.js application that you can either test in a local server or deploy to a cloud-based hosting solution. The client folder contains your Instant Game sample code with additional tooling to test and deploy it. Make sure to read the README.md files of both projects for detailed instructions on how to test and deploy.

Communicating with your Game Bot

When an Instant Game session ends and the user is opted into your Instant Game bot a messaging_game_plays webhook event is sent. Instant Game bots can also use the game_play button to allow direct access to the Instant Game bot. Follow our Instant Game bot tutorial for more information on creating a game bot.

From your game client, you can send data to your Game Bot by using the FBInstant.setSessionData method:

FBInstant.setSessionData({
  scoutSent:true, 
  scoutDurationInHours:24
});

The object passed as a parameter to setSessionData will be available in the payload property of the game_play webhook. Here's how to retrieve the data in your Messenger Bot (Node.js code example provided):

//
// Process game_play webhook
//
function receivedGameplay(event) {
  // Messenger platform Page-Scope ID
  var senderId = event.sender.id; 

  // FBInstant player id
  var playerId = event.game_play.player_id; 

  // FBInstant context id
  var contextId = event.game_play.context_id;

  if (event.game_play.payload) {
    // Get data from payload
    var payload = JSON.parse(event.game_play.payload);
    var scoutSent = payload['scoutSent'];
    var scoutDurationInHours = payload['scoutDurationInHours']; 

    // Schedule sending message to player when scout returns.
    if (scoutSent) {
      Scheduler.after(scoutDurationInHours).hours().then(function(){
        sendMessage(
          senderId, 
          contextId,
          'Your scout has come back with more intel. Want to find out more?', 
          'Get scout report!'
          {deeplinkTo:'scout_screen'}
        );
      }
    }
  }
}

You can also check our sample code for a full working example. Note that the sample uses the Generic Template for sending a message to the player. You can check out the Messenger Platform docs for many other template examples that are also compatible with the Instant Games game_play button.

Note in the example above, that the bot's game_play button sent more information that should be checked next time the game client gets opened. To check from our game if the session is being started from this bot message, and access its payload, we need to use FBInstant.getEntryPointData. The example below shows how to perform this check upon game initialization.

FBInstant.initializeAsync().then(function(){
  const entryPointData = FBInstant.getEntryPointData();
  if (entryPointData) {
    switch(entryPointData.deepLinkTo) {
      case 'scout_screen':
        game.loadAssetsFor(SCOUT_SCENE);
      case 'daily_chest_dialog':
        game.loadAssetsFor(DAILY_CHEST_SCENE);
      // case...
      default:
        game.loadAssetsFor(START_MENU);
    }
  }  
  FBInstant.startGameAsync().then(function(){
    game.start();
  })
});

Communicating with your custom backend

Although webhooks provide one way to send data to your game, they will not be sent for users who have opted out of your game bot. You can also use XMLHttpRequest or the fetch API to communicate with your game's server. In order to secure these communications, we provide the getSignedPlayerInfoAsync function, which allows you to verify that data sent to your server actually originates from the Instant Game.

In your Instant Game:

FBInstant.player.getSignedPlayerInfoAsync('custom_payload_supplied_with_request')
  .then(function (result) {
    // The verification of the ID and signature should happen on server side.
    SendToMyServer(
      result.getPlayerID(), // same value as FBInstant.player.getID()
      result.getSignature(),
      ... //any additional parameters required for your server call
    );
   });

On your server (Node.js code example provided):

const CryptoJS = require('crypto-js');
var firstpart = signedRequest.split('.')[0];
firstpart = firstpart.replace(/-/g, '+').replace(/_/g, '/');
const signature = CryptoJS.enc.Base64.parse(firstpart).toString();
const dataHash = CryptoJS.HmacSHA256(signedRequest.split('.')[1], '<APP_SECRET>').toString();
var isValid = signature === dataHash;
const json = CryptoJS.enc.Base64.parse(request.split('.')[1]).toString(CryptoJS.enc.Utf8);
const data = JSON.parse(json);

console.log(validated); // this will be true if the request is verified as coming from the game
console.log(data); // a JSON object as follows:

/*
{
  algorithm: 'HMAC-SHA256',
  issued_at: 1517294566,
  player_id: '1114685845316172',
  request_payload: 'custom_payload_supplied_with_request'
}
*/

Best Practices for Game Bots

Game Bots can be a powerful retention mechanic when used effectively, but used poorly they can provide an annoying player experience and drive users away from your game. We provide the following guidelines to help you optimize your game bot experience.

Do:

Provide relevant, timely and valuable updates to the players. For more information, visit our Best Practices section.

Give the user control (for example, by confirming they would like to be notified, and with what frequency).

Use entry point data on play buttons to load the game in contextually relevant ways.

Name the bot the same as the game.

Make use of social updates like turn reminders, tournaments results, timed rewards and challenges.

Make sure your players have the right incentives open the game via a bot message by using the message payload to reward them in-game with something valuable. A bot message is usually not valuable if it opens your game to the start screen.

Use a persistent menu to provide common actions, such as launching the game.

Set default action to use game_play on custom updates, so that the entire image takes you into the game.

Use bots to announce new features or content.

Optimize time of day for message sends per user, being sensitive to timezones.

Do not:

Send a message immediately after the player closes the game.

Send messages to re-engage the player with no context (e.g.: "Come back to the game now!"). Instead prefer re-engagement messages with rich context (e.g.: "Your scout has come back with more info")

Adopt the voice of other Facebook users or mislead players to believe their friends are communicating with them.

Continue to send a user bot messages when they repeatedly do not engage. Policy limits will apply and block your message from being sent. Current limits are 5 messages over 10 days of last game play session. When testing your bot, make sure to play your game at least once every 5 messages.

Set messaging_type to any other value than RESPONSE or UPDATE

Use the Messenger Platform's Broadcast API as it is currently not yet available for game bots. Please reach out to your partner manager if you are interested in using it.

Link to any app store.

Next steps: