Skip to main content

Method execute

The execute method is mandatory to implement in any class that inherits the abstract Command class. This method takes two arguments: message and data, which are objects. The message object contains data related to the user's message, such as text, sender ID, and so on. The data object is an optional parameter and is used to pass additional data to the command.

The execute method should contain the logic for processing user command input and creating a response. It is called when the command has been identified and is ready to be executed. In general, the execute method is the key method in handling user commands and generating corresponding responses.

note

If an error occurs during command execution, you can use the onError method to handle it.

Parameters

  • message - The UserMessageContext object containing information about the incoming user message, such as message text, chat ID, etc.
  • data - The ICommandExecuteData object containing additional data required to execute the command.

Example Usage

The final code for the execute method depends on the specific project requirements and applied architecture, but as an example, consider processing a simple "greeting" command.

import { Command, UserMessageContext, CommandHandler } from "evogram";

@CommandHandler("start")
class GreetingCommand extends Command {
public execute(message: UserMessageContext) {
const greetingText = `Hello, ${message.user.fullname}! Nice to meet you.`;
return message.reply(greetingText);
}
}

We import classes Command, UserMessageContext, and decorator CommandHandler from the evogram module, which indicates that this class is a command handler.

Then we create the GreetingCommand class, which is inherited from the Command class. The execute method takes the UserMessageContext object, which contains information about the user's message. When this command is called, a greeting message will be sent to the user containing their name.

The CommandHandler decorator indicates that this class is the handler for the "start" command. Thus, when a user receives the "/start" command, the execute method of this class will be automatically called.

danger

In this example, we do not handle possible errors, which can lead to application crashes in case of their occurrence. In a real project, appropriate error handling must be provided.