Home > Raku > Despotting

Despotting

API::Discord is a bit spotty. Many classes that are typically represented as a Str don’t sport that method. In same cases bare deparsed JSON is returned. That led to a fair amount of clutter that followed a pattern. After making a remote call via the API, I mix in a role and query the API further, before passing a list on via a Supply. I do the same operation with different operants. That’s sounds like a candidate for a multi sub.

multi sub augment(Discord::Channel $s) {
    $s does role :: {
        method Str { ‚#‘ ~ self.name }
    }
}

multi sub augment(%author where { .<discriminator>:exists }, API::Discord:D $discord) {
    $discord.get-user(%author<id>) does role :: {
        method Str { self.username ~ '#' ~ self.discriminator }
    }
}

multi sub augment(API::Discord::User $user) {
    $user does role :: {
        method Str { self.username ~ '#' ~ self.discriminator }
    }
}

# [...]

    start react {
        whenever $discord.ready {
            note "Logged in as { $discord.user.username }.";
        }
        whenever $discord.messages -> $message {
            next unless $channels ~~ $message.channel.name;

            $result.emit: [ $message.channel.&augment, $message.author.&augment, $message.content ];
        }
        whenever $discord.events -> $event {
            if $event<t> eq 'MESSAGE_UPDATE' {
                my $m = $event<d>;
                my $channel = $discord.get-channel($m<channel_id>).&augment;
                my $author = $m<author>.&augment($discord);
                next unless $channels ~~ $channel;

                $result.emit: [ $channel, $author, $m<content>, :update ];
            }
        }
        CATCH { default { say .^name ␣ .Str } }
    }

Simply calling augment as a pseudo-method will fix the shortcomings. If the API is changes I only have to accommodate that change in a single place in my program. Raku makes it very convenient to deal with an inconvenience. One might think Raku is British. Time to make some tea.

Categories: Raku
  1. No comments yet.
  1. June 22, 2021 at 13:53

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: