For advanced use cases, you might want to use the ASK Frontend API.
The ASK Frontend API is the underlying package that powers the ASK Frontend UI components <ask-chat>
and <ask-button>
.
It holds the logic for communicating with the ASK backend and provides a way to interact with the bot programmatically.
There are two ways on using the ASK Frontend API:
This is the correct way if you want to use the ASK Frontend UI components.
The setup function window.createAskBot()
takes the same options as window.askSetup()
, which you can find at the ASK Frontend documentation.
The process is straightforward and similar to the basic setup. It involves the following steps:
<script src="https://dist.aboutsomethink.org/ask-frontend.iife.js"></script>
<script>
// window.createAskBot() is provided b the ASK Frontend UI. It returns an ASK Frontend API instance and
// two render functions: renderChat() and renderButton()
const { askBotService, renderChat } = window.createAskBot({
botID: 1,
token: 'yourtoken',
})
// After initialized, send a message to the bot
askBotService.subscribeTo('initialized', () => {
askBotService.postChatMessage({ message: 'Hello Bot' });
})
// Attach standalone chat to a DOM node
renderChat("container");
</script>
<div id="container"></div>
This is the correct way if you want to implement your own UI.
In this case, you have full control over the bot, but you need to implement the UI yourself. To react to bot events, you can subscribe to the bot's events.
To setup:
Note: Unless when using the ASK Frontend UI where it's not necessary to call the init() function, you need to call the init()
function to initialize the bot in this case.
<script src="https://dist.aboutsomethink.org/ask-frontend-bot-service.umd.cjs"></script>
<script>
const bot = new AskBotService({ botID: 3, token: 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef' });
bot.subscribeTo('botMessage', (message) => {
console.log('Bot says:', message.payload.text);
})
bot.init().then(() => {
bot.postChatMessage({ message: 'Hello' });
});
</script>
It's also possible to subscribe to the streamed message chunks:
<script src="https://dist.aboutsomethink.org/ask-frontend-bot-service.umd.cjs"></script>
<script>
const bot = new AskBotService({
botID: 3,
token: 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef',
});
bot.subscribeTo('streamingReadyState', ({ payload }) => {
console.log(`Connection status changed: ${payload}`);
})
bot.subscribeTo('streamingMessage', ({ chunk, buffer }) => {
console.log(`Received chunk: ${chunk}. Current buffer: ${buffer}`);
})
bot.subscribeTo('streamingError', ({ payload }) => {
console.log(`Streaming error: ${JSON.stringify(payload)}`);
})
bot.init().then(() => {
bot.postChatMessage({ message: 'Hello' });
});
</script>