Skip to content

Instantly share code, notes, and snippets.

@hiratara
Created October 2, 2009 14:32
Show Gist options
  • Select an option

  • Save hiratara/199793 to your computer and use it in GitHub Desktop.

Select an option

Save hiratara/199793 to your computer and use it in GitHub Desktop.
package MyCoro::IRC::Client;
use Moose;
use AnyEvent::IRC::Client;
use Coro ();
use Coro::AnyEvent ();
has ae_irc => (
isa => 'AnyEvent::IRC::Client',
is => 'ro',
default => sub { AnyEvent::IRC::Client->new },
);
has events => (
isa => 'ArrayRef',
is => 'ro',
default => sub { [] },
);
has cur_coro => (
isa => 'Maybe[Coro]',
is => 'rw',
);
sub reg_watcher {
my $self = shift;
my ( $watcher ) = @_;
$self->ae_irc->reg_cb(
$watcher => sub {
push @{ $self->events }, {event => $watcher, args => [ @_ ]};
$self->cur_coro->ready if $self->cur_coro;
}
);
}
sub next {
my $self = shift;
unless( @{ $self->events } ){
$self->cur_coro( $Coro::current );
Coro::schedule while ! @{ $self->events };
}
$self->cur_coro( undef );
return shift @{ $self->events };
}
__PACKAGE__->meta->make_immutable;
no Moose;
package MyCoro::Twitter::Stream;
use Moose;
use AnyEvent::Twitter::Stream;
use Coro ();
use Coro::AnyEvent ();
has args => (
isa => 'HashRef',
is => 'ro',
required => 1,
);
has stream => (
isa => 'AnyEvent::Twitter::Stream',
is => 'rw',
);
has tweets => (
isa => 'ArrayRef',
is => 'ro',
default => sub { [] },
);
has cur_coro => (
isa => 'Maybe[Coro]',
is => 'rw',
);
sub BUILDARGS {
return shift->SUPER::BUILDARGS( args => { @_ } );
}
sub BUILD {
my $self = shift;
my $stream = AnyEvent::Twitter::Stream->new(
%{ $self->args },
on_tweet => sub {
push @{ $self->tweets }, shift;
$self->cur_coro->ready if $self->cur_coro;
},
on_error => sub { die @_; },
on_eof => sub { exit; },
);
$self->stream( $stream );
}
sub next {
my $self = shift;
unless( @{ $self->tweets } ){
$self->cur_coro( $Coro::current );
Coro::schedule while ! @{ $self->tweets };
}
$self->cur_coro( undef );
return shift @{ $self->tweets };
}
__PACKAGE__->meta->make_immutable;
no Moose;
package main;
use strict;
use warnings;
use Coro;
use Data::Dumper;
use Encode;
use utf8;
my $channel = $ARGV[0];
my $c = MyCoro::IRC::Client->new;
$c->reg_watcher('connect');
$c->reg_watcher('registered');
$c->reg_watcher('publicmsg');
$c->ae_irc->connect(
"irc.nara.wide.ad.jp", 6663, { nick => 'hiratara_bot' }
);
$c->ae_irc->send_srv( "JOIN", $channel );
async{
while(my $ev = $c->next){
if( $ev->{event} eq 'publicmsg'){
$c->ae_irc->send_chan(
$channel, "NOTICE", $channel,
$ev->{args}[2]{params}[1]
);
}else{
warn $ev->{event};
};
}
};
my $twitter = MyCoro::Twitter::Stream->new(
username => $ARGV[1],
password => $ARGV[2],
method => 'filter',
track => '#food',
);
async{
while(my $tweet = $twitter->next){
$c->ae_irc->send_chan(
$channel, "NOTICE", $channel,
encode_utf8( "$tweet->{user}{screen_name}: $tweet->{text}" )
);
}
};
schedule;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment