# Game Updates via Messenger


Game Updates via Messenger (formerly known as Game Bots) let you create

This is a powerful re-engagement channel because Messenger is where players already spend time communicating with friends. A well-crafted game message in a player's inbox can feel personal and relevant, driving them back into your game at the right moment.

This guide covers what game bots are, how to set one up, sending messages, message templates, personalization, App Review requirements, rate limiting, and best practices.

## What Are Game Bots?

A game bot is a Messenger bot that is linked to your Instant Game's Facebook Page. Once set up, the bot can:

- Send messages to players who have opted in to receive them
- Deliver rich content including images, buttons, and card carousels
- Respond to player messages (if you implement conversational logic)
- Send personalized re-engagement messages based on game state
- Provide a persistent Messenger presence for your game

From the player's perspective, your game appears as a conversation in their Messenger inbox. When they receive a game update, it appears as a message from your game's Page, just like a message from a friend.

## Setting Up a Messenger Bot

### Prerequisites

Before you can send game updates via Messenger, you need:

1. **A Facebook Page** for your game (see [Pages and Groups](https://developers.facebook.com/documentation/games/retain/pages-and-groups))
2. **An Instant Games app** configured in the [App Dashboard](https://developers.facebook.com/apps/)
3. **Messenger Platform** added to your app in the App Dashboard
4. **A server** to host your bot's webhook endpoint

### Step 1: Create a Facebook Page

If you do not already have a Facebook Page for your game, create one:

1. Go to [facebook.com/pages/create](https://www.facebook.com/pages/create).
2. Choose a Page category appropriate for games.
3. Name the Page after your game and add your game's branding.

### Step 2: Add Messenger Platform to Your App

1. Open the [App Dashboard](https://developers.facebook.com/apps/).
2. Select your app.
3. In the left sidebar, click **Add Product** and select **Messenger**.
4. Follow the setup wizard to connect your Facebook Page to the Messenger Platform.
5. Generate a **Page Access Token** -- you will need this to send messages via the API.

### Step 3: Set Up a Webhook

Your bot needs a webhook endpoint -- a URL on your server that Facebook calls when events occur (e.g., a player sends a message, opts in, or interacts with your bot).

1. In the App Dashboard, go to **Messenger** > **Settings**.
2. In the **Webhooks** section, click **Setup Webhooks**.
3. Enter your webhook URL (must be HTTPS) and a verify token of your choosing.
4. Subscribe to the relevant events:
   - `messages` -- Receives messages sent by players
   - `messaging_optins` -- Receives opt-in events when players subscribe
   - `messaging_game_plays` -- Receives events when players play your game

Your webhook must respond to the verification challenge:

```javascript
// Express.js example
app.get('/webhook', (req, res) => {
  const VERIFY_TOKEN = 'your_verify_token';

  const mode = req.query['hub.mode'];
  const token = req.query['hub.verify_token'];
  const challenge = req.query['hub.challenge'];

  if (mode === 'subscribe' && token === VERIFY_TOKEN) {
    console.log('Webhook verified');
    res.status(200).send(challenge);
  } else {
    res.sendStatus(403);
  }
});
```

And handle incoming events:

```javascript
app.post('/webhook', (req, res) => {
  const body = req.body;

  if (body.object === 'page') {
    body.entry.forEach(entry => {
      const event = entry.messaging[0];
      const senderId = event.sender.id;

      if (event.message) {
        handleIncomingMessage(senderId, event.message);
      } else if (event.optin) {
        handleOptIn(senderId, event.optin);
      } else if (event.game_play) {
        handleGamePlay(senderId, event.game_play);
      }
    });

    res.status(200).send('EVENT_RECEIVED');
  } else {
    res.sendStatus(404);
  }
});
```

### Step 4: Link Your Game to the Page

In the App Dashboard, ensure that your Instant Game is linked to the Facebook Page you created. This connection allows the Messenger bot to interact with players who play your game.

## Sending Messages

Once your bot is set up, you can send messages to players using the Messenger Platform Send API.

### Basic Text Message

```javascript
async function sendTextMessage(recipientId, text) {
  const response = await fetch(
    `https://graph.facebook.com/v18.0/me/messages?access_token=${PAGE_ACCESS_TOKEN}`,
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        recipient: { id: recipientId },
        message: { text: text },
      }),
    }
  );

  const data = await response.json();
  if (data.error) {
    console.error('Message send failed:', data.error);
  }
  return data;
}
```

### Message with Buttons

Buttons let the player take action directly from the message -- such as opening your game, viewing a leaderboard, or accepting a challenge.

```javascript
async function sendButtonMessage(recipientId, text, buttons) {
  await fetch(
    `https://graph.facebook.com/v18.0/me/messages?access_token=${PAGE_ACCESS_TOKEN}`,
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        recipient: { id: recipientId },
        message: {
          attachment: {
            type: 'template',
            payload: {
              template_type: 'button',
              text: text,
              buttons: buttons,
            },
          },
        },
      }),
    }
  );
}

// Example usage
sendButtonMessage(playerId, 'Your daily reward is ready!', [
  {
    type: 'web_url',
    url: 'https://fb.gg/play/your_game_id',
    title: 'Claim Reward',
  },
  {
    type: 'postback',
    title: 'Remind Me Later',
    payload: 'REMIND_LATER',
  },
]);
```

### Message with Image

```javascript
async function sendImageMessage(recipientId, imageUrl, text) {
  await fetch(
    `https://graph.facebook.com/v18.0/me/messages?access_token=${PAGE_ACCESS_TOKEN}`,
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        recipient: { id: recipientId },
        message: {
          attachment: {
            type: 'template',
            payload: {
              template_type: 'generic',
              elements: [
                {
                  title: 'New Tournament Available!',
                  subtitle: text,
                  image_url: imageUrl,
                  buttons: [
                    {
                      type: 'web_url',
                      url: 'https://fb.gg/play/your_game_id',
                      title: 'Join Now',
                    },
                  ],
                },
              ],
            },
          },
        },
      }),
    }
  );
}
```

## Message Templates

The Messenger Platform supports several message template types:

### Generic Template

A versatile template that supports an image, title, subtitle, and up to three buttons. Useful for game event announcements, challenge notifications, and re-engagement messages.

### Button Template

A text message with up to three buttons. Useful for simple calls to action where an image is not needed.

### Media Template

Supports sending images or videos as the primary content. Useful for sharing gameplay highlights or promotional content.

### Receipt Template

A structured template for displaying transaction-like information. Could be used for in-game purchase confirmations or reward summaries.

For full documentation on all template types, refer to the [Messenger Platform documentation](https://developers.facebook.com/documentation/business-messaging/messenger-platform/send-messages/templates).

## Personalization

The most effective game bot messages are personalized to the specific player. Use game-state data from your backend to customize messages:

```javascript
async function sendPersonalizedUpdate(player) {
  const { messengerId, name, lastScore, friendName, friendScore } = player;

  if (friendScore > lastScore) {
    // A friend has passed the player's score
    await sendButtonMessage(
      messengerId,
      `Hey ${name}! ${friendName} just scored ${friendScore.toLocaleString()} and passed your score of ${lastScore.toLocaleString()}. Are you going to let that stand?`,
      [
        {
          type: 'web_url',
          url: 'https://fb.gg/play/your_game_id',
          title: 'Take Back the Lead!',
        },
      ]
    );
  }
}
```

Personalization ideas:
- "Your friend [name] just beat your score"
- "You have not played in 3 days -- your daily streak is about to reset"
- "A new tournament starts in 1 hour"
- "Your energy is full -- time to play!"
- "Congratulations on reaching Level [X]! Here is a special reward."

## Handling the game_play Event

When a player finishes playing your game, Facebook sends a `game_play` webhook event to your bot. This is a powerful trigger for sending post-game messages.

```javascript
function handleGamePlay(senderId, gamePlayEvent) {
  const gameId = gamePlayEvent.game_id;
  const playerId = gamePlayEvent.player_id;
  const contextType = gamePlayEvent.context_type;
  const contextId = gamePlayEvent.context_id;
  const score = gamePlayEvent.score;
  const payload = gamePlayEvent.payload;

  console.log(`Player ${playerId} played game ${gameId}, scored ${score}`);

  // Send a follow-up message
  sendButtonMessage(
    senderId,
    `Great game! You scored ${score} points. Want to challenge a friend?`,
    [
      {
        type: 'web_url',
        url: 'https://fb.gg/play/your_game_id',
        title: 'Play Again',
      },
    ]
  );
}
```

## App Review Requirements

Before your bot can send messages to the general public, you must submit your app for App Review and request the necessary Messenger permissions.

### Required Permissions

- **pages_messaging:** Required to send messages to players through your Page.

### Important: Testing Limitations

**You must use real Facebook accounts for testing your Messenger bot.** Test accounts (created through the App Dashboard for testing purposes) cannot receive bot messages. This is a critical requirement to be aware of during development:

- Add real Facebook accounts as testers or administrators in your app's settings
- These accounts will be able to interact with your bot before it passes App Review
- Do not rely on test accounts for bot testing -- they will not receive messages
- During development, only accounts with a role in your app (Admin, Developer, Tester) can interact with the bot

### Submission Guidelines

When submitting for App Review:
1. Provide clear instructions for the reviewer explaining how your bot works
2. Include screenshots or a video of the bot in action
3. Explain what messages players will receive and when
4. Demonstrate that messages are relevant and not spammy
5. Ensure your bot complies with the [Messenger Platform Policy](https://developers.facebook.com/documentation/business-messaging/messenger-platform/policy)

## Rate Limiting

The Messenger Platform enforces rate limits to protect the user experience:

- **Standard messaging:** You can send messages to players within 24 hours of their last interaction with your bot (Standard Messaging window).
- **Message tags:** For messages outside the 24-hour window, you must use approved message tags. The `GAME_EVENT` tag is relevant for game-related notifications.
- **Frequency limits:** Do not send more than a few messages per day to any individual player. Even within the 24-hour window, excessive messaging will result in rate limiting or policy action.
- **Aggregate limits:** Your bot has overall sending limits based on its engagement rate. High-engagement bots get higher limits.

### Handling Rate Limits

```javascript
async function sendMessageWithRetry(recipientId, message, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    const response = await fetch(
      `https://graph.facebook.com/v18.0/me/messages?access_token=${PAGE_ACCESS_TOKEN}`,
      {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          recipient: { id: recipientId },
          message: message,
        }),
      }
    );

    const data = await response.json();

    if (!data.error) {
      return data;
    }

    if (data.error.code === 4) {
      // Rate limited -- wait and retry
      const waitTime = Math.pow(2, attempt) * 1000;
      console.warn(`Rate limited. Retrying in ${waitTime}ms...`);
      await new Promise(resolve => setTimeout(resolve, waitTime));
    } else {
      console.error('Message send failed:', data.error);
      return null;
    }
  }

  console.error('Max retries exceeded');
  return null;
}
```

## Next Steps

- **[Notification Best Practices](https://developers.facebook.com/documentation/games/retain/notifications/best-practices)** -- Consolidated best practices across all notification channels.
- **[Notification Guidelines](https://developers.facebook.com/documentation/games/retain/notifications/notification-guidelines)** -- Content formatting and quality criteria for notification messages.
- **[A2U API](https://developers.facebook.com/documentation/games/retain/notifications/a2u-api)** -- Server-driven notifications through Facebook's notification system.
- **[Notification Service](https://developers.facebook.com/documentation/games/retain/notifications/notification-service)** -- Scheduled notifications through Facebook's infrastructure.
- **[Notifications Overview](https://developers.facebook.com/documentation/games/retain/notifications/overview)** -- Compare all notification channels.
- **[Pages and Groups](https://developers.facebook.com/documentation/games/retain/pages-and-groups)** -- Set up the Facebook Page needed for your Messenger bot.