Twitter フォロワー同期(リム専用)Bot Perl 解析編

自動でフォローされたらフォローし返すプログラムを書きたいけどNet::Twitterの使い方がわからなかったのでとりあえずフォロワー同期(リム専用)Botのソースをマニュアルを読みながら適当に解析してコメント打ちました。

マニュアル:Net::Twitter(英語)
参考にさせて頂いたソース:■[メモ]Twitterで自動フォロー削除

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/perl
use utf8;
use strict;
use warnings;
 
# モジュール使用宣言
use Array::Diff;
use Data::Dumper;
use Net::Twitter;
use YAML::Tiny;
use Encode;
use FindBin;
 
# 現在のパスから見て設定ファイルを読み込み
my $config = (YAML::Tiny->read($FindBin::Bin . '/config.yml'))->[0];
# OAuth認証
my $twitter = Net::Twitter->new(
     traits => ['API::REST', 'OAuth'],
     consumer_key => $config->{'consumer_key'},
     consumer_secret => $config->{'consumer_secret'}
);
$twitter->access_token($config->{'access_token'});
$twitter->access_token_secret($config->{'access_token_secret'});
# 認証失敗時の処理
die('Auth failed:'.$config->{'username'}) unless ( $twitter->authorized ) ;
 
# ユーザー名を含むユーザー情報を取得
my $cr = $twitter->verify_credentials;
my $own_id = $cr->{id};
 
my $nextc = -1; # paging default.
my @following_id_list; # outgo
 
# APIの仕様?から一度に100人までしか取得できないから0が返ってくるまでdoブロックをループ
do{
    # cursorは前回取得したフォローイングまでの番号が入っている
    my $following_list = $twitter->friends_ids({ id=>$own_id, cursor => $nextc });
    $nextc = $following_list->{next_cursor};
    # 配列からフォローイングのidを取得
    foreach my $id (@{ $following_list->{ids} }){
        push(@following_id_list, $id); # 後で比較するためにフォローイングを配列に保管
    }
}while($nextc!=0);
# 文字昇順でソート
@following_id_list = sort @following_id_list;
 
$nextc = -1;
my @followers_id_list; # income
do{
    # cursorは前回取得したフォロワーまでの番号が入っている
    my $followers_list = $twitter->followers_ids({ id=>$own_id, cursor => $nextc });  
    $nextc = $followers_list->{next_cursor};
    # 配列からフォロワーのidを取得
    foreach my $id (@{ $followers_list->{ids} }){
        push(@followers_id_list, $id); # 後で比較するためにフォロワーを配列に保管
    }
}while($nextc!=0);
# 文字昇順でソート
@followers_id_list = sort @followers_id_list;
 
# 差分を取得
my $diff = Array::Diff->diff(@following_id_list, @followers_id_list);
 
# リムった人をリム返し
foreach my $delid (@{ $diff->{deleted} }){
    $twitter->destroy_friend($delid);
}

だいたい構造がわかったのでちゃちゃっと書き足しましょうか^^

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(Spamcheck Enabled)

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)