2008/12/27

Coding Jabber, the first pass ...

My current obsessions are Jabber and Twitter, finding ways to use them that work with what I'm doing. I've made a program that works a bit like mail on a Unix command line. You might list a directory and mail it to yourself like this: ls | mail yourself@yourserver.edu. This will work about the same way, except I build in a default target, so you can ls | jabber.pl as well as ls | jabber.pl yourself@yourjabberserver.edu . I have it set up so I can also do jabber.pl yourself@yourjabberserver.edu Insert message here .

My next goal is to add presence, which I regard as the cool thing about Jabber.


#!/usr/bin/perl

# ========= ========= ========= ========= ========= =========
# jabber.pl
#
# AUTHOR - Dave Jacoby
#
# Copyright (c) 2008. David Jacoby.
#
# This program is free software; you can redistribute it
# and/or modify it under the same terms as Perl itself.
#
# See http://www.perl.com/perl/misc/Artistic.html
#
# ---------
use 5.010 ;
use strict ;
use warnings ;
use Carp ;
use Net::XMPP ;

my $verbose = 0 ;

if ( $ENV{ PATH } eq '/usr/bin:/bin' ) {
#AS CRONTAB
$verbose = 0 ;
}
elsif ( defined $ENV{ EDITOR } ) {
#AS COMMANDLINE
$verbose = 1 ;
}
elsif ( !defined $ENV{ EDITOR } ) {
#could almost say 'else'
exit 0 ;
}

# connection vars
my $hostname = 'talk.google.com' ;
my $port = 5222 ;
my $componentname = 'gmail.com' ;
my $connectiontype = 'tcpip' ;
my $tls = 1 ;

# user vars
my $username = 'xxx' ;
my $password = 'xxx' ;
my $resource = 'Test' ;

# message
my $addr = '' ;
my @field ;

my $arg = shift @ARGV ;
$arg =~ m{([A-Za-z0-9_.+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})}mix ;
$addr = $1 ;

if ( $addr eq '' ) {
push @field, 'xxxx@gmail.com' ;
unshift @ARGV, $arg ;
}
else {
push @field, $addr ;
}

my $args = join ' ', @ARGV ;
if ( length $args == 0 ) {
while ( ) {
$args .= $_ ;
}
}
if ( length $args == 0 ) { $args = 'blank' ; }
if ( length $args > 139 ) { $args = substr $args, 0, 139 ; }

my $Connection = new Net::XMPP::Client() ;

# Connect to talk.google.com
my $status = $Connection->Connect( hostname => $hostname,
port => $port,
componentname => $componentname,
connectiontype => $connectiontype,
tls => $tls ) ;
if ( !( defined( $status ) ) ) {
$verbose and say 'ERROR: XMPP connection failed.' ;
$verbose and say $! ;
exit( 0 ) ;
}

# Change hostname
my $sid = $Connection->{ SESSION }->{ id } ;
$Connection->{ STREAM }->{ SIDS }->{ $sid }->{ hostname } = $componentname ;

# Authenticate
my @result = $Connection->AuthSend( username => $username,
password => $password,
resource => $resource ) ;

if ( $result[ 0 ] ne "ok" ) {
print "ERROR: Authorization failed: $result[0] - $result[1]\n" ;
exit( 0 ) ;
}

# Send messages
for my $address ( @field ) {
$Connection->MessageSend( to => $address,
resource => $resource,
subject => "Notification",
type => "chat",
body => $args ) ;

$verbose and say 'TO: ' . $address ;
$verbose and say $args ;
}

$verbose and say 'end' ;
exit ;
Post a Comment