Skip to main content

Creating commands in a bot

Commands are the main way a user interacts with a bot. Each command represents a specific action that can be performed using the bot. For example, getting the current weather, translating text, or playing a game.

Step 1: Create your first command

Let's create a command HelloCommand that simply sends the user the message "Hello, world!".

import { Command, UserMessageContext } from "evogram";

@CommandHandler("hello")
class HelloCommand extends Command {
public async execute(message: UserMessageContext){
message.reply("Hello, world!");
}
}

Step 2: Handling command parameters

Often commands require additional parameters to perform a specific action. For example, the TranslateCommand command may need to specify the language to translate the text to. Let's modify our HelloCommand command so that it can accept parameters from the user's message.

import { Command, UserMessageContext } from "evogram";

@CommandHandler({
name: "hello",
args: {
method: "fulltext",
value: ["name"]
}
})
export class HelloCommand extends Command {
public async execute(message: UserMessageContext, data: ICommandExecuteData): Promise<void> {
message.reply(`Hello, ${data.args.name}!`);
}
}

In this example, we used the @CommandHandler decorator to define the command name and its parameters. We set the command name as "hello", and the parameters as the user's name (name) passed as text after the command. Then, we modified the execute method to use the data from the command received from the user. In this case, we used the data parameter to access the values of the command parameters. After that, we pass the user's name in the response message to the user using the message.reply method.

Step 3: Registering commands

Now that we have a command, we need to register it with the bot. To do this, simply import the class with our command.

// Import the main Evogram class
import { Evogram } from 'evogram';
// Import the command we just created
import "./commands/hello.ts"
// Authorize the bot using API token
const client = new Evogram("YOUR_TOKEN");
// Launch the bot using LongPoll
client.updates.polling.start();

Step 4: Calling a command

Now users can call our command by sending messages to the bot. Let's see how it works.

> /hello Jane
Bot: Hello, Jane!