2 # slirc.pl: local Slack IRC gateway
3 # Copyright (C) 2017-2019 Daniel Beer <dlbeer@gmail.com>
5 # Permission to use, copy, modify, and/or distribute this software for any
6 # purpose with or without fee is hereby granted, provided that the above
7 # copyright notice and this permission notice appear in all copies.
9 # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 # To run, create a configuration file with the following content:
19 # slack_token=<legacy API token>
20 # password=<password of your choice>
23 # Then run ./slirc.pl <config-file>. Connect to the chosen port on
24 # 127.0.0.1 with your chosen password.
26 # Updated 2018-05-15 to add support for listening on Unix domain sockets
27 # by Colin Watson <cjwatson@chiark.greenend.org.uk>. To use this feature
28 # with an IRC client supporting Unix domain connections, add the line
29 # "unix_socket=<path>" to the config file.
32 # - HTML entities are now escaped/unescaped properly
33 # - Channel IDs are translated with the correct sigil
34 # - You can now close accumulated group chats. This is mapped to
35 # JOIN/PART (the behaviour of JOIN/PART for public channels is
37 # - IRC-side PING checks are now more lenient, to work around bugs in
39 # - Added X commands for debug dumps and dynamically switching protocol
42 # Updated 2019-05-08 based on changes from Neia Finch to improve
52 use AnyEvent::WebSocket::Client;
53 use URI::Encode qw(uri_encode);
56 use Digest::SHA qw(sha256);
59 my $VERSION = "20190225";
60 my $start_time = time();
65 ########################################################################
67 ########################################################################
69 my $connected; # Is the RTM connection ready?
70 my $self_id; # Slack ID of our own user, or undef
72 my %channels; # Slack ID -> channel hash ref
73 my %channels_by_name; # irc_lcase -> channel hash ref
76 # - Members: Slack ID set
77 # - Name: text (IRC name)
80 my %users; # Slack ID -> user hash ref
81 my %users_by_name; # irc_lcase -> user hash ref
82 my %users_by_dmid; # Slack DMID -> user hash ref
85 # - Name: text (IRC name)
86 # - Channels: Slack ID set
88 # - DMId: DM session ID (may be undefined, or blank if open in progress)
89 # - TxQueue: messages awaiting transmission if no DM open
91 ########################################################################
93 ########################################################################
95 # Canonicalize an IRC name
111 return irc_lcase($a) eq irc_lcase($b);
114 # Choose an unused valid name with reference to the hash
116 my ($name, $hash) = @_;
118 $name =~ s/[#,<>!\0\r\n: ]/_/g;
120 return $name if length($name) && irc_lcase($name) ne "x" &&
121 !defined($hash->{irc_lcase($name)});
126 my $prop = "$name$i";
128 return $prop unless defined($hash->{irc_lcase($prop)});
133 ########################################################################
135 ########################################################################
137 # Forward decls to RTM subsystem
139 sub rtm_send_to_user;
149 my ($c, $source, $short, $long) = @_;
151 $source =~ s/[\t\r\n\0 ]//g;
153 my @arg = (":$source");
155 for my $a (@$short) {
156 $a =~ s/[\t\r\n\0 ]//g;
159 $a = "*" unless length($a);
163 if (defined($long)) {
164 $long =~ s/[\r\n\0]/ /g;
169 my $line = join(' ', @arg);
170 print "IRC $c->{Handle} SEND: $line\n" if $config{debug_dump};
171 $c->{Handle}->push_write("$line\r\n");
175 my ($c, $num, $short, $long) = @_;
176 my $dst = $c->{Nick};
178 $dst = "*" unless defined($c->{Nick});
179 irc_send_args $c, "localhost",
180 [sprintf("%03d", $num), $dst, @$short], $long;
184 my ($c, $uid, $short, $long) = @_;
185 my $user = $users{$uid};
186 my $nick = $uid eq $self_id ? $c->{Nick} : $user->{Name};
188 irc_send_args $c, "$nick!$user->{Id}\@localhost", $short, $long;
194 print "IRC $c->{Handle} DISCONNECT: $msg\n";
195 delete $irc_clients{$c->{Handle}};
196 $c->{Handle}->destroy;
199 sub irc_disconnect_all {
200 print "IRC: disconnect all\n";
201 foreach my $k (keys %irc_clients) {
202 $irc_clients{$k}->{Handle}->destroy;
210 my @ulist = keys %{$chan->{Members}};
212 while ($i < @ulist) {
215 my $chunk = join(' ', map {
216 $_ eq $self_id ? $c->{Nick} : $users{$_}->{Name}
217 } @ulist[$i .. ($i + $n - 1)]);
218 irc_send_num $c, 353, ['@', "#$chan->{Name}"], $chunk;
222 irc_send_num $c, 366, ["#$chan->{Name}"], "End of /NAMES list";
225 sub irc_server_notice {
227 my $nick = $c->{Nick};
229 $nick = "*" unless defined($nick);
230 irc_send_args $c, "localhost", ["NOTICE", $nick], $msg;
233 sub irc_gateway_notice {
235 my $nick = $c->{Nick};
237 $nick = "*" unless defined($nick);
238 irc_send_args $c, "X!X\@localhost", ["NOTICE", $nick], $msg;
241 sub irc_notify_away {
243 my $user = $users{$self_id};
246 if ($user->{Presence} eq 'away') {
248 $msg = "You have been marked as being away";
251 $msg = "You are no longer marked as being away";
254 irc_send_num $c, $num, [], $msg if $c->{Ready};
257 sub irc_broadcast_away {
258 for my $k (keys %irc_clients) {
259 my $c = $irc_clients{$k};
260 irc_notify_away $c if $c->{Ready};
269 ' ___| (_)_ __ ___ _ __ | |',
270 '/ __| | | \'__/ __| | \'_ \| |',
271 '\__ \ | | | | (__ _| |_) | |',
272 '|___/_|_|_| \___(_) .__/|_|',
274 'slirc.pl, Copyright (C) 2017-2019 Daniel Beer <dlbeer@gmail.com>'
277 for my $x (@banner) {
278 irc_send_num $c, 372, [], $x;
280 irc_send_num $c, 376, [], "End of /MOTD command";
283 sub irc_check_welcome {
286 if (defined $c->{Nick} && defined $c->{User} &&
287 (!$config{password} || defined $c->{Password}) &&
289 if (!$config{password} ||
290 sha256($c->{Password}) eq sha256($config{password})) {
293 irc_server_notice $c, "Incorrect password";
294 irc_disconnect $c, "Incorrect password";
299 return unless $c->{Authed} && !$c->{Ready} && $connected;
301 my $u = $users_by_name{irc_lcase($c->{Nick})};
302 if (defined($u) && ($u->{Id} ne $self_id)) {
303 irc_server_notice $c, "Nick already in use";
304 irc_disconnect $c, "Nick already in use";
308 my $lt = localtime($start_time);
310 irc_send_num $c, 001, [], "slirc.pl IRC-to-Slack gateway";
311 irc_send_num $c, 002, [], "This is slirc.pl version $VERSION";
312 irc_send_num $c, 003, [], "Server started " . ctime($start_time);
316 my $user = $users{$self_id};
318 for my $k (keys %{$user->{Channels}}) {
319 my $chan = $channels{$k};
320 irc_send_from $c, $self_id, ["JOIN", "#$chan->{Name}"];
321 irc_send_num $c, 332, ["#$chan->{Name}"], $chan->{"Topic"};
322 irc_send_names $c, $chan;
328 sub irc_check_welcome_all {
329 foreach my $k (keys %irc_clients) {
330 irc_check_welcome $irc_clients{$k};
334 sub irc_broadcast_nick {
335 my ($id, $newname) = @_;
336 return if $id eq $self_id;
338 for my $k (keys %irc_clients) {
339 my $c = $irc_clients{$k};
340 irc_send_from $c, $id, ["NICK", $newname] if $c->{Ready};
344 sub irc_broadcast_join {
345 my ($uid, $chid) = @_;
346 my $chan = $channels{$chid};
348 for my $k (keys %irc_clients) {
349 my $c = $irc_clients{$k};
350 next unless $c->{Ready};
352 if ($uid eq $self_id) {
353 irc_send_from $c, $self_id, ["JOIN", "#$chan->{Name}"];
354 irc_send_num $c, 332, ["#$chan->{Name}"], $chan->{Topic};
355 irc_send_names $c, $chan;
357 irc_send_from $c, $uid, ["JOIN", "#$chan->{Name}"];
362 sub irc_broadcast_part {
363 my ($uid, $chid) = @_;
364 my $chan = $channels{$chid};
366 for my $k (keys %irc_clients) {
367 my $c = $irc_clients{$k};
368 next unless $c->{Ready};
369 irc_send_from $c, $uid, ["PART", "#$chan->{Name}"];
374 my ($c, $chname, $u) = @_;
376 my $user = $users{$u};
377 my $nick = $u eq $self_id ? $c->{Nick} : $user->{Name};
378 my $here = $user->{Presence} eq 'away' ? 'G' : 'H';
380 irc_send_num $c, 352, [$chname, $user->{Id}, "localhost", "localhost",
381 $nick, $here], "0 $user->{Realname}";
386 my $u = $users{$uid};
387 my $nick = $uid eq $self_id ? $c->{Nick} : $u->{Name};
389 irc_send_num $c, 311,
390 [$nick, $u->{Id}, "localhost", "*"], $u->{Realname};
391 irc_send_num $c, 312, [$nick, "localhost"], "slirc.pl";
392 my $clist = join(' ', map { "#" . $channels{$_}->{Name} }
393 keys %{$u->{Channels}});
394 irc_send_num $c, 319, [$nick], $clist;
395 irc_send_num $c, 301, [$nick], "away" if $u->{Presence} eq 'away';
398 sub irc_invite_or_kick {
399 my ($c, $action, $name, $chname) = @_;
402 my $chan = $channels_by_name{irc_lcase($chname)};
404 unless (defined $chan) {
405 irc_send_num $c, 401, ["#$chname"], "No such nick/channel";
409 my $what = $chan->{Type} eq "C" ? "channels" : "groups";
411 foreach (split(/,/, $name)) {
412 my $user = $users_by_name{irc_lcase($_)};
415 rtm_apicall "$what.$action", { user => $user->{Id},
416 channel => $chan->{Id} };
418 irc_send_num $c, 401, [$user], "No such nick/channel";
423 my %gateway_command = (
424 "debug_dump_state" => sub {
426 irc_gateway_notice $c, "Dumping debug state on stdout";
427 print Dumper({ "connected" => $connected,
428 "self_id", => $self_id,
429 "%channels" => \%channels,
430 "%channels_by_name" => \%channels_by_name,
432 "users_by_name" => \%users_by_name,
433 "users_by_dmid" => \%users_by_dmid
436 "debug_dump" => sub {
438 $config{debug_dump} = $arg ? 1 : 0 if defined $arg;
439 irc_gateway_notice $c, "Protocol debug is " .
440 ($config{debug_dump} ? "on" : "off");
444 unless (defined($name)) {
445 irc_gateway_notice $c, "Syntax: newgroup <name>";
449 irc_gateway_notice $c, "Creating group $name";
450 rtm_apicall "groups.create", { name => $name };
454 unless (defined($name)) {
455 irc_gateway_notice $c, "Syntax: newchan <name>";
459 irc_gateway_notice $c, "Creating channel $name";
460 rtm_apicall "channels.create", { name => $name };
464 unless (defined($name)) {
465 irc_gateway_notice $c, "Syntax: archive <name>";
469 my $g = $channels_by_name{irc_lcase($name)};
470 my $what = $g->{Type} eq "C" ? "channels" : "groups";
472 irc_gateway_notice $c, "Archiving $name";
473 rtm_apicall "$what.archive", { channel => $g->{Id} };
475 irc_gateway_notice $c, "No such channel: $name";
480 unless (defined($name)) {
481 irc_gateway_notice $c, "Syntax: close <name>";
486 my $g = $channels_by_name{irc_lcase($name)};
487 my $what = $g->{Type} eq "C" ? "channels" : "groups";
489 irc_gateway_notice $c, "Closing $name";
490 rtm_apicall "$what.close", { channel => $g->{Id} };
492 irc_gateway_notice $c, "No such channel: $name";
496 my ($c, $fileid) = @_;
497 unless (defined($fileid)) {
498 irc_gateway_notice $c, "Syntax: cat <fileid> <filename>";
502 rtm_apicall "files.info", { file => $fileid }, sub {
504 return unless defined $data;
506 my $body = $data->{content};
508 if (length($body) > 65536) {
509 irc_gateway_notice $c, "File too big";
511 irc_gateway_notice $c, "---- BEGIN $fileid ----";
512 foreach (split(/\n/, $body)) {
513 irc_gateway_notice $c, "$_";
515 irc_gateway_notice $c, "---- END $fileid ----";
519 "disconnect" => sub {
521 irc_gateway_notice $c, "Disconnecting";
522 rtm_destroy "User disconnection request";
526 unless (defined($nick)) {
527 irc_gateway_notice $c, "Syntax: delim <name>";
532 if ($nick eq $c->{Nick}) {
533 $user = $users{$self_id};
535 $user = $users_by_name{irc_lcase($nick)};
536 $user = undef if $user->{Id} eq $self_id;
539 unless (defined($user)) {
540 irc_gateway_notice $c, "No such nick: $nick";
544 unless (defined $user->{DMId}) {
545 irc_gateway_notice $c, "DM already closed for $nick";
549 irc_gateway_notice $c, "Closing DM for $nick";
550 rtm_apicall "im.close", { channel => $user->{DMId} };
556 my ($c, $newnick) = @_;
557 return unless defined($newnick);
559 if (defined $c->{Nick}) {
560 my $u = $users_by_name{irc_lcase($newnick)};
561 if (defined($u) && ($u->{Id} ne $self_id)) {
562 irc_send_num $c, 433, [$newnick], "Nickname is already in use";
564 irc_send_from $c, $self_id, ["NICK"], $newnick;
565 $c->{Nick} = $newnick;
568 $c->{Nick} = $newnick;
569 irc_check_welcome $c;
575 $c->{Password} = $pass;
576 irc_check_welcome $c;
580 return unless scalar(@arg) >= 4;
582 $c->{User} = $arg[0];
583 $c->{Realname} = $arg[3];
584 irc_check_welcome $c;
588 return unless $c->{Ready};
589 my $presence = defined $msg ? "away" : "auto";
590 rtm_apicall "users.setPresence", { presence => $presence };
593 my ($c, $reply) = @_;
594 $reply = "" unless defined($reply);
595 irc_send_args $c, "localhost", ["PONG"], $reply;
598 my ($c, $name, $chname) = @_;
599 return unless $c->{Ready};
600 irc_invite_or_kick $c, "invite", $name, $chname;
603 my ($c, $name, $chname) = @_;
604 return unless $c->{Ready};
605 irc_invite_or_kick $c, "kick", $name, $chname;
609 return unless $c->{Ready};
610 return unless defined($name);
612 foreach my $n (split(/,/, $name)) {
614 my $chan = $channels_by_name{irc_lcase($n)};
615 if (not defined $chan) {
616 irc_send_num $c, 401, ["#$n"], "No such nick/channel";
617 } elsif ($chan->{Members}->{$self_id}) {
619 } elsif ($chan->{Type} eq "G") {
620 rtm_apicall "groups.open", { channel => $chan->{Id} };
621 irc_broadcast_join $self_id, $chan->{Id}
622 if rtm_update_join $self_id, $chan->{Id};
624 #rtm_apicall "channels.join", { channel => $chan->{Id} };
625 rtm_apicall "conversations.join", { channel => $chan->{Id} };
630 my ($c, $arg, $what) = @_;
631 return unless $c->{Ready};
632 return unless defined($arg);
636 if ($arg eq $c->{Nick}) {
637 irc_send_num $c, 221, [], "+i";
638 } elsif ($arg =~ /^#(.*)$/) {
639 my $chan = $channels_by_name{$1};
643 irc_send_num $c, 368, ["#$chan->{Name}"],
644 "End of channel ban list";
646 irc_send_num $c, 324,
648 ($chan->{Type} eq "G" ? "+ip" : "+p")];
649 irc_send_num $c, 329,
650 ["#$chan->{Name}", $start_time];
653 irc_send_num $c, 403, [$arg], "No such channel";
656 irc_send_num $c, 403, [$arg], "No such channel";
660 my ($c, $name, $topic) = @_;
661 return unless defined($name) && defined($topic);
662 return unless $c->{Ready};
665 my $chan = $channels_by_name{irc_lcase($name)};
666 unless (defined($chan)) {
667 irc_send_num $c, 401, ["#$name"], "No such nick/channel";
671 my $what = $chan->{Type} eq "C" ? "channels" : "groups";
673 rtm_apicall "$what.setTopic", { channel => $chan->{Id},
678 return unless $c->{Ready};
679 return unless defined($name);
681 foreach my $n (split(/,/, $name)) {
683 my $chan = $channels_by_name{irc_lcase($n)};
684 if (not defined($chan)) {
685 irc_send_num $c, 401, ["#$n"], "No such nick/channel";
686 } elsif ($chan->{Members}->{$self_id}) {
687 if ($chan->{Type} eq "G") {
688 rtm_apicall "groups.close", { channel => $chan->{Id} };
689 irc_broadcast_part $self_id, $chan->{Id}
690 if rtm_update_part $self_id, $chan->{Id};
692 #rtm_apicall "channels.leave", { channel => $chan->{Id} };
693 rtm_apicall "conersations.leave", { channel => $chan->{Id} };
700 return unless $c->{Ready};
702 irc_send_num $c, 321, ["Channel"], "Users Name";
703 foreach my $chid (keys %channels) {
704 my $chan = $channels{$chid};
705 my $n = keys %{$chan->{Members}};
707 irc_send_num $c, 322, ["#$chan->{Name}", $n], $chan->{Topic};
709 irc_send_num $c, 323, [], "End of /LIST";
712 my ($c, $nicklist) = @_;
713 return unless $c->{Ready};
714 return unless defined($nicklist);
717 for my $nick (split(/,/, $nicklist)) {
718 if (irc_eq($nick, "x")) {
719 irc_send_num $c, 311,
720 ["X", "X", "localhost", "*"], "Gateway service";
721 irc_send_num $c, 312, ["X", "localhost"], "slirc.pl";
722 } elsif (irc_eq($nick, $c->{Nick})) {
723 irc_send_whois $c, $self_id;
727 if ($nick =~ /^.*!([^@]*)/) {
730 $user = $users_by_name{irc_lcase($nick)};
731 $user = undef if defined($user) && $user->{Id} eq $self_id;
734 if (defined($user)) {
735 irc_send_whois $c, $user->{Id};
737 irc_send_num $c, 401, [$nick], "No such nick/channel";
742 irc_send_num $c, 318, [$nicklist], "End of /WHOIS list";
746 return unless $c->{Ready};
747 return unless defined($name);
751 my $chan = $channels_by_name{irc_lcase($n)};
752 unless (defined($chan)) {
753 irc_send_num $c, 401, [$name], "No such nick/channel";
757 irc_send_names $c, $chan;
761 return unless $c->{Ready};
763 if (!defined($name)) {
764 foreach my $u (keys %users) {
765 irc_send_who $c, "*", $u;
767 irc_send_num $c, 352, ["*", "X", "localhost", "localhost",
768 "X", "H"], "0 Gateway service";
769 } elsif (irc_eq($name, "X")) {
770 irc_send_num $c, 352, ["*", "X", "localhost", "localhost",
771 "X", "H"], "0 Gateway service";
772 } elsif ($name =~ /^.*!([^@]*)/) {
773 unless (exists $users{$1}) {
774 irc_send_num $c, 401, [$name], "No such nick/channel";
778 irc_send_who $c, $name, $1;
779 } elsif ($name =~ /^#(.*)$/) {
780 my $chan = $channels_by_name{irc_lcase($1)};
782 unless (defined($chan)) {
783 irc_send_num $c, 401, [$name], "No such nick/channel";
787 foreach my $u (keys %{$chan->{Members}}) {
788 irc_send_who $c, "#$chan->{Name}", $u;
791 my $user = $users_by_name{irc_lcase($name)};
793 unless (defined($user)) {
794 irc_send_num $c, 401, [$name], "No such nick/channel";
798 irc_send_who $c, $name, $self_id;
801 $name = "*" unless defined($name);
802 irc_send_num $c, 315, [$name], "End of /WHO list";
809 my ($c, $namelist, $msg) = @_;
810 return unless $c->{Ready};
811 return unless defined($namelist) && defined($msg);
816 $msg =~ s/"/"/g;
817 $msg =~ s/<@([^>]+)>/'<@' . irc_name_to_id($c, $1) . '>'/eg;
818 $msg =~ s/<#([^>]+)>/'<#' . irc_chan_to_id($c, $1) . '>'/eg;
820 foreach my $name (split(/,/, $namelist)) {
821 if (irc_eq($name, "X")) {
822 my @args = split(/ */, $msg);
823 my $cmd = shift @args;
824 my $handler = $gateway_command{lc($cmd)};
826 if (defined $handler) {
827 $handler->($c, @args);
829 irc_gateway_notice $c, "Unknown command: $cmd";
831 } elsif ($name =~ /^#(.*)$/) {
832 my $chan = $channels_by_name{irc_lcase($1)};
836 type => "message", channel => $chan->{Id},
839 irc_send_num $c, 401, [$name], "No such nick/channel";
841 } elsif (irc_eq($name, $c->{Nick})) {
842 rtm_send_to_user $self_id, $msg;
844 my $user = $users_by_name{irc_lcase($name)};
847 rtm_send_to_user $user->{Id}, $msg;
849 irc_send_num $c, 401, [$name], "No such nick/channel";
855 shift->{PingCount} = 0;
859 irc_disconnect $c, "QUIT";
863 sub irc_broadcast_notice {
866 print "NOTICE: $msg\n";
867 foreach my $k (keys %irc_clients) {
868 my $c = $irc_clients{$k};
869 irc_server_notice $c, $msg if $c->{Authed};
875 return $c->{Nick} if $id eq $self_id;
877 return $u->{Name} if defined($u);
883 return $self_id if $name eq $c->{Nick};
884 my $u = $users_by_name{$name};
885 return $u->{Id} if defined($u);
891 my $ch = $channels{$id};
892 return $ch->{Name} if defined ($ch);
898 my $ch = $channels_by_name{$chan};
899 return $ch->{Id} if defined($ch);
904 my ($srcid, $dstname, $subtype, $text) = @_;
908 $prefix = "\002[$subtype]\002 " if defined($subtype);
910 for my $k (keys %irc_clients) {
911 my $c = $irc_clients{$k};
912 next unless $c->{Ready};
914 my $translate = $text;
915 $translate =~ s/<@([^>]+)>/'<@' . irc_id_to_name($c, $1) . '>'/eg;
916 $translate =~ s/<#([^>]+)>/'<#' . irc_id_to_chan($c, $1) . '>'/eg;
917 $translate =~ s/</</g;
918 $translate =~ s/>/>/g;
919 $translate =~ s/"/"/g;
920 $translate =~ s/&/&/g;
922 for my $line (split(/\n/, $translate)) {
923 irc_send_from $c, $srcid, ["PRIVMSG", $dstname], "$prefix$line";
929 my ($id, $subtype, $msg) = @_;
931 irc_do_message $id, $users{$id}->{Name}, $subtype, $msg;
935 my ($id, $subtype, $chid, $msg) = @_;
936 irc_do_message $id, "#$channels{$chid}->{Name}", $subtype, $msg;
939 sub irc_topic_change {
940 my ($id, $chid) = @_;
941 my $chan = $channels{$chid};
943 foreach my $k (keys %irc_clients) {
944 my $c = $irc_clients{$k};
946 irc_send_from $c, $id, ["TOPIC", "#$chan->{Name}"], $chan->{Topic}
954 if (++$c->{PingCount} >= 3) {
955 irc_disconnect $c, "Ping timeout";
959 irc_send_args $c, "localhost", ["PING"], time();
960 $c->{PingTimer} = AnyEvent->timer(after => 60, cb => sub { irc_ping($c); });
964 my ($c, $fh, $line, $eol) = @_;
966 print "IRC $fh RECV: $line\n" if $config{debug_dump};
970 my $smallargs = $line;
973 if ($line =~ /^(.*?) :(.*)$/) {
978 my @words = split / */, $smallargs;
979 push @words, $bigarg if defined($bigarg);
981 if (scalar(@words)) {
982 my $cmd = shift @words;
983 my $handler = $irc_command{uc($cmd)};
985 $handler->($c, @words) if (defined($handler));
988 $fh->push_read(line => sub { irc_line($c, @_) });
992 print "Start IRC listener\n";
993 my $listen_host = $config{unix_socket} ? "unix/" : "127.0.0.1";
994 tcp_server $listen_host,
995 ($config{unix_socket} || $config{port} || 6667), sub {
996 my ($fd, $host, $port) = @_;
999 $fh = new AnyEvent::Handle
1002 my ($fh, $fatal, $msg) = @_;
1003 irc_disconnect $irc_clients{$fh}, "error: $msg";
1007 irc_disconnect $irc_clients{$fh}, "EOF";
1010 print "IRC $fh Got connection from $host:$port\n";
1012 my $c = { Handle => $fh };
1013 $c->{PingTimer} = AnyEvent->timer(after => 30,
1014 cb => sub { irc_ping $c; });
1015 $c->{PingCount} = 0;
1016 $irc_clients{$fh} = $c;
1017 $fh->push_read(line => sub { irc_line($c, @_) });
1019 irc_server_notice $c, "Waiting for RTM connection" if not $connected;
1021 chmod 0600, $config{unix_socket} if $config{unix_socket};
1025 ########################################################################
1027 ########################################################################
1032 my %rtm_apicall_handles;
1033 my $rtm_cooldown_timer;
1042 my ($method, $args, $cb) = @_;
1045 print "RTM APICALL $method ", Dumper($args) if $config{debug_dump};
1047 $args->{token} = $config{slack_token};
1049 foreach my $k (keys %$args) {
1050 my $ek = uri_encode($k);
1051 my $ev = uri_encode($args->{$k});
1053 push @encode, "$ek=$ev";
1057 $x = http_post "https://slack.com/api/$method", join('&', @encode),
1059 "Content-Type", "application/x-www-form-urlencoded"
1061 my ($body, $hdr) = @_;
1062 delete $rtm_apicall_handles{$x};
1064 unless ($hdr->{Status} =~ /^2/) {
1065 irc_broadcast_notice
1066 "API HTTP error: $method: $hdr->{Status} $hdr->{Reason}";
1067 $cb->(undef) if defined($cb);
1071 my $data = decode_json $body;
1073 print "RTM REPLY $method ", Dumper($data) if $config{debug_dump};
1075 unless ($data->{ok}) {
1076 irc_broadcast_notice "API error: $data->{error}";
1077 $cb->(undef) if defined($cb);
1081 $cb->($data) if defined($cb);
1084 $rtm_apicall_handles{$x} = 1;
1090 $frame->{id} = $rtm_msg_id++;
1091 print "RTM SEND: ", Dumper($frame) if $config{debug_dump};
1092 $rtm_con->send(encode_json $frame);
1095 sub rtm_update_join {
1096 my ($uid, $chid) = @_;
1097 my $chan = $channels{$chid};
1098 my $user = $users{$uid};
1100 if (!$chan->{Members}->{$uid}) {
1101 $chan->{Members}->{$uid} = 1;
1102 $user->{Channels}->{$chid} = 1;
1109 sub rtm_update_part {
1110 my ($uid, $chid) = @_;
1111 my $chan = $channels{$chid};
1112 my $user = $users{$uid};
1114 if ($chan->{Members}->{$uid}) {
1115 delete $channels{$chid}->{Members}->{$uid};
1116 delete $users{$uid}->{Channels}->{$chid};
1123 sub rtm_update_user {
1127 if (exists $users{$c->{id}}) {
1128 $user = $users{$c->{id}};
1129 my $oldname = $user->{Name};
1130 delete $users_by_name{irc_lcase($oldname)};
1131 my $newname = irc_pick_name($c->{name}, \%users_by_name);
1133 $user->{Realname} = $c->{real_name} // $c->{name};
1135 irc_broadcast_nick $c->{id}, $newname
1136 if $oldname ne $newname;
1138 $user->{Name} = $newname;
1139 $user->{Presence} = $c->{presence} // 'active';
1140 $users_by_name{$newname} = $user;
1142 my $name = irc_pick_name($c->{name}, \%users_by_name);
1147 Realname => $c->{real_name} // $c->{name},
1149 Presence => $c->{presence} // 'active'
1152 $users{$c->{id}} = $user;
1153 $users_by_name{$name} = $user;
1156 $user->{Realname} = "" unless defined($user->{Realname});
1159 sub rtm_record_unknown_uid {
1162 unless (exists $users{$uid}) {
1164 my $name = irc_pick_name($uid, \%users_by_name);
1175 $users_by_name{irc_lcase($name)} = $u;
1177 rtm_apicall "users.info", { user => $uid }, sub {
1180 rtm_update_user $data->{user} if defined $data;
1185 sub rtm_update_channel {
1186 my ($type, $c) = @_;
1189 rtm_apicall "conversations.members", { channel => $id }, sub {
1194 my $name = $c->{name};
1196 $c->{members} = $data->{'members'};
1198 $name = "+$name" if $type eq "G";
1200 # Cross-reference users/channels
1201 foreach my $u (@{$c->{members}}) {
1202 rtm_record_unknown_uid $u;
1203 # Filter ourselves out of the membership list if this is a
1204 # closed group chat.
1205 next if $type eq 'G' && $u eq $self_id && !$c->{is_open};
1207 $users{$u}->{Channels}->{$id} = 1;
1210 if (exists $channels{$id}) {
1211 my $chan = $channels{$id};
1212 $chan->{Members} = $mhash;
1213 $chan->{Topic} = $c->{topic}->{value};
1214 $chan->{Type} = $type;
1216 my $name = irc_pick_name($name, \%channels_by_name);
1222 Topic => $c->{topic}->{value}
1225 $channels{$c->{id}} = $chan;
1226 $channels_by_name{irc_lcase($name)} = $chan;
1231 sub rtm_delete_channel {
1233 my $chan = $channels{$chid};
1234 return unless defined $chan;
1236 foreach ($chan->{Members}) {
1237 my $user = $users{$_};
1239 delete $user->{Channels}->{$chid};
1242 delete $channels_by_name{irc_lcase($chan->{Name})};
1243 delete $channels{$chid};
1246 sub rtm_mark_channel {
1247 my ($chid, $ts) = @_;
1249 $rtm_mark_queue{$chid} = $ts;
1251 unless (defined $rtm_mark_timer) {
1252 $rtm_mark_timer = AnyEvent->timer(after => 5, cb => sub {
1253 for my $chid (keys %rtm_mark_queue ) {
1254 rtm_apicall "conversations.mark", {
1256 ts => $rtm_mark_queue{$chid}
1259 %rtm_mark_queue = ();
1260 undef $rtm_mark_timer;
1266 "presence_change" => sub {
1268 my $user = $users{$msg->{user}};
1270 if (defined $user) {
1271 my $old = $user->{Presence};
1272 $user->{Presence} = $msg->{presence} if defined $user;
1273 irc_broadcast_away if
1274 $msg->{user} eq $self_id and $old ne $msg->{presence};
1277 "manual_presence_change" => sub {
1279 my $user = $users{$self_id};
1280 my $old = $user->{Presence};
1282 $user->{Presence} = $msg->{presence};
1283 irc_broadcast_away if $old ne $msg->{presence};
1287 rtm_record_unknown_uid $msg->{user};
1289 my $u = $users{$msg->{user}};
1290 $u->{DMId} = $msg->{channel};
1291 $users_by_dmid{$msg->{channel}} = $u;
1293 foreach my $msg (@{$u->{TxQueue}}) {
1294 rtm_send { type => "message",
1295 channel => $u->{DMId}, text => $msg };
1302 my $u = $users_by_dmid{$msg->{channel}};
1303 return unless defined($u);
1306 delete $users_by_dmid{$msg->{channel}};
1308 "group_joined" => sub {
1311 rtm_update_channel "G", $msg->{channel};
1312 irc_broadcast_join $self_id, $msg->{channel}->{id};
1314 "group_left" => sub {
1317 irc_broadcast_part $self_id, $msg->{channel}
1318 if rtm_update_part $self_id, $msg->{channel};
1320 "group_archive" => sub {
1323 irc_broadcast_part $self_id, $msg->{channel}
1324 if rtm_update_part $self_id, $msg->{channel};
1325 rtm_delete_channel $msg->{channel};
1327 "channel_joined" => sub {
1330 rtm_update_channel "C", $msg->{channel};
1331 irc_broadcast_join $self_id, $msg->{channel}->{id};
1333 "channel_left" => sub {
1336 irc_broadcast_part $self_id, $msg->{channel}
1337 if rtm_update_part $self_id, $msg->{channel};
1339 "channel_archive" => sub {
1342 irc_broadcast_part $self_id, $msg->{channel}
1343 if rtm_update_part $self_id, $msg->{channel};
1344 rtm_delete_channel $msg->{channel};
1346 "member_joined_channel" => sub {
1349 rtm_record_unknown_uid $msg->{user};
1350 irc_broadcast_join $msg->{user}, $msg->{channel}
1351 if rtm_update_join($msg->{user}, $msg->{channel});
1353 "member_left_channel" => sub {
1356 irc_broadcast_part $msg->{user}, $msg->{channel}
1357 if rtm_update_part($msg->{user}, $msg->{channel});
1360 $rtm_ping_count = 0;
1364 my $chan = $channels{$msg->{channel}};
1365 my $subtype = $msg->{subtype} || "";
1366 my $uid = $msg->{user} || $msg->{comment}->{user} || $msg->{bot_id};
1367 my $text = $msg->{text} // '';
1369 if (defined($msg->{attachments})) {
1370 my $attext = join '\n', map {
1372 . " " . ($_->{text} or "")
1373 . " " . ($_->{title_link} or "") } @{$msg->{attachments}};
1374 $text .= "\n" unless length($text);
1378 if (defined($chan)) {
1379 if ($subtype eq "channel_topic" or $subtype eq "group_topic") {
1380 $chan->{Topic} = $msg->{topic};
1381 irc_topic_change $uid, $chan->{Id};
1383 irc_chanmsg $uid, $msg->{subtype}, $chan->{Id}, $text;
1385 rtm_mark_channel $chan->{Id}, $msg->{ts};
1387 irc_privmsg $uid, $msg->{subtype}, $text;
1390 if ($subtype eq "file_share") {
1391 my $fid = $msg->{file}->{id};
1392 rtm_apicall "files.info", { file => $fid }, sub {
1394 return unless defined $data;
1396 my $body = $data->{content};
1397 return unless length($body) <= 65536;
1399 if (defined $chan) {
1400 irc_chanmsg $uid, ">$fid", $chan->{Id}, $body;
1402 irc_privmsg $uid, ">$fid", $body;
1409 sub rtm_send_to_user {
1410 my ($id, $msg) = @_;
1411 my $u = $users{$id};
1413 if (defined($u->{DMId}) && length($u->{DMId})) {
1414 rtm_send { type => "message",
1415 channel => $u->{DMId}, text => $msg };
1419 push @{$u->{TxQueue}}, $msg;
1421 if (!defined($u->{DMId})) {
1422 rtm_apicall "im.open", { user => $u->{Id} }, sub {
1424 unless (defined $result) {
1426 foreach my $m (@{$u->{TxQueue}}) {
1427 irc_broadcast_notice "Failed to send to $u->{Name}: $m";
1440 return if defined($rtm_cooldown_timer);
1441 print "Waiting before reinitiating RTM\n";
1442 $rtm_cooldown_timer = AnyEvent->timer(after => 5, cb => sub {
1443 undef $rtm_cooldown_timer;
1450 return unless defined($rtm_con);
1452 irc_broadcast_notice $msg;
1457 %channels_by_name = ();
1459 %users_by_name = ();
1460 %users_by_dmid = ();
1462 %rtm_apicall_handles = (); # cancel outstanding requests
1463 %rtm_mark_queue = ();
1464 undef $rtm_mark_timer;
1465 undef $rtm_ping_timer;
1475 if (++$rtm_ping_count >= 2) {
1476 rtm_destroy "RTM ping timeout";
1480 rtm_send { type => "ping" };
1481 $rtm_ping_timer = AnyEvent->timer(after => 60, cb => \&rtm_ping);
1487 return if defined($rtm_client);
1488 $rtm_client = AnyEvent::WebSocket::Client->new;
1490 print "WSS URL: $url\n" if $config{debug_dump};
1491 $rtm_client->connect($url)->cb(sub {
1492 $rtm_con = eval { shift->recv; };
1494 irc_broadcast_notice "WSS connection failed: $@\n";
1499 print "WSS connected\n";
1501 $rtm_ping_count = 0;
1503 irc_check_welcome_all;
1505 $rtm_ping_timer = AnyEvent->timer(after => 60, cb => \&rtm_ping);
1507 $rtm_con->on(each_message => sub {
1510 my $msg = decode_json shift->{body};
1512 print "RTM RECV: ", Dumper($msg) if $config{debug_dump};
1513 irc_broadcast_notice "RTM error: $msg->{error}->{msg}"
1516 if (defined $msg->{type}) {
1517 my $handler = $rtm_command{$msg->{type}};
1518 $handler->($msg) if defined($handler);
1521 print "Error in message handler: $@" if $@;
1524 $rtm_con->on(finish => sub {
1528 if (defined $con->close_error) {
1529 rtm_destroy "RTM connection error: $con->close_error";
1530 } elsif (defined $con->close_reason) {
1531 rtm_destroy "RTM connection closed: $con->close_reason";
1533 rtm_destroy "RTM connection finished";
1536 print "Error in finish handler: $@" if $@;
1542 print "Requesting RTM connection\n";
1543 rtm_apicall "rtm.start", {}, sub {
1546 unless (defined($data)) {
1551 $self_id = $data->{self}->{id};
1553 foreach my $c (@{$data->{users}}) {
1557 foreach my $c (@{$data->{ims}}) {
1558 my $u = $users{$c->{user}};
1560 $u->{DMId} = $c->{id};
1561 $users_by_dmid{$c->{id}} = $u;
1564 foreach my $c (@{$data->{channels}}) {
1565 rtm_update_channel "C", $c unless $c->{is_archived};
1568 foreach my $c (@{$data->{bots}}) {
1573 foreach my $c (@{$data->{groups}}) {
1574 rtm_update_channel "G", $c unless $c->{is_archived};
1577 rtm_start_ws $data->{url};
1581 ########################################################################
1583 ########################################################################
1585 my $cfgfile = shift || die "You must specify a config file";
1586 open(my $cfg, $cfgfile) || die "Can't open $cfgfile";
1589 $config{$1} = $2 if /^([-_0-9a-zA-Z]+)=(.*)$/;
1595 AnyEvent->condvar->recv;