# Push Notification Configuration for Programmable Chat

Programmable Chat integrates APN (iOS) and GCM/FCM (Android and browsers) Push Notifications for certain events. Not all implementations need every possible event to trigger push notifications. Additionally, the content and payload of your push notifications will differ based on requirements and use cases.

Chat Service instances provide some configuration options which allow push configuration on a per Service instance basis. These options allow for:

* Selecting which of the eligible Chat events should trigger push notifications
* Specifying the payload template for each message type (overriding the default template)

> \[!WARNING]
>
> It is not possible to selectively register for various push
> notification message types on the client SDKs (iOS and Android).

**Table of Contents**

* [Push Notification Types](#push-types)
* [Push Notification Templates](#push-templates)
* [Configuring Push Notifications](#push-configuring)

## Push Notification Types \[#push-types]

The following Push Notifications can be configured for a Chat Service instance:

| Push Notification Type | Description                                                                              |
| :--------------------- | :--------------------------------------------------------------------------------------- |
| New Message            | This is sent to all members within a Channel when a new Message is posted to the Channel |
| Added to Channel       | This is sent to Users that have been added to a Channel                                  |
| Invited to Channel     | This is sent to Users that have been invited to join a Channel                           |
| Removed from Channel   | This is sent to Users that have been removed from a Channel they were a Member of        |

**Note:** The default `enabled` flag for new Service instances for all Push Notifications is `false`. This means that Push will be disabled until you explicitly enable it.

**Note:** You may configure a `sound` parameter value for each of the Push Notification types (detailed below).

## Push Notification Templates \[#push-templates]

Each of the Push Notification types has a default template for the payload (or notification body). Each of these templates can be overridden per Service instance via the Push Notification configuration. The templating employs markup for a limited set of variables:

### Template Variables

| Template Variable          | Description                                                                                                                                                                                   |
| :------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `${USER}`                  | Will be replaced with the `FriendlyName` of the User who triggered the Push Notification (if any). The User's `Identity` will be used if no `FriendlyName` has been set.                      |
| `${USER_FRIENDLY_NAME}`    | Will be replaced with the `FriendlyName` of the User who triggered the Push Notification (if any). The User's `Identity` will be used if no `FriendlyName` has been set.                      |
| `${USER_IDENTITY}`         | Will be replaced with the `Identity` of the User who triggered the Push Notification.                                                                                                         |
| `${USER_SID}`              | Will be replaced with the `Sid` of the User who triggered the Push Notification (if any). The User's `Identity` will be used if no `Sid` is available.                                        |
| `${CHANNEL}`               | Will be replaced with the `UniqueName`, `FriendlyName` or `ChannelSid` (if they exist, in that order of priority). These properties are tied to the Channel related to the Push Notification. |
| `${CHANNEL_FRIENDLY_NAME}` | Will be replaced with the `FriendlyName`, `UniqueName` or `ChannelSid` (if they exist, in that order of priority). These properties are tied to the Channel related to the Push Notification. |
| `${CHANNEL_SID}`           | Will be replaced with the `ChannelSid`. This property is tied to the Channel related to the Push Notification.                                                                                |
| `${CHANNEL_UNIQUE_NAME}`   | Will be replaced with the `UniqueName` or `ChannelSid` (if they exist, in that order of priority). These properties are tied to the Channel related to the Push Notification.                 |
| `${MESSAGE}`               | Will be replaced with the body of the actual Message. Only used for notifications of type: **New Message**                                                                                    |

**Note:** *The maximum length of the entire notification payload is **110 characters**.* This substring is applied after the notification payload is constructed and the variables data applied. Thus, freeform text and the variable data are compiled into a string and the first **110 characters** are then used as the notification payload.

**Note:** Variables can be used multiple times within a template, but each variable will contribute to the maximum number of available characters.

### Default Templates

| Push Notification Type | Default Template                                           |
| :--------------------- | :--------------------------------------------------------- |
| New Message            | `${CHANNEL};${USER}: ${MESSAGE}`                           |
| Added to Channel       | You have been added to channel `${CHANNEL}` by `${USER}`   |
| Invited to Channel     | `${USER}` has invited you to join the channel `${CHANNEL}` |
| Removed from Channel   | `${USER}` has removed you from the channel `${CHANNEL}`    |

## Configure Push Notifications \[#push-configuring]

Each Push Notification type can be configured for a Service instance. The configuration allows each notification type to be `enabled` or `disabled.` This also handles custom template configuration as per the templating mechanism described above.

The following are the eligible notification `type` names:

* `NewMessage`
* `AddedToChannel`
* `InvitedToChannel`
* `RemovedFromChannel`

The following are the configuration parameters used:

| parameter name                             | description                                                                                                                                                                                                                                   |
| :----------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Notifications.\[type].Enabled              | `true` if this type of push notification should be sent, `false` if not. Default: `false`                                                                                                                                                     |
| Notifications.\[type].Template             | The customer template string for the notification type.                                                                                                                                                                                       |
| Notifications.\[type].Sound                | The "sound" push payload parameter that will be set for this notification type.                                                                                                                                                               |
| Notifications.NewMessage.BadgeCountEnabled | `true` if the `NewMessage` notification type should send a badge count value in the push payload. *This parameter is only applicable to the `NewMessage` type.* Note that this is currently only used by the iOS APNS push notification type. |

### Badge Count

This setting is only for the `NewMessage` notification type. Currently, only APNS push notifications for iOS will use this and include the `badge` property in the payload. If enabled, the value of this property will represent the count of 1:1 Channels the User is a Member of which have any *unread* Messages for the User.

If `Notifications.NewMessage.BadgeCountEnabled` is set to `true`, decrements to the count of 1:1 Channels with unread messages will be sent to all registered iOS endpoints for that User.

Configure NewMessage Push Notifications

```js
// Download the helper library from https://www.twilio.com/docs/node/install
const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = twilio(accountSid, authToken);

async function updateService() {
  const service = await client.chat.v2
    .services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
    .update({
      "notifications.addedToChannel.enabled": true,
      "notifications.addedToChannel.sound": "default",
      "notifications.addedToChannel.template":
        "A New message in ${CHANNEL} from ${USER}: ${MESSAGE}",
    });

  console.log(service.sid);
}

updateService();
```

```python
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = os.environ["TWILIO_ACCOUNT_SID"]
auth_token = os.environ["TWILIO_AUTH_TOKEN"]
client = Client(account_sid, auth_token)

service = client.chat.v2.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").update(
    notifications_added_to_channel_enabled=True,
    notifications_added_to_channel_sound="default",
    notifications_added_to_channel_template="A New message in ${CHANNEL} from ${USER}: ${MESSAGE}",
)

print(service.sid)
```

```csharp
// Install the C# / .NET helper library from twilio.com/docs/csharp/install

using System;
using Twilio;
using Twilio.Rest.Chat.V2;
using System.Threading.Tasks;

class Program {
    public static async Task Main(string[] args) {
        // Find your Account SID and Auth Token at twilio.com/console
        // and set the environment variables. See http://twil.io/secure
        string accountSid = Environment.GetEnvironmentVariable("TWILIO_ACCOUNT_SID");
        string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN");

        TwilioClient.Init(accountSid, authToken);

        var service = await ServiceResource.UpdateAsync(
            notificationsAddedToChannelEnabled: true,
            notificationsAddedToChannelSound: "default",
            notificationsAddedToChannelTemplate: "A New message in ${CHANNEL} from ${USER}: ${MESSAGE}",
            pathSid: "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");

        Console.WriteLine(service.Sid);
    }
}
```

```java
// Install the Java helper library from twilio.com/docs/java/install

import com.twilio.Twilio;
import com.twilio.rest.chat.v2.Service;

public class Example {
    // Find your Account SID and Auth Token at twilio.com/console
    // and set the environment variables. See http://twil.io/secure
    public static final String ACCOUNT_SID = System.getenv("TWILIO_ACCOUNT_SID");
    public static final String AUTH_TOKEN = System.getenv("TWILIO_AUTH_TOKEN");

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
        Service service =
            Service.updater("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
                .setNotificationsAddedToChannelEnabled(true)
                .setNotificationsAddedToChannelSound("default")
                .setNotificationsAddedToChannelTemplate("A New message in ${CHANNEL} from ${USER}: ${MESSAGE}")
                .update();

        System.out.println(service.getSid());
    }
}
```

```go
// Download the helper library from https://www.twilio.com/docs/go/install
package main

import (
	"fmt"
	"github.com/twilio/twilio-go"
	chat "github.com/twilio/twilio-go/rest/chat/v2"
	"os"
)

func main() {
	// Find your Account SID and Auth Token at twilio.com/console
	// and set the environment variables. See http://twil.io/secure
	// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment
	client := twilio.NewRestClient()

	params := &chat.UpdateServiceParams{}
	params.SetNotificationsAddedToChannelEnabled(true)
	params.SetNotificationsAddedToChannelSound("default")
	params.SetNotificationsAddedToChannelTemplate("A New message in ${CHANNEL} from ${USER}: ${MESSAGE}")

	resp, err := client.ChatV2.UpdateService("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
		params)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	} else {
		if resp.Sid != nil {
			fmt.Println(*resp.Sid)
		} else {
			fmt.Println(resp.Sid)
		}
	}
}
```

```php
<?php

// Update the path below to your autoload.php,
// see https://getcomposer.org/doc/01-basic-usage.md
require_once "/path/to/vendor/autoload.php";

use Twilio\Rest\Client;

// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
$sid = getenv("TWILIO_ACCOUNT_SID");
$token = getenv("TWILIO_AUTH_TOKEN");
$twilio = new Client($sid, $token);

$service = $twilio->chat->v2
    ->services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
    ->update([
        "notificationsAddedToChannelEnabled" => true,
        "notificationsAddedToChannelSound" => "default",
        "notificationsAddedToChannelTemplate" => "A New message in ${CHANNEL} from ${USER}: ${MESSAGE}",
    ]);

print $service->sid;
```

```ruby
# Download the helper library from https://www.twilio.com/docs/ruby/install
require 'twilio-ruby'

# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ENV['TWILIO_ACCOUNT_SID']
auth_token = ENV['TWILIO_AUTH_TOKEN']
@client = Twilio::REST::Client.new(account_sid, auth_token)

service = @client
          .chat
          .v2
          .services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
          .update(
            notifications_added_to_channel_enabled: true,
            notifications_added_to_channel_sound: 'default',
            notifications_added_to_channel_template: 'A New message in ${CHANNEL} from ${USER}: ${MESSAGE}'
          )

puts service.sid
```

```bash
# Install the twilio-cli from https://twil.io/cli

twilio api:chat:v2:services:update \
   --sid ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \
   --notifications.added-to-channel.enabled \
   --notifications.added-to-channel.sound default \
   --notifications.added-to-channel.template "A New message in ${CHANNEL} from ${USER}: ${MESSAGE}"
```

```bash
curl -X POST "https://chat.twilio.com/v2/Services/ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \
--data-urlencode "Notifications.AddedToChannel.Enabled=true" \
--data-urlencode "Notifications.AddedToChannel.Sound=default" \
--data-urlencode "Notifications.AddedToChannel.Template=A New message in ${CHANNEL} from ${USER}: ${MESSAGE}" \
-u $TWILIO_ACCOUNT_SID:$TWILIO_AUTH_TOKEN
```

```json
{
  "account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "consumption_report_interval": 100,
  "date_created": "2015-07-30T20:00:00Z",
  "date_updated": "2015-07-30T20:00:00Z",
  "default_channel_creator_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "default_channel_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "default_service_role_sid": "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "friendly_name": "friendly_name",
  "limits": {
    "channel_members": 500,
    "user_channels": 600
  },
  "links": {
    "channels": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Channels",
    "users": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users",
    "roles": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles",
    "bindings": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings"
  },
  "notifications": {
    "log_enabled": true,
    "added_to_channel": {
      "enabled": false,
      "template": "notifications.added_to_channel.template"
    },
    "invited_to_channel": {
      "enabled": false,
      "template": "notifications.invited_to_channel.template"
    },
    "new_message": {
      "enabled": false,
      "template": "notifications.new_message.template",
      "badge_count_enabled": true
    },
    "removed_from_channel": {
      "enabled": false,
      "template": "notifications.removed_from_channel.template"
    }
  },
  "post_webhook_url": "post_webhook_url",
  "pre_webhook_url": "pre_webhook_url",
  "pre_webhook_retry_count": 2,
  "post_webhook_retry_count": 3,
  "reachability_enabled": false,
  "read_status_enabled": false,
  "sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "typing_indicator_timeout": 100,
  "url": "https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
  "webhook_filters": [
    "webhook_filters"
  ],
  "webhook_method": "webhook_method",
  "media": {
    "size_limit_mb": 150,
    "compatibility_message": "new media compatibility message"
  }
}
```

Setting additional notification types requires including them in your configuration request. For instance, to include the AddedToChannel Push Notification type, you can add

```bash
'Notifications.AddedToChannel.Enabled=true'
'Notifications.AddedToChannel.Template=You are now a Member of ${CHANNEL}!  Added by ${USER}'
'Notifications.AddedToChannel.Sound=default'
```

to your `curl` request.

Next: [Notifications on iOS](/docs/chat/ios/push-notifications-ios)
