AnyEvent::SlackBot - AnyEvent Driven Slack Bot Interface


  use Modern::Perl;
  use Data::Dumper;
  use AnyEvent::SlackBot;
  use AnyEvent::Loop;

  my $sb=AnyEvent::SlackBot->new(
    on_event=>sub {
      my ($sb,$json,$conn_data)=@_;
      if(exists $json->{type} and $json->{type} eq 'desktop_notification') {
        my $ref={
          text=>'this is a test',
        print Dumper($json,$ref);

  my $result=$sb->connect_and_run;
  die $result unless $result;


Slack client. Handles Ping Pong on idle conntions, and transparrently reconnects as needed. The guts of the module wrap AnyEvent::WebSocket::Client, keeping the code base very light.

OO Arguments and accessors

Required Arguments

  on_event: code refrence for handling events
    sub { my ($self,$connection,$message,$startup_info)=@_ }

Optional Arguments

  on_idle: code refrence for use in idle time
    sub { my ($self)=@_ }

  on_reply: code refrence called when the server responds to a post
    sub { my ($self,$json,$connection_data)=@_ }

  agent: Sets the AnyEvent::HTTP::MultiGet Object
  logger: sets the logging object, DOES( Log::Log4perl::Logger )
  rtm_start_url: the url used to fetch the websockets connection from
  token: the authentication token used by rtm_start_url
  auto_reconnect: if true ( default ) reconnects when a connection fails
  unknown_que: array ref of objects that may be repeats from us

Set at Run time

  connection: The connection object
  bot_id:     The Bot ID defined at runtime
  stats:      An anonyous hash ref of useful stats

OO Methods

  • $self->connect_and_run

    COnnects and starts running

  • my $id=$self->next_id

    Provides an id for the next message.

  • if($self->is_connected) { ... }

    Denotes if we are currently connected to slack

  • $self->send($ref)

    Converts $ref to json and sends it on the session.

  • $self->send_typing($json)

    Given $json sends a currently typing reply

  • $self->post_to_web($msg,$endpoint|undef,"FORM"|"JSON"|undef)

    Posts the to the given REST Endpoint outside of the WebSocket.

        Hash ref representing the requrest being sent
          token: set to $self->token if not set
          scope: set to: 'chat:write:bot' if not set
        The Rest xxx endpint, the default is 'chat.postMessage'
        Sets how the data will be sent over
        Supported options are:
          - FORM: posts the data using form encoding
          - JSON: converts $msg to a json string and posts
  • if($self->we_sent_msg($json,$connection_data)) { ... }

    When true, $json is a duplicate from something we sent

  • $self->build_connection($connection_details)

    Internal Method used for buiding connections.

  • $self->handle_reconnect

    Internal method used to reconnect.

See Also

The slack api documentation -

The AnyEvent WebSocket Client library - AnyEvent::WebSocket::Client

The AnyEvent HTTP Client library - AnyEvent::HTTP::MultiGet


Michael Shipper mailto:AKALINUX@CPAN.ORG