source: lib/BarnOwl/Module/Twitter.pm @ c1e5316

release-1.10release-1.7release-1.8release-1.9
Last change on this file since c1e5316 was c1e5316, checked in by Nelson Elhage <nelhage@mit.edu>, 15 years ago
Display outgoing personal twitters
  • Property mode set to 100644
File size: 8.2 KB
Line 
1use warnings;
2use strict;
3
4=head1 NAME
5
6BarnOwl::Module::Twitter
7
8=head1 DESCRIPTION
9
10Post outgoing zephyrs from -c $USER -i status -O TWITTER to Twitter
11
12=cut
13
14package BarnOwl::Module::Twitter;
15
16use Net::Twitter;
17use JSON;
18
19use BarnOwl;
20use BarnOwl::Hooks;
21use BarnOwl::Message::Twitter;
22use HTML::Entities;
23
24my $twitter;
25my $user     = BarnOwl::zephyr_getsender();
26my ($class)  = ($user =~ /(^[^@]+)/);
27my $instance = "status";
28my $opcode   = "twitter";
29
30sub fail {
31    my $msg = shift;
32    undef $twitter;
33    BarnOwl::admin_message('Twitter Error', $msg);
34    die("Twitter Error: $msg\n");
35}
36
37my $desc = <<'END_DESC';
38BarnOwl::Module::Twitter will watch for authentic zephyrs to
39-c $twitter:class -i $twitter:instance -O $twitter:opcode
40from your sender and mirror them to Twitter.
41
42A value of '*' in any of these fields acts a wildcard, accepting
43messages with any value of that field.
44END_DESC
45BarnOwl::new_variable_string(
46    'twitter:class',
47    {
48        default     => $class,
49        summary     => 'Class to watch for Twitter messages',
50        description => $desc
51    }
52);
53BarnOwl::new_variable_string(
54    'twitter:instance',
55    {
56        default => $instance,
57        summary => 'Instance on twitter:class to watch for Twitter messages.',
58        description => $desc
59    }
60);
61BarnOwl::new_variable_string(
62    'twitter:opcode',
63    {
64        default => $opcode,
65        summary => 'Opcode for zephyrs that will be sent as twitter updates',
66        description => $desc
67    }
68);
69
70BarnOwl::new_variable_bool(
71    'twitter:poll',
72    {
73        default => 1,
74        summary => 'Poll Twitter for incoming messages',
75        description => "If set, will poll Twitter every minute for normal updates,\n"
76        . 'and every two minutes for direct message'
77     }
78 );
79
80my $conffile = BarnOwl::get_config_dir() . "/twitter";
81open(my $fh, "<", "$conffile") || fail("Unable to read $conffile");
82my $cfg = do {local $/; <$fh>};
83close($fh);
84eval {
85    $cfg = from_json($cfg);
86};
87if($@) {
88    fail("Unable to parse ~/.owl/twitter: $@");
89}
90
91$twitter  = Net::Twitter->new(username   => $cfg->{user} || $user,
92                              password   => $cfg->{password},
93                              source => 'barnowl');
94
95eval {
96    $twitter->{ua}->timeout(1);
97};
98
99if(!defined($twitter->verify_credentials())) {
100    fail("Invalid twitter credentials");
101}
102
103sub match {
104    my $val = shift;
105    my $pat = shift;
106    return $pat eq "*" || ($val eq $pat);
107}
108
109sub handle_message {
110    my $m = shift;
111    ($class, $instance, $opcode) = map{BarnOwl::getvar("twitter:$_")} qw(class instance opcode);
112    if($m->sender eq $user
113       && match($m->class, $class)
114       && match($m->instance, $instance)
115       && match($m->opcode, $opcode)
116       && $m->auth eq 'YES') {
117        twitter($m->body);
118    }
119}
120
121our $last_poll        = 0;
122our $last_direct_poll = 0;
123our $last_id          = undef;
124our $last_direct      = undef;
125
126unless(defined($last_id)) {
127    eval {
128        $last_id = $twitter->friends_timeline({count => 1})->[0]{id};
129    };
130}
131
132unless(defined($last_direct)) {
133    eval {
134        $last_direct = $twitter->direct_messages()->[0]{id};
135    };
136}
137
138sub poll_messages {
139    poll_twitter();
140    poll_direct();
141}
142
143sub twitter_error {
144    my $ratelimit = $twitter->rate_limit_status;
145    unless(defined($ratelimit)) {
146        # Twitter's just sucking, sleep for 5 minutes
147        $last_direct_poll = $last_poll = time + 60*5;
148        die("Twitter seems to be having problems.\n");
149    }
150    if($ratelimit->{remaining_hits} <= 0) {
151        $last_direct_poll = $last_poll = $ratelimit->{reset_time_in_seconds};
152        die("Twitter: ratelimited until " . $ratelimit->{reset_time} . "\n");
153    }
154}
155
156sub poll_twitter {
157    return unless ( time - $last_poll ) >= 60;
158    $last_poll = time;
159    return unless BarnOwl::getvar('twitter:poll') eq 'on';
160
161    my $timeline = $twitter->friends_timeline( { since_id => $last_id } );
162    unless(defined($timeline)) {
163        twitter_error();
164        return;
165    };
166    if ( scalar @$timeline ) {
167        for my $tweet ( reverse @$timeline ) {
168            if ( $tweet->{id} <= $last_id ) {
169                next;
170            }
171            my $msg = BarnOwl::Message->new(
172                type      => 'Twitter',
173                sender    => $tweet->{user}{screen_name},
174                recipient => $cfg->{user} || $user,
175                direction => 'in',
176                source    => decode_entities($tweet->{source}),
177                location  => decode_entities($tweet->{user}{location}||""),
178                body      => decode_entities($tweet->{text})
179               );
180            BarnOwl::queue_message($msg);
181        }
182        $last_id = $timeline->[0]{id};
183    } else {
184        # BarnOwl::message("No new tweets...");
185    }
186}
187
188sub poll_direct {
189    return unless ( time - $last_direct_poll) >= 120;
190    $last_direct_poll = time;
191    return unless BarnOwl::getvar('twitter:poll') eq 'on';
192
193    my $direct = $twitter->direct_messages( { since_id => $last_direct } );
194    unless(defined($direct)) {
195        twitter_error();
196        return;
197    };
198    if ( scalar @$direct ) {
199        for my $tweet ( reverse @$direct ) {
200            if ( $tweet->{id} <= $last_direct ) {
201                next;
202            }
203            my $msg = BarnOwl::Message->new(
204                type      => 'Twitter',
205                sender    => $tweet->{sender}{screen_name},
206                recipient => $cfg->{user} || $user,
207                direction => 'in',
208                location  => decode_entities($tweet->{sender}{location}||""),
209                body      => decode_entities($tweet->{text}),
210                isprivate => 'true'
211               );
212            BarnOwl::queue_message($msg);
213        }
214        $last_direct = $direct->[0]{id};
215    } else {
216        # BarnOwl::message("No new tweets...");
217    }
218}
219
220sub twitter {
221    my $msg = shift;
222    if($msg =~ m{\Ad\s+([^\s])+(.*)}sm) {
223        twitter_direct($1, $2);
224    } elsif(defined $twitter) {
225        $twitter->update($msg);
226    }
227}
228
229sub twitter_direct {
230    my $who = shift;
231    my $msg = shift;
232    if(defined $twitter) {
233        $twitter->new_direct_message({
234            user => $who,
235            text => $msg
236           });
237        if(BarnOwl::getvar("displayoutgoing") eq 'on') {
238            my $tweet = BarnOwl::Message->new(
239                type      => 'Twitter',
240                sender    => $cfg->{user} || $user,
241                recipient => $who, 
242                direction => 'out',
243                body      => $msg,
244                isprivate => 'true'
245               );
246            BarnOwl::queue_message($tweet);
247        }
248    }
249}
250
251sub twitter_atreply {
252    my $to  = shift;
253    my $msg = shift;
254    twitter("@".$to." ".$msg);
255}
256
257BarnOwl::new_command(twitter => \&cmd_twitter, {
258    summary     => 'Update Twitter from BarnOwl',
259    usage       => 'twitter [message]',
260    description => 'Update Twitter. If MESSAGE is provided, use it as your status.'
261    . "\nOtherwise, prompt for a status message to use."
262   });
263
264BarnOwl::new_command('twitter-direct' => \&cmd_twitter_direct, {
265    summary     => 'Send a Twitter direct message',
266    usage       => 'twitter-direct USER',
267    description => 'Send a Twitter Direct Message to USER'
268   });
269
270BarnOwl::new_command( 'twitter-atreply' => sub { cmd_twitter_atreply(@_); },
271    {
272    summary     => 'Send a Twitter @ message',
273    usage       => 'twitter-atreply USER',
274    description => 'Send a Twitter @reply Message to USER'
275    }
276);
277
278
279sub cmd_twitter {
280    my $cmd = shift;
281    if(@_) {
282        my $status = join(" ", @_);
283        twitter($status);
284    } else {
285      BarnOwl::start_edit_win('What are you doing?', \&twitter);
286    }
287}
288
289sub cmd_twitter_direct {
290    my $cmd = shift;
291    my $user = shift;
292    die("Usage: $cmd USER\n") unless $user;
293    BarnOwl::start_edit_win("$cmd $user", sub{twitter_direct($user, shift)});
294}
295
296sub cmd_twitter_atreply {
297    my $cmd  = shift;
298    my $user = shift;
299    BarnOwl::start_edit_win("Reply to \@" . $user, sub { twitter_atreply($user, shift) });
300}
301
302eval {
303    $BarnOwl::Hooks::receiveMessage->add("BarnOwl::Module::Twitter::handle_message");
304    $BarnOwl::Hooks::mainLoop->add("BarnOwl::Module::Twitter::poll_messages");
305};
306if($@) {
307    $BarnOwl::Hooks::receiveMessage->add(\&handle_message);
308    $BarnOwl::Hooks::mainLoop->add(\&poll_messages);
309}
310
311BarnOwl::filter('twitter type ^twitter$');
312
3131;
Note: See TracBrowser for help on using the repository browser.