source: lib/BarnOwl/Module/Twitter.pm @ 51a7fc5

release-1.10release-1.7release-1.8release-1.9
Last change on this file since 51a7fc5 was 51a7fc5, checked in by Nelson Elhage <nelhage@mit.edu>, 15 years ago
Set the timeout on Net::Twitter's LWP::UserAgent to 1s.
  • Property mode set to 100644
File size: 5.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
37# Don't redefine variables if they already exist
38# This is a workaround for http://barnowl.mit.edu/trac/ticket/44
39# Which was fixed in svn r819
40if((BarnOwl::getvar('twitter:class')||'') eq '') {
41    my $desc = <<'END_DESC';
42BarnOwl::Module::Twitter will watch for authentic zephyrs to
43-c $twitter:class -i $twitter:instance -O $twitter:opcode
44from your sender and mirror them to Twitter.
45
46A value of '*' in any of these fields acts a wildcard, accepting
47messages with any value of that field.
48END_DESC
49    BarnOwl::new_variable_string('twitter:class',
50                               {
51                                   default => $class,
52                                   summary => 'Class to watch for Twitter messages',
53                                   description => $desc
54                                  });
55    BarnOwl::new_variable_string('twitter:instance',
56                               {
57                                   default => $instance,
58                                   summary => 'Instance on twitter:class to watch for Twitter messages.',
59                                   description => $desc
60                                  });
61    BarnOwl::new_variable_string('twitter:opcode',
62                               {
63                                   default => $opcode,
64                                   summary => 'Opcode for zephyrs that will be sent as twitter updates',
65                                   description => $desc
66                                  });
67}
68
69my $conffile = BarnOwl::get_config_dir() . "/twitter";
70open(my $fh, "<", "$conffile") || fail("Unable to read $conffile");
71my $cfg = do {local $/; <$fh>};
72close($fh);
73eval {
74    $cfg = from_json($cfg);
75};
76if($@) {
77    fail("Unable to parse ~/.owl/twitter: $@");
78}
79
80$twitter  = Net::Twitter->new(username   => $cfg->{user} || $user,
81                              password   => $cfg->{password},
82                              source => 'barnowl');
83
84eval {
85    $twitter->{ua}->timeout(1);
86};
87
88if(!defined($twitter->verify_credentials())) {
89    fail("Invalid twitter credentials");
90}
91
92sub match {
93    my $val = shift;
94    my $pat = shift;
95    return $pat eq "*" || ($val eq $pat);
96}
97
98sub handle_message {
99    my $m = shift;
100    ($class, $instance, $opcode) = map{BarnOwl::getvar("twitter:$_")} qw(class instance opcode);
101    if($m->sender eq $user
102       && match($m->class, $class)
103       && match($m->instance, $instance)
104       && match($m->opcode, $opcode)
105       && $m->auth eq 'YES') {
106        twitter($m->body);
107    }
108}
109
110my $last_poll = 0;
111my $last_id   = undef;
112unless(defined($last_id)) {
113    $last_id = $twitter->friends_timeline({count => 1})->[0]{id};
114}
115
116sub poll_messages {
117    return unless ( time - $last_poll ) >= 45;
118    $last_poll = time;
119    my $timeline = $twitter->friends_timeline( { since_id => $last_id } );
120    unless(defined($timeline)) {
121        BarnOwl::error("Twitter returned error ... rate-limited?");
122        # Sleep for 15 minutes
123        $last_poll = time + 60*15;
124        return;
125    };
126    if ( scalar @$timeline ) {
127        for my $tweet ( reverse @$timeline ) {
128            if ( $tweet->{id} <= $last_id ) {
129                next;
130            }
131            my $msg = BarnOwl::Message->new(
132                type      => 'Twitter',
133                sender    => $tweet->{user}{screen_name},
134                recipient => $cfg->{user} || $user,
135                direction => 'in',
136                source    => decode_entities($tweet->{source}),
137                location  => decode_entities($tweet->{user}{location}) || "",
138                body      => decode_entities($tweet->{text})
139               );
140            BarnOwl::queue_message($msg);
141        }
142        $last_id = $timeline->[0]{id};
143    } else {
144        # BarnOwl::message("No new tweets...");
145    }
146}
147
148sub twitter {
149    my $msg = shift;
150    if(defined $twitter) {
151        $twitter->update($msg);
152    }
153}
154
155BarnOwl::new_command(twitter => \&cmd_twitter, {
156    summary     => 'Update Twitter from BarnOwl',
157    usage       => 'twitter [message]',
158    description => 'Update Twitter. If MESSAGE is provided, use it as your status.'
159    . "\nOtherwise, prompt for a status message to use."
160   });
161
162sub cmd_twitter {
163    my $cmd = shift;
164    if(@_) {
165        my $status = join(" ", @_);
166        twitter($status);
167    } else {
168      BarnOwl::start_edit_win('What are you doing?', \&twitter);
169    }
170}
171
172eval {
173    $BarnOwl::Hooks::receiveMessage->add("BarnOwl::Module::Twitter::handle_message");
174    $BarnOwl::Hooks::mainLoop->add("BarnOwl::Module::Twitter::poll_messages");
175};
176if($@) {
177    $BarnOwl::Hooks::receiveMessage->add(\&handle_message);
178    $BarnOwl::Hooks::mainLoop->add(\&poll_messages);
179}
180
181BarnOwl::filter('twitter type ^twitter$');
182
1831;
Note: See TracBrowser for help on using the repository browser.