Last active
September 18, 2017 14:33
-
-
Save kwakwaversal/ab420b29969969e370f6 to your computer and use it in GitHub Desktop.
IRC websocket #perl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use EV; | |
use AnyEvent::IRC::Client; | |
use Mojolicious::Lite; | |
app->config(hypnotoad => {listen => ['http://*:3000']}); | |
# Join #mojo on irc.perl.org | |
my $irc = AnyEvent::IRC::Client->new; | |
$irc->connect('172.16.0.34', 6667, {nick => "mojobot$$"}); | |
$irc->send_srv(JOIN => '#perl'); | |
get '/' => 'index'; | |
get '/events' => sub { | |
my $self = shift; | |
# Emit "msg" event for every new IRC message | |
$self->res->headers->content_type('text/event-stream'); | |
my $g = $irc->reg_cb(publicmsg => sub { | |
my $message = pop->{params}->[1]; | |
$self->write("event:msg\ndata: $message\n\n"); | |
}); | |
$self->on(finish => sub { undef $g }); | |
}; | |
app->start; | |
__DATA__ | |
@@ index.html.ep | |
<!doctype html><html> | |
<head><title>An IRC channel</title></head> | |
<body> | |
<script> | |
var events = new EventSource('<%= url_for 'events' %>'); | |
// Subscribe to "msg" event | |
events.addEventListener('msg', function(event) { | |
document.body.innerHTML += event.data + '<br/>'; | |
}, false); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment