Links

HTTP Requests

HTTP requests are the next feature we will look at to expand your app functionality. If you want to connect your app to the outside world, the HTTP property enables users to invoke an external web service.
In this topic, we will create a slash command get for our Hello World app. This command executes a GET HTTP request based on the given URL. You can also use our Tester App or any app of your choice. Make sure that a Rocket.Chat server is ready to deploy the app.

Step 1: Register the slash command

The slash command must be registered in the app's main class, at the root of the project.
1
import { IAppAccessors, IConfigurationExtend, ILogger } from '@rocket.chat/apps-engine/definition/accessors';
2
import { App } from '@rocket.chat/apps-engine/definition/App';
3
import { IAppInfo } from '@rocket.chat/apps-engine/definition/metadata';
4
import { HTTPRequestCommand } from './commands/HTTPRequestCommand'; // [1]
5
6
export class HelloWorldApp extends App {
7
constructor(info: IAppInfo, logger: ILogger, accessors: IAppAccessors) {
8
super(info, logger, accessors);
9
}
10
11
public async extendConfiguration(configuration: IConfigurationExtend) {
12
configuration.slashCommands.provideSlashCommand(new HTTPRequestCommand()); // [2]
13
}
14
}
Here, we import our new slash command class and then register it in the app's configuration.

Step 2: Create the slash command

  1. 1.
    If you haven't created a separate directory for slash commands, it is recommended to create a commands directory at the root of the project.
  2. 2.
    Create the HTTPRequestCommand.ts file in this directory.
  3. 3.
    Then enter the code shown below:
1
import {
2
IHttp,
3
IModify,
4
IRead,
5
} from '@rocket.chat/apps-engine/definition/accessors';
6
import {
7
ISlashCommand,
8
SlashCommandContext,
9
} from '@rocket.chat/apps-engine/definition/slashcommands';
10
11
export class HTTPRequestCommand implements ISlashCommand {
12
public command = 'get'; // [1]
13
public i18nParamsExample = '';
14
public i18nDescription = '';
15
public providesPreview = false;
16
17
public async executor(context: SlashCommandContext, read: IRead, modify: IModify, http: IHttp): Promise<void> {
18
const [url] = context.getArguments(); // [2]
19
20
if (!url) { // [3]
21
throw new Error('Error!');
22
}
23
24
await http.get(url); // [4]
25
}
26
}
This code implements the following:
  1. 1.
    The slash command is called get.
  2. 2.
    When executed, it uses the argument that the user passed after the command as the URL.
  3. 3.
    The argument is mandatory. If no argument is provided, an error is thrown.
  4. 4.
    Perform the GET request using the provided argument.
Optionally, you can store the GET request in a console constant. When the command is executed, it is logged.
1
const response = await http.get(url);
2
console.log("result: " + response.data);

Step 3: Print the request to a conversation

Now, instead of logging console output to the instance's log, let's output it to the conversation.
Add the following private method to HTTPRequestCommand.ts.
1
private async sendMessage(context: SlashCommandContext, modify: IModify, message: string): Promise<void> {
2
const messageStructure = modify.getCreator().startMessage();
3
const sender = context.getSender(); // [1]
4
const room = context.getRoom(); // [2]
5
6
messageStructure
7
.setSender(sender)
8
.setRoom(room)
9
.setText(message); // [3]
10
11
await modify.getCreator().finish(messageStructure); // [4]
12
}
This function implements the following:
  1. 1.
    Gets the user who invoked the command (in this case, you).
  2. 2.
    Selects the room where the command was executed.
  3. 3.
    Sets the received string as the message.
  4. 4.
    Sends the message to the room.
Then, append the following code to the end of the executor method:
1
const response = await http.get(url);
2
const message = JSON.stringify(response.data, null, 2);
3
await this.sendMessage(context, modify, message);
Instead of simply sending the request and not capturing the response, we store the response in a constant, format its content as a string, and transmit it using our new sendMessage method.
Note: To learn more about messaging, see the IMessageBuilder documentation.

Step 4: Deploy the app

To deploy the app, run:
rc-apps deploy --url <server_url> -u <user> -p <pwd>
  • The <server_url> parameter is the URL of your Rocket.Chat server.
  • Replace the placeholders with the URL, username, and password for your server, respectively.
After executing this command, your application will be deployed to the server.
Packaging your app
Alternatively, you can execute the rc-apps package command. This gives you a compressed zip file of your app that you can upload as a private app to your Rocket.Chat server.

Step 5: Test the app

After deploying the application, enter /get <some_url> in any channel and the app will send a GET request to the specified URL. In this example, we will use JSONPlaceholder to obtain dummy data to test our app:
  • Enter /get https://jsonplaceholder.typicode.com/todos/1 in a chat.
  • You receive the following response in the chat:
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
Similarly, you can apply this feature to connect with any domain of your choice.
Next, let's gain an understanding of events and the Apps-Engine-supported features to handle Rocket.Chat events.
Last modified 3mo ago
Rocket.Chat versions receive support for six months after release.