Docs / AI / Laraflare Converse
Laraflare Converse
Introduction
Laraflare Converse gives you a unified API for building chat bots that communicate across Slack, Telegram, GitHub, and your own application's web pages. You write your bot once, and Converse handles each platform's webhooks, threads, and message formats.
For example, you might build a support bot that answers questions in your team's Slack channels, replies to new GitHub issues, and chats with customers on your application's help page. Converse also integrates with the Laraflare AI SDK, so an AI agent can answer your bot's messages while Converse manages conversation memory and typing indicators.
Note
Converse is still being ported. Its threads, cards, attachments, emoji and capabilities, the driver base class and the fake are here; defining bots and handlers, agent bots, the built-in Slack, Telegram, GitHub, web and terminal drivers, the web chat, its configuration file and its Artisan commands are not yet, so this page documents only the parts you can use today.
Installation
Install Converse in your application with npm:
npm install @laraflare/converse
Note
Converse has no
converse:installcommand yet, so nothing publishesconfig/converse.ts,routes/bot.tsor Converse's migrations. A connection is read fromconverse.connections.{name}in your application's configuration, as shown in custom drivers.
Threads
A Thread represents one conversation thread on a platform, such as a Slack thread or a GitHub issue. Create one from the connection name, a channel ID, and an optional thread ID. Without a thread ID, the thread targets the channel itself:
import { Thread } from '@laraflare/converse';
const channel = new Thread('slack', 'C0123456789');
const thread = new Thread('slack', 'C0123456789', '1712345678.000100');
To reply to a thread later, such as when a long-running job completes, store the thread's connection, channel().id(), and id values and pass them back to Thread:
await order.update({
chat_connection: thread.connection(),
chat_channel: thread.channel().id(),
chat_thread: thread.id(),
});
const stored = new Thread(order.chat_connection, order.chat_channel, order.chat_thread);
Sending Messages
Call sendEphemeral to send a message visible only to the user who triggered the event. On platforms without ephemeral messages, Converse sends the user a direct message instead, and inside a direct message it sends a regular reply. Outside a turn, pass the recipient as the second argument. It accepts a string, a Markdown instance, or a card, and returns a SentMessage instance:
import { Markdown } from '@laraflare/converse';
await message.thread().sendEphemeral('Only you can see this message.');
await thread.sendEphemeral(Markdown.make('**Only you** can see this message.'), userId);
Because GitHub supports neither ephemeral messages nor direct messages, sendEphemeral throws UnsupportedCapabilityException on GitHub.
Note
sendandmentionare not onThreadyet; they arrive with the rest of Converse's port.
Editing, Deleting, and Reacting
You can edit, delete, and react to a SentMessage. edit and delete return promises, because Converse records the change in your database:
import { Emoji } from '@laraflare/converse/Enums/Emoji';
const sent = await thread.sendEphemeral('Working on it...');
await sent.edit('All done!');
sent.addReaction(Emoji.ThumbsUp);
sent.removeReaction(Emoji.ThumbsUp);
await sent.delete();
You can also react directly to an incoming Message, such as to acknowledge that your bot received it:
message.addReaction(Emoji.Eyes);
When you only have a message's ID, call edit, delete, addReaction, or removeReaction on the thread:
await thread.edit(messageId, 'All done!');
thread.addReaction(messageId, Emoji.ThumbsUp);
Alongside Emoji enum cases, reaction methods accept an emoji character or shortcode such as '👀' or 'eyes'. Each platform limits which reactions bots can use. ThumbsUp, ThumbsDown, Heart, Party, and Eyes work across Slack, Telegram, and GitHub.
Note
Telegram allows one reaction per message from your bot, so adding a new reaction replaces the previous one.
Typing Indicators
Call updateStatus to show the platform's typing indicator and clearStatus to hide it. Slack also displays the status text you pass, defaulting to "is thinking..." when omitted. Slack shows status text only inside threads, Telegram ignores the text, and on platforms without typing indicators such as GitHub, both methods do nothing:
thread.updateStatus('Searching the docs...');
thread.clearStatus();
Channels and Direct Messages
To post in the parent channel instead of replying inside the thread, call forChannel, which returns a Thread targeting the channel itself. Because every GitHub comment lives on an issue or pull request, channel threads aren't available on GitHub:
const channel = thread.forChannel();
Call channel to get a Channel instance with id, name, memberCount, and isDirectMessage methods. Any field the platform doesn't supply is null.
To start a direct message with a user, call directMessage with the connection, the user, and the bot's name. It returns the Thread of the direct message:
import { Converse } from '@laraflare/converse/Facades/Converse';
const thread = Converse.directMessage('slack', userId, 'support');
On Telegram, your bot can send a direct message only to a user who has already started a chat with it.
Capabilities
Each platform supports a different set of features. Converse throws UnsupportedCapabilityException if you edit, delete, react, send an attachment, send an ephemeral message, or open a direct message on a platform that doesn't support it. Check support ahead of time with supports and the Capability enum:
import { Capability } from '@laraflare/converse/Enums/Capability';
if (thread.supports(Capability.EditMessage)) {
await sent.edit('Updated.');
}
Note
The built-in Slack, Telegram, and GitHub drivers are not ported yet, so which capabilities a connection has depends on its driver: each
Capabilitycase is supported by a driver that implements its contract, such asSupportsEditMessagesforCapability.EditMessage(see custom drivers).
Cards
Cards are structured messages that each driver renders natively. Slack receives Block Kit blocks, Telegram receives formatted text with an inline keyboard, and GitHub receives GitHub Flavored Markdown:
import { Actions } from '@laraflare/converse/Cards/Actions';
import { Button } from '@laraflare/converse/Cards/Button';
import { Card } from '@laraflare/converse/Cards/Card';
import { Field } from '@laraflare/converse/Cards/Field';
import { Fields } from '@laraflare/converse/Cards/Fields';
import { Text } from '@laraflare/converse/Cards/Text';
const card = Card.make('Refund request')
.withChildren(
Text.make('**Order #1042** on the _Pro_ plan'),
Fields.make(Field.make('Amount', '$49.00')),
Actions.make(
Button.make('approve-refund')
.withLabel('Approve')
.withValue('1042')
.primary(),
Button.make('deny-refund')
.withLabel('Deny')
.withValue('1042')
.danger(),
),
)
.withFallback('Refund request for order #1042');
await thread.sendEphemeral(card);
Slack shows the fallback text in notifications, while other platforms use it when a card has no visible content. If you omit fallback text, Converse falls back to the card's title. The @laraflare/converse/Cards modules provide these elements:
| Element | Description |
|---|---|
Text |
A block of Markdown text. |
Image |
An image with optional alt text. |
Fields and Field |
Pairs of labels and values. |
Table |
Headers, rows, and an optional caption. |
Section |
A group of elements. |
Divider |
A separator. |
Link |
A link. |
Actions |
A row of controls. |
Button |
A button that sends an action to your bot. |
LinkButton |
A button that opens a URL. |
Select and RadioSelect |
A menu of options. |
Cards and their elements are immutable. Methods such as withLabel and primary return a new instance, so chain them or assign the returned instance to a variable.
Converse throws InvalidCardException when a card exceeds platform limits, such as more than 25 controls in an Actions row or more than 100 options in a Select.
Note
Handling a button click needs a bot with a handler, which Converse's port doesn't have yet, so
Actionevents,HandlesActionsand callback URLs are not documented here.Button.withCallbackUrlandoncealready build the button.
Menus
Select and RadioSelect elements offer a menu of options. Each option has a label and the value your bot receives when a user chooses it:
import { Actions } from '@laraflare/converse/Cards/Actions';
import { Select } from '@laraflare/converse/Cards/Select';
Actions.make(
Select.make('priority')
.withPlaceholder('Choose a priority')
.option('High', 'high')
.option('Low', 'low'),
);
Slack renders Select as a dropdown menu and RadioSelect as radio buttons. Telegram renders each option as a button, and GitHub renders the options as text.
Link Buttons
Use LinkButton when a button should open a URL directly in the user's browser instead of sending an Action event to your bot:
import { LinkButton } from '@laraflare/converse/Cards/LinkButton';
LinkButton.make('View the order', 'https://example.com/orders/1042');
Raw Platform Payloads
When you need platform-specific formatting beyond what Card provides, pass the driver name and raw payload to withRaw. Other platforms still render the standard card:
import { Card } from '@laraflare/converse/Cards/Card';
import { Text } from '@laraflare/converse/Cards/Text';
Card.make('Release notes')
.withChildren(Text.make('Version 2.0 has shipped.'))
.withRaw('slack', {
blocks: [
{ type: 'section', text: { type: 'mrkdwn', text: '*Version 2.0* has shipped.' } },
],
});
For GitHub, put the comment's Markdown in the raw payload's body key:
.withRaw('github', { body: '> [!TIP]\n> **Version 2.0** has shipped.' });
Attachments
Before passing a message to your bot, Converse downloads and stores each attached file on your configured attachment disk (converse.attachments.disk, or your default filesystem disk). Read stored files with message.attachments(). Reading and storing a file return promises, because a disk is read and written asynchronously:
for (const attachment of message.attachments()) {
const name = attachment.name();
const mimeType = attachment.mimeType();
const contents = await attachment.contents();
await attachment.store('exports/' + name);
}
Files that fail Converse's checks aren't stored. Inspect skipped files with unavailableAttachments and read why each was rejected with unavailable:
for (const attachment of message.unavailableAttachments()) {
await message.thread().sendEphemeral(
`I skipped ${attachment.name()}: ${attachment.unavailable()}.`,
);
}
GitHub doesn't send attachments to bots, so attachments always returns an empty collection on GitHub.
Warning
Because users upload these files, Converse refuses to store them on a public disk. Store them in object storage, such as an R2 bucket, so every part of your application can reach them.
To send a file from your bot, make an Attachment instance from storage, a path, or its contents:
import { Attachment } from '@laraflare/converse';
const summary = await Attachment.fromStorage('reports/summary.pdf');
const orders = Attachment.fromPath(storage_path('app/exports/orders.csv'));
const exported = Attachment.fromContents(csv, 'export.csv', 'text/csv');
Note
sendAttachmentand the upload limits (the number, size, and MIME types of files Converse accepts) are not ported yet.
Custom Drivers
To integrate another chat platform, register a custom driver with Converse.extend in the boot method of AppServiceProvider:
import { Converse } from '@laraflare/converse/Facades/Converse';
import { DiscordDriver } from '../Bots/Drivers/DiscordDriver';
/**
* Bootstrap any application services.
*/
override boot(): void {
Converse.extend('discord', (app, config) => new DiscordDriver(config));
}
Then configure a connection using that driver in config/converse.ts:
import { env } from '@laraflare/framework';
export default function converse() {
return {
connections: {
discord: {
driver: 'discord',
bot_token: env('DISCORD_BOT_TOKEN'),
},
},
};
}
Extend Driver and implement events, which turns an incoming webhook payload into bot events, and sendMessage:
import type { Card } from '@laraflare/converse/Cards/Card';
import { Driver } from '@laraflare/converse/Drivers/Driver';
import type { Markdown, SentMessage, Thread } from '@laraflare/converse';
export class DiscordDriver extends Driver {
/**
* Convert the webhook payload into bot events.
*/
*events(payload: Record<string, unknown>): Iterable<unknown> {
// ...
}
/**
* Send a message to the given thread.
*/
sendMessage(thread: Thread, content: Card | Markdown | string): SentMessage {
// ...
}
}
The driver's connection configuration is available on this.config.
In events, yield one bot event per incoming message. Attach the platform's message ID with withId and event ID with withEventId so Converse can deduplicate repeated webhooks, and pass isSelf as true on User for messages sent by the bot itself so Converse ignores them:
import { CarbonImmutable } from '@laraflare/framework';
import { Message } from '@laraflare/converse/BotEvents/Message';
import { Thread, User } from '@laraflare/converse';
/**
* Convert the webhook payload into bot events.
*/
*events(payload: Record<string, any>): Iterable<unknown> {
const author = payload.author;
yield Message.make(
new Thread(this.connection(), payload.channel_id),
payload.content,
new User(author.id, author.username, null, false, author.id === this.config.bot_id),
CarbonImmutable.parse(payload.timestamp),
).withId(payload.id).withEventId(payload.event_id);
}
Implement the corresponding contracts in @laraflare/converse/Contracts/Drivers for every feature your platform supports. Each contract enables its matching capability, such as SupportsEditMessages enabling Capability.EditMessage.
Note
Converse doesn't receive webhooks yet, so the
ReceivesWebhooks,SupportsCreateInlineResponses,SuppliesAgentHistoryandProvidesSetupcontracts and theconverse:setupcommand are not ported.
Testing
In your test suite, you don't want bots hitting real Slack or Telegram APIs. Call Converse.fake() to replace every connection with a fake that records what your code does, and assert against the fake:
import { Emoji } from '@laraflare/converse/Enums/Emoji';
import { Converse } from '@laraflare/converse/Facades/Converse';
const fake = Converse.fake();
// Assert a reaction was removed...
fake.assertReactionRemoved(Emoji.Eyes);
// Assert a typing indicator status was shown...
fake.assertStatus('Searching the docs...');
removedReactions and statuses return what was recorded, for finer assertions.
When your code looks up users or channels, seed the fake with withUsers and withChannels:
import { Channel, User } from '@laraflare/converse';
import { Converse } from '@laraflare/converse/Facades/Converse';
const fake = Converse.fake()
.withUsers(new User('U0000001', 'Jane', 'jane'))
.withChannels(new Channel('C0123456789', '#support'));
Note
Converse.incomingand the fake's other assertions (assertSent,assertEdited,assertDeleted,assertReactionAdded,assertAttachmentSent,assertDirectMessageSentand the approval assertions) record what bots send, and arrive with the rest of Converse's port.