Skip to content

Instantly share code, notes, and snippets.

@xaicron
Created April 9, 2010 15:17
Show Gist options
  • Select an option

  • Save xaicron/361271 to your computer and use it in GitHub Desktop.

Select an option

Save xaicron/361271 to your computer and use it in GitHub Desktop.
#!perl
use strict;
use warnings;
use Encode qw/find_encoding encode_utf8 decode_utf8/;
use Term::Encoding qw(term_encoding);
use AnyEvent::Impl::Perl;
use AnyEvent;
use Coro;
use Coro::Handle;
my $user_id = shift || die "Usage: $0 user_id";
my $encoding = find_encoding term_encoding;
$| = 1;
my $in = unblock \*STDIN;
my $out = unblock \*STDOUT;
my $api;
my $is_read = +{};
main();
exit;
sub main {
init();
my $me = get_current_user();
my $chat_id = chat_open($user_id);
my $cv_sender = AE::cv;
my $w;
my $sender; $sender = unblock_sub {
$out->syswrite('MESSAGE: ');
chomp(my $msg = encode_utf8($encoding->decode($in->readline)));
send_message($chat_id, $msg);
$w = AE::timer 0, 0, $sender;
};
$w = AE::timer 0, 0, $sender;
my $cv_reader = AE::cv;
my $reader = AE::timer 0, 1, sub {
read_message($me, $chat_id);
};
$cv_reader->recv;
$cv_sender->recv;
}
sub init {
if ($^O eq 'linux' ) { _linux() }
elsif ($^O eq 'MSWin32') { _windows() }
}
sub get_current_user {
my $res = $api->("GET CURRENTUSERHANDLE");
$res =~ s/CURRENTUSERHANDLE //;
return $res;
}
sub chat_open {
my ($user_id) = @_;
my $res = $api->("CHAT CREATE $user_id");
return _get_chat_id($res);
}
sub send_message {
my ($chat_id, $msg) = @_;
my $res = $api->("CHATMESSAGE $chat_id $msg");
}
sub read_message {
my ($me, $chat_id) = @_;
my $res = $api->("GET CHAT $chat_id RECENTCHATMESSAGES");
my $messges = [];
for my $msg_id (_get_recent_ids($res)) {
next if $is_read->{$msg_id}++;
my $name = get_message_from($msg_id);
next if $name eq $me;
my $body = get_message_body($msg_id) || next;
print "$name: $body";
push @$messges, +{body => $body, name => $name};
}
}
sub get_message_from {
my $msg_id = shift;
my $res = $api->("GET MESSAGE $msg_id PARTNER_HANDLE");
my ($handle) = $res =~ /PARTNER_HANDLE (.*)/;
return $handle;
}
sub get_message_body {
my $msg_id = shift;
my $res = $api->("GET MESSAGE $msg_id BODY");
my ($body) = $res =~ /BODY (.*)/;
return $body;
}
sub _get_chat_id {
my $res = shift;
my ($id) = $res =~ /^CHAT (.*) STATUS \w+$/;
return $id;
}
sub _get_recent_ids {
my $res = shift;
my ($id) =$res =~ /RECENTCHATMESSAGES (.*)$/;
my @ids = split /,\s/, $id;
return @ids;
}
##
sub _linux {
require Net::DBus::Skype;
my $skype = Net::DBus::Skype->new;
$api = sub {
my $command = shift;
return $skype->raw_skype($command);
};
}
sub _windows {
require SkypeAPI;
my $skype = SkypeAPI->new;
$skype->attach;
$api = sub {
my $cmd = shift;
return $skype->send_command($skype->create_command({string => $cmd}));
};
}
__END__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment