AnyEvent-Discord

 view release on metacpan or  search on metacpan

lib/AnyEvent/Discord.pm  view on Meta::CPAN

    $self->{'_sequence'} = undef;
    $self->_socket->close();
  }

  # Make an HTTP request to the Discord API
  method _discord_api(Str $method, Str $path, $payload?) {
    my $headers = HTTP::Headers->new(
      Authorization => 'Bot ' . $self->token,
      User_Agent    => $self->user_agent,
      Content_Type  => 'application/json',
    );
    my $request = HTTP::Request->new(
      uc($method),
      join('/', $self->base_uri, $path),
      $headers,
      $payload,
    );
    $self->_trace('api req: ' . $request->as_string());
    my $res = $self->_ua->request($request);
    $self->_trace('api res: ' . $res->as_string());
    if ($res->is_success()) {
      if ($res->header('Content-Type') eq 'application/json') {
        return decode_json($res->decoded_content());
      } else {
        return $res->decoded_content();
      }
    }
    return;
  }

  # Send the 'identify' event to the Discord websocket
  method _discord_identify() {
    $self->_debug('Sending identify');
    $self->_ws_send_payload(AnyEvent::Discord::Payload->from_hashref({
      op => 2,
      d  => {
        token           => $self->token,
        compress        => JSON::false,
        large_threshold => 250,
        shard           => [0, 1],
        properties => {
          '$os'      => 'linux',
          '$browser' => $self->user_agent(),
          '$device'  => $self->user_agent(),
        }
      }
    }));
  }

  # Send a payload to the Discord websocket
  method _ws_send_payload(AnyEvent::Discord::Payload $payload) {
    unless ($self->_socket) {
      $self->_debug('Attempted to send payload to disconnected socket');
      return;
    }
    my $msg = $payload->as_json;
    $self->_trace('ws out: ' . $msg);
    $self->_socket->send($msg);
  }

  # Look up the gateway endpoint using the Discord API
  method _lookup_gateway() {
    my $payload = $self->_discord_api('GET', 'gateway');
    die 'Invalid gateway returned by API' unless ($payload and $payload->{url} and $payload->{url} =~ /^wss/);

    # Add the requested version and encoding to the provided URL
    my $gateway = $payload->{url};
    $gateway .= '/' unless ($gateway =~/\/$/);
    $gateway .= '?v=6&encoding=json';
    return $gateway;
  }

  # Dispatch an internal event type
  method _handle_internal_event(Str $type) {
    foreach my $event_source (qw(_internal_events _events)) {
      if ($self->{$event_source}->{$type}) {
        map {
          $self->_debug('Sending ' . ( $event_source =~ /internal/ ? 'internal' : 'caller' ) . ' event ' . $type);
          $_->($self);
        } @{ $self->{$event_source}->{$type} };
      }
    }
  }

  # Dispatch a Discord event type
  method _handle_event(AnyEvent::Discord::Payload $payload) {
    my $type = lc($payload->t);
    $self->_debug('Got event ' . $type);
    foreach my $event_source (qw(_internal_events _events)) {
      if ($self->{$event_source}->{$type}) {
        map {
          $self->_debug('Sending ' . ( $event_source =~ /internal/ ? 'internal' : 'caller' ) . ' event ' . $type);
          $_->($self, $payload->d, $payload->op);
        } @{ $self->{$event_source}->{$type} };
      }
    }
  }

  # Send debug messages to console if verbose is >=1
  method _debug(Str $message) {
    say time . ' ' . $message if ($self->verbose);
  }

  # Send trace messages to console if verbose is 2
  method _trace(Str $message) {
    say time . ' ' . $message if ($self->verbose and $self->verbose == 2);
  }

  # Called when Discord provides the 'hello' event
  method _event_hello(AnyEvent::Discord::Payload $payload) {
    $self->_debug('Received hello event');
    my $interval = $payload->d->{'heartbeat_interval'};
    my $timer = AnyEvent->timer(
      after    => $interval * rand() / 1000,
      interval => $interval / 1000,
      cb       => sub {
        $self->_debug('Heartbeat');
        $self->_ws_send_payload(AnyEvent::Discord::Payload->from_hashref({
          op => 1,
          d  => $self->_sequence()
        }));

lib/AnyEvent/Discord.pm  view on Meta::CPAN


=head1 PUBLIC METHODS

=over 4

=item new(\%arguments)

Instantiate the AnyEvent::Discord client. The hashref of arguments matches the
configuration accessors listed above. A common invocation looks like:

  my $client = AnyEvent::Discord->new({ token => 'ABCDEF' });

=item on($event_type, \&handler)

Attach an event handler to a defined event type. If an invalid event type is
specified, no error will occur -- this is mostly to be able to handle events
that are created after this module is published. This is an append method, so
calling on() for an event multiple times will call each callback assigned. If
the handler already exists for an event, no error will be returned, but the
handler will not be called twice.

Discord event types: https://discord.com/developers/docs/topics/gateway#list-of-intents

Opcodes: https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-opcodes

These events receive the parameters client, data object (d) and the opcode (op).
The $client variable is this instance of AnyEvent::Discord, and the contents of
$data and $op are dependent on the event type.

  sub event_responder {
    my ($client, $data, $opcode) = @_;
    return;
  }

Internal event types:

=over 4

=item disconnected

Receives no parameters, just notifies a disconnection will occur. It will
auto reconnect.

=item error

Receives an error message as a parameter, allows internal handling of errors
that are not a hard failure.

=back

=item off($event_type, \&handler?)

Detach an event handler from a defined event type. If the handler does not
exist for the event, no error will be returned. If no handler is provided, all
handlers for the event type will be removed.

=item connect()

Start connecting to the Discord API and return immediately. In a new AnyEvent
application, this would come before executing "AnyEvent->condvar->recv". This
method will retrieve the available gateway endpoint, create a connection,
identify itself, begin a heartbeat, and once complete, Discord will fire a
'ready' event to the handler.

=item send($channel_id, $content)

Send a message to the provided channel.

=item typing($channel_id)

Starts the "typing..." indicator in the provided channel. This method issues the
typing request, and starts a timer on the caller's behalf to keep the indicator
active. Returns an instance of that timer to allow the caller to undef it when
the typing indicator should be stopped.

  my $instance = $client->typing($channel);
  # ... perform some actions
  $instance = undef;
  # typing indicator disappears

=item close()

Close the connection to the server.

=back

=head1 CAVEATS

This is incredibly unfinished.

=head1 AUTHOR

Nick Melnick <nmelnick@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2021, Nick Melnick.

This is free software; you can redistribute it and/or modify it under the same
terms as the Perl 5 programming language system itself.

=cut



( run in 0.567 second using v1.01-cache-2.11-cpan-cdf2f3d4e48 )