Discord-Client

 view release on metacpan or  search on metacpan

lib/Discord/Client/Gateway.pm  view on Meta::CPAN


    # Reuse an outstanding startup wait; a reconnect needs a fresh ready notification.
    return $self->_failed( 'Gateway is closed', 'shutdown' ) if $self->{closed};
    return $self->{loop}->new_future->done($self) if $self->{state} eq 'ready';
    return $self->{ready_future} if $self->{ready_future} && !$self->{ready_future}->is_ready;
    my $ready = $self->{loop}->new_future;
    $self->{ready_future} = $ready;
    $ready->on_cancel( sub { $self->close } );
    return $ready if $self->{running};

    # Discover the endpoint once before opening the first connection.
    $self->{running} = 1;
    $self->{state} = 'discovering';
    my $info = $self->{identify_limiter}->info;
    $self->{discovery} = $info;

    # Discovery completion may arrive after the caller has closed the Gateway.
    $info->on_ready(
        sub {
            delete $self->{discovery};
            return if $self->{closed};

lib/Discord/Client/HTTPInteractions.pm  view on Meta::CPAN

handler may have performed side effects. This is process-local.
Use shared deduplication across workers if your side effects require it.

=head1 SERVE THE EXAMPLE

Set C<DISCORD_PUBLIC_KEY> to the application's 64-character hexadecimal public
key from the Developer Portal. Install Plack and a PSGI server, then run:

    PERL5LIB=lib plackup examples/http-interactions.psgi

Expose the service over public HTTPS and set its L<Interactions Endpoint URL|https://docs.discord.com/developers/interactions/overview#configuring-an-interactions-endpoint-url> in
the Developer Portal. C<plackup> alone serves local HTTP. The SDK verifies
signatures and answers signed PING requests. HTTP and Gateway are alternative
interaction delivery methods for the application.

=head1 LICENSE

Apache License 2.0.

=cut

lib/Discord/Client/Interaction.pm  view on Meta::CPAN

    my $future = $self->_observe($source);
    $self->{initial_operation} = $future;
    $self->{initial_source} = $source if blessed($source) && $source->isa('Future');
    $future->on_ready( sub { $self->_complete_initial_response( $future, $next_state ) } );
    return $future;
}

sub _send_initial_response {
    my ( $self, $payload ) = @_;

    # HTTP delivery can answer inline; Gateway delivery uses the unauthenticated callback endpoint.
    return $self->{initial_sender}->($payload) if $self->{initial_sender};
    my $path = '/interactions/' . $self->{id} . '/' . uri_escape_utf8( $self->{token} ) . '/callback';
    return $self->_rest->request( 'POST', $path, auth => 0, json => $payload );
}

sub _complete_initial_response {
    my ( $self, $future, $next_state ) = @_;
    return if $self->{state} eq 'expired' || $self->{closed};

    # Release delivery state and deadline before notifying acknowledgement observers.

lib/Discord/Client/REST.pm  view on Meta::CPAN

            || ref( $limits{$key} )
            || $limits{$key} !~ /\A\d+\z/
            || ( $limits{$key} == 0 && $key ne 'max_retries' );
    }
    return %limits;
}

sub loop { $_[0]->{loop} }
sub stats { $_[0]->{limiter}->stats }

sub _endpoint {
    my ( $self, $method, $pattern, $ids, %args ) = @_;

    # Validate each resource segment before inserting it into a fixed endpoint.
    for my $id (@$ids) {
        return $self->_fail( $self->{loop}->new_future, 'Invalid resource ID', 'request' )
            unless defined($id) && !ref($id) && $id =~ /\A\d{1,20}\z/;
        $pattern =~ s/\{id\}/$id/;
    }
    return $self->request( $method, $pattern, %args );
}
sub get_current_user { $_[0]->request( 'GET', '/users/@me' ) }

sub get_user {
    my ( $self, $user_id ) = @_;
    return $self->_endpoint( 'GET', '/users/{id}', [$user_id] );
}

sub get_channel {
    my ( $self, $channel_id ) = @_;
    return $self->_endpoint( 'GET', '/channels/{id}', [$channel_id] );
}

sub get_guild {
    my ( $self, $guild_id, %query ) = @_;
    return $self->_endpoint( 'GET', '/guilds/{id}', [$guild_id], query => \%query );
}

sub get_guild_channels {
    my ( $self, $guild_id ) = @_;
    return $self->_endpoint( 'GET', '/guilds/{id}/channels', [$guild_id] );
}

sub get_guild_member {
    my ( $self, $guild_id, $user_id ) = @_;
    return $self->_endpoint( 'GET', '/guilds/{id}/members/{id}', [ $guild_id, $user_id ] );
}

sub get_message {
    my ( $self, $channel_id, $message_id ) = @_;
    return $self->_endpoint( 'GET', '/channels/{id}/messages/{id}', [ $channel_id, $message_id ] );
}

sub get_messages {
    my ( $self, $channel_id, %query ) = @_;
    return $self->_fail( $self->{loop}->new_future, 'Invalid message pagination', 'request' )
        unless _valid_message_query( \%query );
    return $self->_endpoint( 'GET', '/channels/{id}/messages', [$channel_id], query => \%query );
}

sub _valid_message_query {
    my ($query) = @_;

    # Pagination selects at most one position and a bounded page size.
    return 0 if grep { $_ !~ /\A(?:before|after|around|limit)\z/ } keys %$query;
    return 0 if ( grep { exists $query->{$_} } qw(before after around) ) > 1;
    for my $key (qw(before after around)) {
        next unless exists $query->{$key};

lib/Discord/Client/REST.pm  view on Meta::CPAN

    return 1;
}

sub _message_body {
    my ( $self, $method, $path, $ids, $body ) = @_;

    # Accept text as a convenience while preserving native Discord message fields.
    $body = { content => "$body" } if defined($body) && !ref($body);
    return $self->_fail( $self->{loop}->new_future, 'Message body must be text or a hash reference', 'request' )
        unless ref($body) eq 'HASH';
    return $self->_endpoint( $method, $path, $ids, json => $body );
}

sub create_message {
    my ( $self, $channel_id, $body ) = @_;
    return $self->_message_body( 'POST', '/channels/{id}/messages', [$channel_id], $body );
}

sub edit_message {
    my ( $self, $channel_id, $message_id, $body ) = @_;
    return $self->_message_body( 'PATCH', '/channels/{id}/messages/{id}', [ $channel_id, $message_id ], $body );
}

sub delete_message {
    my ( $self, $channel_id, $message_id ) = @_;
    return $self->_endpoint( 'DELETE', '/channels/{id}/messages/{id}', [ $channel_id, $message_id ] );
}

sub create_dm {
    my ( $self, $id ) = @_;
    return $self->_fail( $self->{loop}->new_future, 'Invalid resource ID', 'request' )
        unless defined($id) && !ref($id) && $id =~ /\A\d{1,20}\z/;
    return $self->request( 'POST', '/users/@me/channels', json => { recipient_id => "$id" } );
}

sub trigger_typing {
    my ( $self, $channel_id ) = @_;
    return $self->_endpoint( 'POST', '/channels/{id}/typing', [$channel_id] );
}

sub request {
    my ( $self, $method, $path, %args ) = @_;

    # Reject invalid arguments before admitting the request to the scheduler.
    my $future = $self->{loop}->new_future;
    my $auth = exists( $args{auth} ) ? $args{auth} : $self->{auth};
    return $self->_fail( $future, 'auth must be zero or one', 'request' )
        unless defined($auth) && !ref($auth) && $auth =~ /\A[01]\z/;

lib/Discord/Client/REST.pm  view on Meta::CPAN


=head2 create_dm

C<create_dm(user_id)> returns a Future containing the DM channel hashref.

=head2 trigger_typing

C<trigger_typing(channel_id)> returns a Future resolving to undef.

Helper IDs are decimal strings. Invalid IDs, pagination or body shapes fail
before I/O. Discord validates endpoint permissions and payload semantics.

=head2 close

Returns a Future after failing outstanding work with C<shutdown>, cancelling
I/O and timers, and removing the owned HTTP notifier. Repeated calls succeed.
An injected HTTP transport remains caller-owned.

=head2 loop

Returns the configured IO::Async::Loop.

t/13-gateway-websocket.t  view on Meta::CPAN

    $server->listen(
        addr => { family => 'inet', socktype => 'stream', ip => '127.0.0.1', port => 0 },
        extensions => ['SSL'],
        SSL_cert_file => "$dir/cert.pem",
        SSL_key_file => "$dir/key.pem"
    ),
    'WSS listener setup'
)->get;
$gateway_url = 'wss://127.0.0.1:' . $server->read_handle->sockport;

# Serve Gateway discovery locally and advertise the ephemeral WSS endpoint.
my $listener = IO::Async::Listener->new(
    on_stream => sub {
        my ( undef, $stream ) = @_;
        push @http_streams, $stream;
        $stream->configure(
            on_read => sub {
                my ( $stream, $buffer ) = @_;
                return 0 unless $$buffer =~ /\r\n\r\n/;
                T2->like( $$buffer, qr{^GET /api/v10/gateway/bot HTTP/1\.1}, 'actual REST Gateway discovery' );
                $$buffer = '';

t/19-http-interactions.t  view on Meta::CPAN

    );
    return { service => $service, clock => $clock, signer => $signer, errors => \@errors };
}

sub signed {
    my ( $fixture, $payload, $timestamp ) = @_;
    my $clock = $fixture->{clock};
    my $signer = $fixture->{signer};
    $timestamp //= 1700000000 + int( $clock->{now} );

    # Sign the exact UTF-8 bytes that the endpoint receives, including the timestamp prefix.
    my $body = ref($payload) ? JSON::PP->new->utf8->encode($payload) : $payload;
    return (
        {
            'X-Signature-Ed25519' => unpack( 'H*', $signer->sign_message( $timestamp . $body ) ),
            'X-Signature-Timestamp' => "$timestamp"
        },
        $body
    );
}

t/19-http-interactions.t  view on Meta::CPAN

        $clock->advance(3);
        T2->is( $response_future->get->[0], 504, 'unanswered interaction has bounded deadline' );
        T2->unlike( join( ' ', @$errors ), qr/FAKE_HTTP_TOKEN/, 'handler/deadline diagnostics sanitized' );

        # Shutdown also settles pending responses and releases their deadline timers.
        ( $headers, $body ) = signed( $fixture, payload( 104, 'unanswered' ) );
        my $pending = $http->handle( $headers, $body );
        $http->close->get;
        T2->is( $pending->get->[0], 503, 'shutdown finishes pending HTTP responses' );
        T2->is( $clock->timer_count, 0, 'shutdown cleans all timers' );
        T2->is( $http->handle( $headers, $body )->get->[0], 503, 'closed endpoint rejects work' );
    }
);

T2->subtest(
    'signature freshness includes the exact boundary in both directions',
    sub {
        for my $case (
            { name => 'old boundary', offset => -300, status => 200 },
            { name => 'future boundary', offset => 300, status => 200 },
            { name => 'too old', offset => -301, status => 401 },

t/22-rest-models.t  view on Meta::CPAN

use v5.26;
use warnings;
use Test2::V1;
use JSON::PP;
use lib 't/lib';
use TestDiscordREST qw(client response error);
use Discord::Client::Model;

# Each public helper must preserve its endpoint, request shape and unknown response fields.
my @endpoints = (
    {
        name => 'current user discovery',
        method => 'get_current_user',
        args => [],
        verb => 'GET',
        path => '/users/@me',
        response => { id => '1', username => 'bot', future_field => 1 }
    },
    {
        name => 'user lookup',

t/22-rest-models.t  view on Meta::CPAN

    {
        name => 'typing indication',
        method => 'trigger_typing',
        args => ['2'],
        verb => 'POST',
        path => '/channels/2/typing',
        status => 204
    },
);

for my $case (@endpoints) {
    T2->subtest(
        "$case->{name} uses its Discord endpoint and preserves the response",
        sub {
            my ( $rest, $http ) = client();
            my $method = $case->{method};
            my $future = $rest->$method( @{ $case->{args} } );

            my $request = $http->call->{request};
            T2->is( $request->method, $case->{verb}, 'HTTP method' );
            T2->is( $request->uri->path, '/api/v10' . $case->{path}, 'API v10 route' );
            T2->is( { $request->uri->query_form }, $case->{query} // {}, 'query parameters' );
            if ( exists $case->{body} ) {



( run in 2.633 seconds using v1.01-cache-2.11-cpan-eb134014566 )