How to build a Mattermost Chatbot in Perl

This article was originally posted on Wednesday, January 9, 2019 at 17:53:11.

Introduction

WebService::Mattermost is an alternative Mattermost chatbot library written in Perl. It provides two interfaces to the Mattermost API and WebSocket gateway: from a script, and as a base for Moo and Moose classes. In this article, I will cover how to use it in a basic script, and demonstrate with a bot which greets users.

Requirements

Installable from CPAN:

Final code

For anyone who doesn’t want to read, here is the final product. You will need to change the authentication values in the constructor for WebService::Mattermost::V4::Client to your own Mattermost server and bot user.

#!/usr/bin/env perl

use strict;
use warnings;

use WebService::Mattermost::V4::Client;

my $bot = WebService::Mattermost::V4::Client->new({
    username => 'MATTERMOST USERNAME HERE',
    password => 'MATTERMOST PASSWORD HERE',
    base_url => 'https://my.mattermost-server.com/api/v4/',

    debug => 1, # Show extra connection information
});

# Triggered on every message received by the gateway
$bot->on(gw_message => sub {
    my ($bot, $args) = @_;

    # Only post-like messages contain post_data
    my $message = $args->{post_data}->{message};

    if ($message && lc $message eq 'hello') {
        # Respond with a friendly greeting
        $bot->api->posts->create({
            message    => 'Hi, @'.$args->{message}->{data}->{sender_name},
            channel_id => $args->{post_data}->{channel_id},
        });
    }
});

# Start the bot
$bot->start();

Breakdown

#!/usr/bin/env perl

use strict;
use warnings;

use WebService::Mattermost::V4::Client;

my $bot = WebService::Mattermost::V4::Client->new({
    username => 'MATTERMOST USERNAME HERE',
    password => 'MATTERMOST PASSWORD HERE',
    base_url => 'https://my.mattermost-server.com/api/v4/',

    debug => 1, # Show extra connection information
});
# Triggered on every message received by the gateway
$bot->on(gw_message => sub {
    my ($bot, $args) = @_;

    # Only post-like messages contain post_data
    my $message = $args->{post_data}->{message};

    if ($message && lc $message eq 'hello') {
        # Respond with a friendly greeting
        $bot->api->posts->create({
            message    => 'Hi, @'.$args->{message}->{data}->{sender_name},
            channel_id => $args->{post_data}->{channel_id},
        });
    }
});
$bot->start();

Extending

In the bot’s event loops, there are some additional utilites, accessible through the bot argument: