const message = {
text: "/ticket suspicious transaction with id 1234",
};
const response = await channel.sendMessage(message);
Custom Commands Webhook
Stream supports several slash commands out of the box:
- /giphy query
- /ban @userid reason
- /unban @userid
- /mute @userid
- /unmute @userid
Additionally, it’s possible to add your own commands.
By using Custom Commands, you can receive all messages sent using a specific slash command, eg. /ticket
, in your application. When configured, every slash command message happening in a Stream Chat application will propagate to an endpoint via an HTTP POST request.
$response = $channel->sendEvent(["text" => "/ticket suspicious transaction with id 1234"], $user["id"]);
channel.send_event({"text": "/ticket suspicious transaction with id 1234"}, user["id"])
channel.send_event({text: '/ticket suspicious transaction with id 1234'}, user['id'])
channel.SendEvent(ctx, &Event{
Type: "typing.start",
ExtraData: map[string]interface{}{"text", "/ticket suspicious transaction with id 1234"},
}, u.ID)
Event.send("channel-type", "channel-id")
.event(
EventRequestObject.builder()
.type("typing.start")
.user(userRequestObject)
.additionalField("text", "/ticket suspicious transaction with id 1234")
.build())
.request();
var msg = new Event { Type = "typing.start", UserId = user.Id };
msg.SetData("text", "/ticket suspicious transaction with id 1234");
await eventClient.SendEventAsync(channel.Type, channel.Id, msg);
Setting up your Custom Command consists of the following steps:
Registering your Custom Command
Configure a Channel Type
Configuring a Custom Action Handler URL
Implement a handler for your Custom Command
Registering Custom Commands
The API provides methods to create, list, get, update, and delete Custom Command definitions. These determine which commands are allowed to be used and how they’re presented to the user by providing a description of the command.
Command Fields
name | type | description | default | optional |
---|---|---|---|---|
name | string | name of the command | - | ✓ |
description | string | description, shown in commands auto-completion | - | ✓ |
args | string | arguments help text, shown in commands auto-completion | - | ✓ |
set | string | set name used for grouping commands | - | ✓ |
Creating a Command
await client.createCommand({
name: "ticket",
description: "Create a support ticket",
args: "[description]",
set: "support_commands_set",
});
$client->createCommand([
"name" => "ticket",
"description" => "Create a support ticket",
"args" => "[description]",
"set" => "support_commands_set"
]);
client.create_command(dict(
name="ticket",
description="Create a support ticket",
args="[description]",
set="support_commands_set",
))
client.create_command({
name: 'ticket',
description: 'Create a support ticket',
args: '[description]',
set: 'support_commands_set'
})
newCommand := &Command{
Name: "ticket",
Description: "Create a support ticket",
Args: "[description]",
Set: "support_commands_set",
}
client.CreateCommand(ctx, newCommand)
Command.create()
.name("Create a support ticket")
.description("ticket")
.args("[description]")
.setValue("support_commands_set")
.request();
await commandClient.CreateAsync(new CommandCreateRequest
{
Name = "Create a support ticket",
Description = "ticket",
Args = "[description]",
Set = "support_commands_set",
});
List Commands
You can retrieve the list of all commands defined for your application.
await client.listCommands();
$client->listCommands();
client.list_commands()
client.list_commands()
client.ListCommands(ctx)
Command.list().request();
await commandClient.ListAsync();
Get a Command
You can retrieve a custom command definition.
await client.getCommand("ticket");
$client->getCommand("ticket");
client.get_command("ticket")
client.get_command("ticket")
client.GetCommand(ctx, "ticket")
Command.get("ticket").request();
await commandClient.GetAsync("ticket");
Edit a Command
Custom command description, args & set can be changed. Only the fields that must change need to be provided, fields that are not provided to this API will remain unchanged.
await client.updateCommand("ticket", {
description: "Create customer support tickets",
});
$client->updateCommand("ticket", ["description" => "Create customer support tickets"]);
client.update_command("ticket", description="Create customer support tickets")
client.update_command("ticket", { description: 'Create customer support tickets' }
update := Command{Description: "Create customer support tickets"}
client.UpdateCommand(ctx, "ticket", &update)
Command.update("ticket").description("Create customer support tickets").request();
await commandClient.UpdateAsync("ticket", new CommandUpdateRequest
{
Description = "Create customer support tickets",
});
Remove a Command
You can remove a custom command definition.
await client.deleteCommand("ticket");
$client->deleteCommand("ticket");
client.delete_command("ticket")
client.delete_command("ticket")
client.DeleteCommand(ctx, "ticket")
Command.delete("ticket").request();
await commandClient.DeleteAsync("ticket");
You cannot delete a custom command if there are any active channel configurations referencing it explicitly.
Configure a Channel Type
In order to be able to use this command in a channel, we’ll need to create, or update an existing, channel type to include the ticket
command.
await client.createChannelType({
name: "support-channel-type",
commands: ["ticket"],
});
client.createChannelType([
"name" => "support-channel-type",
"commands" => ["ticket"]
]);
client.create_channel_type({
"name": "support-channel-type",
"commands": ["ticket"]
})
client.create_channel_type({
name: 'support-channel-type',
commands: ['ticket']
})
ct := NewChannelType("support-channel-type")
ct.Commands = []*Command{{Description: "ticket"}}
client.CreateChannelType(ctx, ct)
ChannelType
.create()
.withDefaultConfig()
.name("support-channel-type")
.commands(List.of("ticket"))
.request();
await channelTypeClient.CreateChannelTypeAsync(new ChannelTypeWithStringCommandsRequest
{
Name = "support-channel-type"",
Commands = new List<string> { "ticket" },
});
Configure a Custom Action URL
In order to use the defined custom commands, you will first have to set an endpoint URL in the App Settings.
await client.updateAppSettings({
custom_action_handler_url:
"https://example.com/webhooks/stream/custom-commands?type={type}",
});
$client->updateAppSettings(["custom_action_handler_url" => "https://example.com/webhooks/stream/custom-commands?type={type}"]);
client.update_app_settings(custom_action_handler_url="https://example.com/webhooks/stream/custom-commands?type={type}")
client.update_app_settings(custom_action_handler_url: "https://example.com/webhooks/stream/custom-commands?type={type}")
App
.update()
.customActionHandlerUrl("https://example.com/webhooks/stream/custom-commands?type={type}")
.request();
await appClient.UpdateAppSettingsAsync(new AppSettingsRequest
{
CustomActionHandlerUrl = "https://example.com/webhooks/stream/custom-commands?type={type}",
});
settings := &AppSettings{CustomActionHandlerURL: "https://example.com/webhooks/stream/custom-commands?type={type}"}
client.UpdateAppSettings(ctx, settings)
You can use a {type}
variable substitution in the URL to pass on the name of the command that was triggered. See Webhooks Overview for more information on URL configuration
Request format
Your endpoint will receive a POST request with a JSON encoded body containing: message, user and form_data objects. The form_data object will contain values of the interactions initiated by either Attachment or MML actions.
{
"message": {
"id": "xyz",
"text": "/ticket suspicious transaction with id 1234",
"command": "ticket",
"args": "suspicious transaction with id 1234",
"html": "",
"type": "regular",
"cid": "messaging:xyz",
"created_at": "2021-11-16T12:56:59.854Z",
"updated_at": "2021-11-16T12:56:59.854Z",
"attachments": [],
"latest_reactions": [],
"own_reactions": [],
"reaction_counts": null,
"reaction_scores": null,
"reply_count": 0,
"mentioned_users": [],
"silent": false
},
"user": {
"id": "17f8ab2c-c7e7-4564-922b-e5450dbe4fe7",
"Custom": {
"name": "jdoe"
},
"role": "user",
"banned": false,
"online": false
},
"form_data": {
"action": "submit",
"name": "John Doe",
"email": "john@doe.com"
}
}
Response format
If you intend to make any change to the message, you should return a JSON encoded response with the same message structure. Please note that not all message fields can be changed, the full list of fields that can be modified is available in the rewriting messages section.
Discarding messages
Your endpoint can decide to reject the command and return a user message. To do that the endpoint must return a regular message with type set to error.
{
"message": {
"type": "error",
"text": "invalid arguments for command /ticket"
}
}
Rewriting messages
You can also decide to modify the message, in that case you return the updated version of the message and it will overwrite the user input.
{
"message": {
"text": "Ticket #85736 has been created"
}
}
Interactions can be initiated either using Attachment actions:
{
"message": {
"text": "Ticket #85736 has been created",
"attachments": [
{
"type": "text",
"actions": [
{
"name": "action",
"text": "Send",
"style": "primary",
"type": "button",
"value": "submit"
},
{
"name": "action",
"text": "Cancel",
"style": "default",
"type": "button",
"value": "cancel"
}
}
]
}
}
Or by using MML formatted messages:
{
"message": {
"text": "this message contains a MML message."
"mml": "<mml><text>Ticket #85736 has been created</text><button name=\"action\" value=\"submit\">Send</button></mml>",
}
You can find more information on message rewrite in Before Message Send Webhook page
Performance considerations
Your webhook endpoint will be part of the send message transaction, so you should avoid performing any remote calls or potentially slow operations while processing the request. Stream Chat will give your endpoint 1 second of time to reply. If your endpoint is not available (ie. returns a response with status codes 4xx or 5xx) or takes too long, Stream Chat will continue with the execution and save the message as usual.
To make sure that an outage on the hook does not impact your application, Stream will pause your webhook once it is considered unreachable and it will automatically resume once the webhook is found to be healthy again.
Example code
An example of how to handle incoming Custom Command requests can be found in this repo.