-
Notifications
You must be signed in to change notification settings - Fork 18
4. Using the framework
Aditya Sharma edited this page May 7, 2024
·
4 revisions
Rename the wrangler_sample.toml to wrangler.toml before moving forward in the tutorial!
Create a file, index.js, at ./flaregram/src/ would be the main file for the bot and it contains all the code for the bot to run.
Write the following code inside index.js:
import { router } from './flaregram/utils/router';
import { bot } from './flaregram/bot';
// Adding Event Listener, to handle the incoming requests
addEventListener('fetch', (event) => {
event.respondWith(router.handle(event.request));
});
export async function startCommand(body) {
// Fetching user details with message body
const user_id = body.message.from.id
const firstname = body.message.chat.first_name;
const chatId = body.message.chat.id;
// Defining the message parameters, for the 'sendMessage' function
messageparams = {
chat_id: chatId, // Chat ID to send the message to
text: `Hello [${firstname}](tg://user?id=${user_id}),\nWelcome to Sample Bot!`, // Text to send
parse_mode: "markdown"
}
// Sending the message with the 'sendMessage' function
await bot.message.sendMessage(messageparams);
}
// Handling the updates by telegram
export async function updateHandler(obj) {
if (obj.message) {
// if incoming message is '/start' command
if (obj.message.text == '/start'){
// Call the startCommand function
await startCommand(obj);
};
};
};Here's a breakdown of the code:
-
Importing necessary modules:
-
routerfrom./flaregram/utils/router: This is a router module that handles incoming requests and directs them to the appropriate handler functions. -
botfrom./flaregram/bot: This is the main bot module that provides access to the Telegram Bot API.
-
-
Adding an event listener:
- The
addEventListenerfunction is used to listen for incoming requests. When a request is received, therouter.handlefunction is called to handle the request and respond accordingly.
- The
-
Defining the
startCommandfunction:- This function is responsible for processing the
'/start'command. It retrieves user details from the message body, constructs a message parameters object, and sends a welcome message using thesendMessagefunction from thebot.messagemodule.
- This function is responsible for processing the
-
Defining the
updateHandlerfunction:- This function is responsible for handling updates received from Telegram. It checks if the incoming message exists and if the message text is equal to
'/start'. If both conditions are met, thestartCommandfunction is called to execute the'/start'command.
- This function is responsible for handling updates received from Telegram. It checks if the incoming message exists and if the message text is equal to
And π Voila! We've created our first bot just like that! Super easy right?!
Now let's move to the testing and deployment part!!! π
Continue reading...
Also Check out: