Build Quiz Bot Using Action Buttons
In this guide we will learn how we can build a Quiz Bot with DeadSimpleChat Bots.
In the DeadSimpleChat bot message we can also add "Action Buttons", as shown in the image below.
The Action Buttons can be simple buttons, button with images and also button with icons.
The above image shows button with images. When the button is pressed, a Webhook is triggered with event "actionButtonPressed".
Introduction
In this guide we will build a Quiz App, when the user first joins the Chat Room, the bot will send the quiz automatically to the user.
The Bot Message will be private, and will only be visible to the user for which the message is triggered.
- We will use DeadSimpleChat webhooks to listen for when a user joins the chatroom.
- We will handle the webhook in CloudFlare worker, and inside the Worker we will call the Bot API to send the message into the chatroom with Actions Button.
- When the action button is pressed, we will handle the webhook on the Cloudflare worker and send the reply as bot message if the answer is right or wrong.
Initial Setup in DeadSimpleChat
Go to DeadSimpleChat Dashboard, If you don't already have an account then signup for a free account.
a. Listen to User Joined Webhook
We will first setup the User Joined Webhook, to listen when the user joins the chat room. We will receive the Webhook
on webhooks.site
which would allow us to easily inspect the data recieved in the Webhook.
We will then later replace the webhooks.site
URL with the URL of our Cloudflare Worker.
- Go to
webhooks.site
and obtain the Webhook URL - The go to Dead Simple Chat Dashboard -> Settings -> Webhooks and TURN ON Webhook
- Under "Webhook URL" field paste the URL obtained from
webhooks.site
. (We will later replace it with the Cloudflare worker URL) - Turn on "User Joined Chat Room" webhook option
b. Create a Bot
Next we will create the Bot, we will name the bot quizbot
, under Webhook URL we will use the same webhook.site
URL
or you can open webhooks.site
in a different browser or in incognito mode and obtain a new URL to enter here.
We will set the "Bot Trigger" to mention and we will set the "Bot Message Visibility" to private
because we will be
sending the quiz question to every user who joins the chat room, and we want the quiz message to private.
After creating the bot note down the Bot ID
as we will need it in the next step. Also note down the "Secret Key" from
Dashboard -> Developer page.
c. Inspecting the User Joined Webhook
Now let's inspect the "User Joined Webhook", open any chat room and then visit the webhooks.site
page, there you will
a new webhook received.
In the Webhook there is info and userId of the user, we will use this info to send message visible to this user containing the quiz question.
Setting up Cloudflare Workers
Now let's build our backend using Cloudflare workers, if you don't already have an account then signup for a free Cloudflare account.
a. Creating a New Function
After signup go to Workers & Pages -> Create Application -> Create Worker -> Deploy
b. Implementing the Function Logic
In our Cloudflare worker we will handling two Webhooks, one Webhook is for when the user joins the chat room and the second webhook is for when the action button is pressed.
We will will create two paths /user-joined-webhook
and /bot-action-webhook
, from the User Joined Webhook we will
extract the userId
and roomId
to send the message to the user in that Chat Room.
When sending the message, we will send our quiz question along with action buttons, when the action button is pressed
we get the following Webhook, actionButtonPressed
containing the info of the Action Button that is pressed.
You can read more about Send Bot Message API.
{
"user": {
"_id": "648e211a81cea20bd8b1581d",
"username": "admin"
},
"chatRoom": {
"_id": "653f9e50ed0f012c972936fa",
"roomId": "apQRt7tRn",
"name": "Testing Room"
},
"messageHistory": [],
"bot": {
"_id": "6540f869ed0f012c9729384b",
"name": "quizbot",
"metadata": "",
"description": "quiz bot sends quiz"
},
"message": {
"_id": "6540f961ed0f012c972938a1",
"message": "Which animal is known for its ability to climb trees with agility?"
},
"triggeredBy": "actionButtonPressed",
"actionButtonPressed": {
"_id": "6540f961ed0f012c972938a2",
"type": "action",
"id": "1",
"displayText": "Elephant",
"imageURL": "https://upload.wikimedia.org/wikipedia/commons/6/63/African_elephant_warning_raised_trunk.jpg",
"messageId": "6540f961ed0f012c972938a1"
}
}
When the action button is pressed, we will compare the button pressed with correct answer, if answer is correct then we will send the message "Your answer is correct!!" and if it wrong we will send the message "Your answer is incorrect".
You can paste the following code in your Cloudflare worker.
export default {
async fetch(request, env, ctx) {
// REPLACE WITH YOUR BOT_ID
const BOT_ID = ""
// REPLACE WITH YOUR SECRET_KEY
const SECRET_KEY = ""
if (request.method === "POST") {
var pathComponent = request.url.split("/")[3];
// /user-joined-webhook
if (pathComponent === "user-joined-webhook") {
// Handle User Joined
const data = await request.json();
// extracting userId
const userId = data.data.user._id;
// extracting roomId
const roomId = data.data.user.lastChatRoomId;
// Sending BOT MESSAGE
await fetch(`https://api.deadsimplechat.com/consumer/api/v2/bot/${BOT_ID}/chatroom/${roomId}/message?auth=${SECRET_KEY}`, {
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
userId: userId,
message: "Which animal is known for its ability to climb trees with agility?",
"actionButtons": [
{
"type": "action",
"id": "1",
"displayText": "Elephant",
"imageURL": "https://upload.wikimedia.org/wikipedia/commons/6/63/African_elephant_warning_raised_trunk.jpg"
},
{
"type": "action",
"id": "2",
"displayText": "Cat",
"imageURL": "https://upload.wikimedia.org/wikipedia/commons/3/39/Feral_cat_1.JPG"
}, {
"type": "action",
"id": "3",
"displayText": "Dog",
"imageURL": "https://upload.wikimedia.org/wikipedia/commons/4/47/American_Eskimo_Dog.jpg"
}
]
}),
method: "POST"
});
}
// /bot-action-webhook
else if (pathComponent === "bot-action-webhook") {
const data = await request.json();
if (data.triggeredBy == "actionButtonPressed") {
const userId = data.user._id;
const roomId = data.chatRoom.roomId;
const buttonPressedText = data.actionButtonPressed.displayText;
if (buttonPressedText.toLowerCase() === "cat") {
// Send Success Message
await fetch(`https://api.deadsimplechat.com/consumer/api/v2/bot/${BOT_ID}/chatroom/${roomId}/message?auth=${SECRET_KEY}`, {
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
userId: userId,
message: "Your answer is correct!!"
}),
method: "POST"
});
} else {
// Send Error Message
await fetch(`https://api.deadsimplechat.com/consumer/api/v2/bot/${BOT_ID}/chatroom/${roomId}/message?auth=${SECRET_KEY}`, {
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
userId: userId,
message: "Your answer is incorrect"
}),
method: "POST"
});
}
}
} else {
return new Response(JSON.stringify({
success: false,
message: "invalid path"
}), {
status: 404
});
}
return new Response(JSON.stringify({
success: true,
message: ""
}), {
status: 200
});
} else {
return new Response(JSON.stringify({
success: false,
message: "please send HTTP POST Request"
}), {
status: 400
})
}
},
};
Revisiting DeadSimpleChat to Complete Bot Configuration
Now Lets update Webhook URLs in DeadSimpleChat.
a. Updating Join Room Webhook URL
Go to Dashboard -> Settings -> Webhook and there Under Webhook URL add your <CLOUDFLARE_WORKER_URL>/user-joined-webhook
.
For e.g if your Cloudflare worker URL is https://hello-world-blue-sun-0936.perceptronpioneer.workers.dev/
then enter
https://hello-world-blue-sun-0936.perceptronpioneer.workers.dev/user-joined-webhook
.
b. Adding the Webhook URL to the Bot
Go to Dashboard -> Settings -> Edit Bot and under "Webhook URL" enter <CLOUDFLARE_WORKER_URL>/bot-action-webhook
.
For e.g if your Cloudflare worker URL is https://hello-world-blue-sun-0936.perceptronpioneer.workers.dev/
then enter
https://hello-world-blue-sun-0936.perceptronpioneer.workers.dev/bot-action-webhook
.
Testing the Bot
Now join any chat room, as we have set our bot to work on all chatrooms (We can configure it to work on only selected chat rooms as well).
The Bot will send the Quiz, and when you click on any option you will get the reply from the bot, wether is answer is right or wrong.
Conclusion
In this tutorial, we have learned how to use action buttons in a bot. We have seen how to handle two different webhooks, one for when a user joins a chat room and another for when an action button is pressed. We have also learned how to send a message to a user in a specific chat room and how to handle the response when an action button is pressed.
For more information on sending bot messages, please refer to the Send Bot Message API.