| 1 | package AnyEvent::Discord::Client; | ||
| 2 | 1 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 3 | 1 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | |||
| 5 | our $VERSION = '0.000002'; | ||
| 6 | $VERSION = eval $VERSION; | ||
| 7 | |||
| 8 | 0 | ▶ | use AnyEvent::WebSocket::Client; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 9 | use LWP::UserAgent; | ||
| 10 | use JSON; | ||
| 11 | use URI; | ||
| 12 | use HTTP::Request; | ||
| 13 | use HTTP::Headers; | ||
| 14 | use AnyEvent::HTTP; | ||
| 15 | |||
| 16 | my $debug = 0; | ||
| 17 | |||
| 18 | sub new { | ||
| 19 | my ($class, %args) = @_; | ||
| 20 | |||
| 21 | my $self = { | ||
| 22 | token => delete($args{token}), | ||
| 23 | api_root => delete($args{api_root}) // 'https://discordapp.com/api', | ||
| 24 | prefix => delete($args{prefix}) // "!", | ||
| 25 | commands => delete($args{commands}) // {}, | ||
| 26 | |||
| 27 | ua => LWP::UserAgent->new(), | ||
| 28 | api_useragent => "DiscordBot (https://github.com/topaz/perl-AnyEvent-Discord-Client, 0)", | ||
| 29 | |||
| 30 | user => undef, | ||
| 31 | guilds => {}, | ||
| 32 | channels => {}, | ||
| 33 | roles => {}, | ||
| 34 | |||
| 35 | gateway => undef, | ||
| 36 | conn => undef, | ||
| 37 | websocket => undef, | ||
| 38 | heartbeat_timer => undef, | ||
| 39 | last_seq => undef, | ||
| 40 | reconnect_delay => 1, | ||
| 41 | }; | ||
| 42 | |||
| 43 | die "cannot construct new $class without a token parameter" unless defined $self->{token}; | ||
| 44 | die "unrecognized extra parameters were given to $class->new" if %args; | ||
| 45 | |||
| 46 | return bless $self, $class; | ||
| 47 | } | ||
| 48 | |||
| 49 | sub commands { $_[0]{commands} } | ||
| 50 | sub user { $_[0]{user} } | ||
| 51 | sub guilds { $_[0]{guilds} } | ||
| 52 | sub channels { $_[0]{channels} } | ||
| 53 | sub roles { $_[0]{roles} } | ||
| 54 | |||
| 55 | my %event_handler = ( | ||
| 56 | READY => sub { | ||
| 57 | my ($self, $d) = @_; | ||
| 58 | $self->{user} = $d->{user}; | ||
| 59 | print "logged in as $self->{user}{username}.\n"; | ||
| 60 | print "ready!\n"; | ||
| 61 | }, | ||
| 62 | GUILD_CREATE => sub { | ||
| 63 | my ($self, $d) = @_; | ||
| 64 | $self->{guilds}{$d->{id}} = $d; | ||
| 65 | $self->{channels}{$_->{id}} = {%$_, guild_id=>$d->{id}} for @{$d->{channels}}; | ||
| 66 | $self->{roles}{$_->{id}} = {%$_, guild_id=>$d->{id}} for @{$d->{roles}}; | ||
| 67 | print "created guild $d->{id} ($d->{name})\n"; | ||
| 68 | }, | ||
| 69 | CHANNEL_CREATE => sub { | ||
| 70 | my ($self, $d) = @_; | ||
| 71 | $self->{channels}{$d->{id}} = $d; | ||
| 72 | push @{$self->{guilds}{$d->{guild_id}}{channels}}, $d if $d->{guild_id}; | ||
| 73 | print "created channel $d->{id} ($d->{name}) of guild $d->{guild_id} ($self->{guilds}{$d->{guild_id}}{name})\n"; | ||
| 74 | }, | ||
| 75 | CHANNEL_UPDATE => sub { | ||
| 76 | my ($self, $d) = @_; | ||
| 77 | %{$self->{channels}{$d->{id}}} = %$d; | ||
| 78 | print "updated channel $d->{id} ($d->{name}) of guild $d->{guild_id} ($self->{guilds}{$d->{guild_id}}{name})\n"; | ||
| 79 | }, | ||
| 80 | CHANNEL_DELETE => sub { | ||
| 81 | my ($self, $d) = @_; | ||
| 82 | @{$self->{guilds}{$d->{guild_id}}{channels}} = grep {$_->{id} != $d->{id}} @{$self->{guilds}{$d->{guild_id}}{channels}} if $d->{guild_id}; | ||
| 83 | delete $self->{channels}{$d->{id}}; | ||
| 84 | print "deleted channel $d->{id} ($d->{name}) of guild $d->{guild_id} ($self->{guilds}{$d->{guild_id}}{name})\n"; | ||
| 85 | }, | ||
| 86 | GUILD_ROLE_CREATE => sub { | ||
| 87 | my ($self, $d) = @_; | ||
| 88 | $self->{roles}{$d->{role}{id}} = $d->{role}; | ||
| 89 | push @{$self->{guilds}{$d->{guild_id}}{roles}}, $d->{role} if $d->{guild_id}; | ||
| 90 | print "created role $d->{role}{id} ($d->{role}{name}) of guild $d->{guild_id} ($self->{guilds}{$d->{guild_id}}{name})\n"; | ||
| 91 | }, | ||
| 92 | GUILD_ROLE_UPDATE => sub { | ||
| 93 | my ($self, $d) = @_; | ||
| 94 | %{$self->{roles}{$d->{role}{id}}} = %{$d->{role}}; | ||
| 95 | print "updated role $d->{role}{id} ($d->{role}{name}) of guild $d->{guild_id} ($self->{guilds}{$d->{guild_id}}{name})\n"; | ||
| 96 | }, | ||
| 97 | GUILD_ROLE_DELETE => sub { | ||
| 98 | my ($self, $d) = @_; | ||
| 99 | @{$self->{guilds}{$d->{guild_id}}{roles}} = grep {$_->{role}{id} != $d->{role}{id}} @{$self->{guilds}{$d->{guild_id}}{roles}} if $d->{guild_id}; | ||
| 100 | delete $self->{roles}{$d->{role}{id}}; | ||
| 101 | print "deleted role $d->{role}{id} ($d->{role}{name}) of guild $d->{guild_id} ($self->{guilds}{$d->{guild_id}}{name})\n"; | ||
| 102 | }, | ||
| 103 | TYPING_START => sub {}, | ||
| 104 | MESSAGE_CREATE => sub { | ||
| 105 | my ($self, $msg) = @_; | ||
| 106 | my $channel = $self->{channels}{$msg->{channel_id}}; | ||
| 107 | my $guild = $self->{guilds}{$channel->{guild_id}}; | ||
| 108 | |||
| 109 | #(my $hrcontent = $msg->{content) =~ s/[\x00-\x | ||
| 110 | print "[$guild->{name} ($guild->{id}) / $channel->{name} ($channel->{id})] <$msg->{author}{username}> $msg->{content}\n"; | ||
| 111 | #print STDERR join(",",unpack("U*", $msg->{content}))."\n"; | ||
| 112 | return if $msg->{author}{id} == $self->{user}{id}; | ||
| 113 | |||
| 114 | if ($msg->{content} =~ /^\Q$self->{prefix}\E(\S+)(?:\s+(.*?))?\s*$/ || $msg->{content} =~ /^\s*(.*?)\s*$/) { | ||
| 115 | my ($cmd, $args) = (lc $1, defined $2 ? $2 : ""); | ||
| 116 | if (exists $self->{commands}{$cmd}) { | ||
| 117 | $self->{commands}{$cmd}($self, $args, $msg, $channel, $guild); | ||
| 118 | } | ||
| 119 | } | ||
| 120 | }, | ||
| 121 | ); | ||
| 122 | |||
| 123 | sub connect { | ||
| 124 | my ($self) = @_; | ||
| 125 | |||
| 126 | if (!defined $self->{gateway}) { | ||
| 127 | # look up gateway url | ||
| 128 | my $gateway_data = $self->api_sync(GET => "/gateway"); | ||
| 129 | my $gateway = $gateway_data->{url}; | ||
| 130 | die 'invalid gateway' unless $gateway =~ /^wss\:\/\//; | ||
| 131 | $gateway = new URI($gateway); | ||
| 132 | $gateway->path("/") unless length $gateway->path; | ||
| 133 | $gateway->query_form(v=>6, encoding=>"json"); | ||
| 134 | $self->{gateway} = "$gateway"; | ||
| 135 | } | ||
| 136 | |||
| 137 | print "Connecting to $self->{gateway}...\n"; | ||
| 138 | |||
| 139 | $self->{reconnect_delay} *= 2; | ||
| 140 | $self->{reconnect_delay} = 5*60 if $self->{reconnect_delay} > 5*60; | ||
| 141 | |||
| 142 | $self->{websocket} = AnyEvent::WebSocket::Client->new(max_payload_size => 1024*1024); | ||
| 143 | $self->{websocket}->connect($self->{gateway})->cb(sub { | ||
| 144 | $self->{conn} = eval { shift->recv }; | ||
| 145 | if($@) { | ||
| 146 | print "$@\n"; | ||
| 147 | return; | ||
| 148 | } | ||
| 149 | |||
| 150 | print "websocket connected to $self->{gateway}.\n"; | ||
| 151 | $self->{reconnect_delay} = 1; | ||
| 152 | |||
| 153 | # send "identify" op | ||
| 154 | $self->websocket_send(2, { | ||
| 155 | token => $self->{token}, | ||
| 156 | properties => { | ||
| 157 | '$os' => "linux", | ||
| 158 | '$browser' => "zenbotta", | ||
| 159 | '$device' => "zenbotta", | ||
| 160 | '$referrer' => "", | ||
| 161 | '$referring_domain' => "" | ||
| 162 | }, | ||
| 163 | compress => JSON::false, | ||
| 164 | large_threshold => 250, | ||
| 165 | shard => [0, 1], | ||
| 166 | }); | ||
| 167 | |||
| 168 | $self->{conn}->on(each_message => sub { | ||
| 169 | my($connection, $message) = @_; | ||
| 170 | my $msg = decode_json($message->{body}); | ||
| 171 | die "invalid message" unless ref $msg eq 'HASH' && defined $msg->{op}; | ||
| 172 | |||
| 173 | $self->{last_seq} = 0+$msg->{s} if defined $msg->{s}; | ||
| 174 | |||
| 175 | if ($msg->{op} == 0) { #dispatch | ||
| 176 | print "\e[1;30mdispatch event $msg->{t}:".Dumper($msg->{d})."\e[0m\n" if $debug; | ||
| 177 | $event_handler{$msg->{t}}($self, $msg->{d}) if $event_handler{$msg->{t}}; | ||
| 178 | } elsif ($msg->{op} == 10) { #hello | ||
| 179 | $self->{heartbeat_timer} = AnyEvent->timer( | ||
| 180 | after => $msg->{d}{heartbeat_interval}/1e3, | ||
| 181 | interval => $msg->{d}{heartbeat_interval}/1e3, | ||
| 182 | cb => sub { | ||
| 183 | $self->websocket_send(1, $self->{last_seq}); | ||
| 184 | }, | ||
| 185 | ); | ||
| 186 | } elsif ($msg->{op} == 11) { #heartbeat ack | ||
| 187 | # ignore for now; eventually, notice missing ack and reconnect | ||
| 188 | } else { | ||
| 189 | print "\e[1;30mnon-event message op=$msg->{op}:".Dumper($msg)."\e[0m\n" if $debug; | ||
| 190 | } | ||
| 191 | }); | ||
| 192 | |||
| 193 | $self->{conn}->on(parse_error => sub { | ||
| 194 | my ($connection, $error) = @_; | ||
| 195 | print "parse_error: $error\n"; | ||
| 196 | exit; | ||
| 197 | }); | ||
| 198 | |||
| 199 | $self->{conn}->on(finish => sub { | ||
| 200 | my($connection) = @_; | ||
| 201 | print "Disconnected! Reconnecting in five seconds...\n"; | ||
| 202 | my $reconnect_timer; $reconnect_timer = AnyEvent->timer( | ||
| 203 | after => $self->{reconnect_delay}, | ||
| 204 | cb => sub { | ||
| 205 | $self->connect(); | ||
| 206 | $reconnect_timer = undef; | ||
| 207 | }, | ||
| 208 | ); | ||
| 209 | }); | ||
| 210 | }); | ||
| 211 | } | ||
| 212 | |||
| 213 | sub add_commands { | ||
| 214 | my ($self, %commands) = @_; | ||
| 215 | $self->{commands}{$_} = $commands{$_} for keys %commands; | ||
| 216 | } | ||
| 217 | |||
| 218 | sub api_sync { | ||
| 219 | my ($self, $method, $path, $data) = @_; | ||
| 220 | |||
| 221 | my $resp = $self->{ua}->request(HTTP::Request->new( | ||
| 222 | uc($method), | ||
| 223 | $self->{api_root} . $path, | ||
| 224 | HTTP::Headers->new( | ||
| 225 | Authorization => "Bot $self->{token}", | ||
| 226 | User_Agent => $self->{api_useragent}, | ||
| 227 | ($data ? (Content_Type => "application/json") : ()), | ||
| 228 | ( | ||
| 229 | !defined $data ? () | ||
| 230 | : ref $data ? ("Content_Type" => "application/json") | ||
| 231 | : ("Content_Type" => "application/x-www-form-urlencoded") | ||
| 232 | ), | ||
| 233 | ), | ||
| 234 | ( | ||
| 235 | !defined $data ? undef | ||
| 236 | : ref $data ? encode_json($data) | ||
| 237 | : $data | ||
| 238 | ), | ||
| 239 | )); | ||
| 240 | |||
| 241 | if (!$resp->is_success) { | ||
| 242 | return undef; | ||
| 243 | } | ||
| 244 | if ($resp->header("Content-Type") eq 'application/json') { | ||
| 245 | return JSON::decode_json($resp->decoded_content); | ||
| 246 | } else { | ||
| 247 | return 1; | ||
| 248 | } | ||
| 249 | } | ||
| 250 | |||
| 251 | sub websocket_send { | ||
| 252 | my ($self, $op, $d) = @_; | ||
| 253 | die "no connection!" unless $self->{conn}; | ||
| 254 | |||
| 255 | $self->{conn}->send(encode_json({op=>$op, d=>$d})); | ||
| 256 | } | ||
| 257 | |||
| 258 | sub say { | ||
| 259 | my ($self, $channel_id, $message) = @_; | ||
| 260 | $self->api(POST => "/channels/$channel_id/messages", {content => $message}); | ||
| 261 | } | ||
| 262 | |||
| 263 | sub typing { | ||
| 264 | my ($self, $channel) = @_; | ||
| 265 | return AnyEvent->timer( | ||
| 266 | after => 0, | ||
| 267 | interval => 5, | ||
| 268 | cb => sub { | ||
| 269 | $self->api(POST => "/channels/$channel->{id}/typing", ''); | ||
| 270 | }, | ||
| 271 | ); | ||
| 272 | } | ||
| 273 | |||
| 274 | sub api { | ||
| 275 | my ($self, $method, $path, $data, $cb) = @_; | ||
| 276 | http_request( | ||
| 277 | uc($method) => $self->{api_root} . $path, | ||
| 278 | timeout => 5, | ||
| 279 | recurse => 0, | ||
| 280 | headers => { | ||
| 281 | referer => undef, | ||
| 282 | authorization => "Bot $self->{token}", | ||
| 283 | "user-agent" => $self->{api_useragent}, | ||
| 284 | ( | ||
| 285 | !defined $data ? () | ||
| 286 | : ref $data ? ("content-type" => "application/json") | ||
| 287 | : ("content-type" => "application/x-www-form-urlencoded") | ||
| 288 | ), | ||
| 289 | }, | ||
| 290 | ( | ||
| 291 | !defined $data ? () | ||
| 292 | : ref $data ? (body => encode_json($data)) | ||
| 293 | : (body => $data) | ||
| 294 | ), | ||
| 295 | sub { | ||
| 296 | my ($body, $hdr) = @_; | ||
| 297 | return unless $cb; | ||
| 298 | $cb->(!defined $body ? undef : defined $hdr->{"content-type"} && $hdr->{"content-type"} eq 'application/json' ? decode_json($body) : 1, $hdr); | ||
| 299 | }, | ||
| 300 | ); | ||
| 301 | } | ||
| 302 | |||
| 303 | 1; | ||
| 304 | |||
| 305 | __END__ | ||