twitter bot作成
twitterでbotを作ろうと決意。
以下のサイトを参考にbotを作りました。
Twitter ボットの作り方 Perl 編
#!/usr/bin/perl
use strict;
use warnings;
use FindBin;
use List::Util;
use Encode;
use YAML::Tiny;
use Net::Twitter;
use AnyEvent::Twitter::Stream;
use DBI;
use Data::Dumper;
my ($sth, $dbh);$dbh = DBI->connect("DBI:mysql:host=localhost;database=hoge", "username, "password");
$sth = $dbh->prepare("select twid from user");
$sth->execute();
my @following_ids;
while (my @val = $sth->fetchrow_array()) {
push @following_ids, $val[0];
}
my $config = (YAML::Tiny->read($FindBin::Bin . '/config.yml'))->[0];
my $twit = Net::Twitter->new(username => $config->{'username'}, password => $config->{'password'});
my $username = $config->{'username'};
my $password = $config->{'password'};
my $template = Encode::encode('utf8', $config->{'template'});
my $cv = AnyEvent->condvar;
my $listener = AnyEvent::Twitter::Stream->new(
username => $username,
password => $password,
method => "filter",
follow => join(",", @following_ids),
on_tweet => sub {
my $tweet = shift;
my $fromuser = $tweet->{user}{screen_name};
my $statusid = $tweet->{id};
my $text = Encode::encode('utf8', $tweet->{text});
my $reply = $template;
return if $fromuser eq $username;
$text =~ s/\s*\@${username}\s*//;
$reply = '@' . "${fromuser} ${reply}";
print "$reply\n";
$twit->update({status => $reply, in_reply_to_status_id => $statusid});
}
);
$cv->recv;