• Viernes 29 de Marzo de 2024, 05:44

Autor Tema:  programa para enviar SMS  (Leído 2618 veces)

keko

  • Nuevo Miembro
  • *
  • Mensajes: 9
    • Ver Perfil
programa para enviar SMS
« en: Domingo 9 de Febrero de 2003, 12:56 »
0
encontre este programa en perl para mandar SMS alguien m dice como funciona?
quiero hacer una pagina web para q me mande los resultados x movil en vez de x
email como se hace?

#!/usr/bin/perl
#     esms, envío de mensajes a móviles de España
#       http://esms.sourceforge.net
#     Copyright (C) 2001 José Juan Zapater Vera batsman.geo@yahoo.com
#         This program is free software; you can redistribute it and/or
#     modify it under the terms of the GNU General Public License as
#     published by the Free Software Foundation; either version 2 of the
#     License, or (at your option) any later version.
#
#         This program is distributed in the hope that it will be
#     useful, but WITHOUT ANY WARRANTY; without even the implied
#     warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#     See the GNU General Public License for more details.
#
#         You should have received a copy of the GNU General Public
#     License along with this program; if not, write to the Free
#     Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#   ChangeLog (casi a estrenar:)
#      2000/2001   Mauricio Julio Fernández Pradier
#            esms hasta versión 0.9.0
#      01/07/2001   0.9.0a
#            José Juan Zapater Vera
#            limpieza del código, corrección para
#            adaptarse a los cambios del servidor de
#            Navegalia
#      06/07/2001   0.9.0
#            Mauricio Julio Fernández Pradier
#            cambios para que funcione con los
#            módulos de Potato, pequeñas
#            modificaciones
#      30/07/2001   0.9.1
#            Incorporación del servidor de mensajes de
#            Movistar.
#            Creada estructura para multiples servidores
#            de forma cómoda.
#            Eliminado el parámetro de columnas porque
#            está derivado del servidor.

use CGI;
use Text::Wrap qw(wrap $columns);
use LWP::UserAgent;
use HTTP::Cookies;
use HTTP::Request::Common qw(POST GET);
use HTML::TreeBuilder;
use IO::Socket;

use strict;

# Definición de los plugins (servidores de mensajes SMS)
# NombreCorto, Descripción, Nº de columnas, Función
my @plugs = (    [ "navegalia", "Servidor de Airtel", 130, &enviar_mensaje_navegalia, ],
      [ "movistar", "Servidor de Movistar", 160-17,  &enviar_mensaje_movistar, ]
      );
# Servidor por defecto
my $plug = 0;

my $debug = 1;
my $nreintentos = 5; # debería haber un parámetro en la línea de comandos
my $errorconexion = 0; # puesto a uno si el servidor está hundido

sub espera
{
    my $tiempo= pop @_;
    print "Esperando $tiempo segundo(s)...n" if ($debug);
    select(undef,undef,undef,$tiempo);
    # granularidad menor que un segundo
}

sub pretty_print()
{
 my $mensaje = pop @_;
 print
 "-------------------------------------------------------------------------n" .
 "$mensajen" .
 "-------------------------------------------------------------------------n";
}


sub obtener_telefono
{
  my $alias = pop @_;
  my $fichero;
  $fichero = $ENV{"HOME"} . "/.esmsalias";
  print "Abriendo fichero de alias $fichero.n";
  print "Buscando teléfono de $alias.n";
  open(INPUT, $fichero);
  while (<INPUT>) {
   chop($_);
        ##   print "Leída línea $_.n";
     if ( /$alias/ ) {
      s/^$alias //g;
      s/ //g;
      s/t//g;
      close(INPUT);
      return $_;
   }
  }
  close(INPUT);
  return 0;
}


sub enviar_mensaje_navegalia
{
 my ($linea, $telefono, $repeat) = @_;
 my $ua = new LWP::UserAgent;
 $ua->agent("Mozilla/4.75 [en] (X11; U; Linux 2.4.5 itanium; Nav)");
 
 my $req = GET 'http://212.73.32.207/html/texto.htm', [ tNumber=>$telefono, nAddress=>"ttt@ttt.es" ];
 $req->header ( Referer =>
  "http://212.73.32.207/html/c_01.htm");
 my $res=$ua->request($req);
 
 unless($res->is_success || $errorconexion) {
   print "Error en la petición HTTP.n";
   print "El servidor no funciona correctamente en este momento.n";
   print "Inténtelo más tarde o comuníqueselo a los autores de esms.n";
   $errorconexion = 1;
    return 1;
 }
 if($res->is_success) {
    $errorconexion = 0;
 } else {
   return 1;
 }
 
 my $tree = HTML::TreeBuilder->new();
 $tree->ignore_text(1);
 $tree->parse($res->content);
 
 my $form = $tree->find_by_attribute('name','envio_sms');
 my $action=$form->attr_get_i('action');
 my $value1=$form->find_by_attribute('name','estado1')->attr_get_i('value');
 my $value2=$form->find_by_attribute('name','estado2')->attr_get_i('value');

 #print "Usando action=$action, estado1=$value1, estado2=$value2.n" if($debug);

 $req= POST $action, [ estado1 => $value1, estado2 => $value2,
    telefonoDestino1 => $telefono, codigoLookFeel => 1, tNumber => "", nAddress => "", texto => $linea];
 $req->header ( Referer => "http://212.73.32.207/html/texto.htm?$telefono");

 &espera(($repeat-1)*2+0.1); #Tengo que hacer pausa que si no no cuela

 $res=$ua->request($req);
 
 # elimina árbol HTML, el reference counting falla
 #$tree->destroy;
 # aunque está en la documentación, no está en el paquete para potato
 # ¿¿??

 # depuración a lo bestia
 # print $res->content if ($debug);
 
 if ($res->content =~ /no se está procesando correctamente/) {
     print ( "Error al enviar el mensaje:n" );
     &pretty_print($linea);
     return 1;
 }
 else {
     print "Mensaje enviado correctamenten" if ($debug);
     return 0;
 }
}

sub enviar_mensaje_movistar
{
 my ($linea, $telefono, $repeat) = @_;
 my $ua = new LWP::UserAgent;
 $ua->agent("Mozilla/4.75 [en] (X11; U; Linux 2.4.5 itanium; Nav)");

 # Obtenemos cookies

 my $cookie_jar = HTTP::Cookies->new;

 my $req = POST 'http://www.correo.movistar.net/enviar_mensajes.asp';
 my $res = $ua->request($req);
 $cookie_jar->extract_cookies($res);
 
 $req= POST 'http://www.correo.movistar.net/confirmacion_envio.asp', [ confirmacion => 0,
    nocache => "7%2F24%2F01+5%3A53%3A55+PM",
    telefono => $telefono, email => "nobody@nobody.com", mensaje_texto => $linea];
 $req->header ( Referer => "http://www.correo.movistar.net/enviar_mensajes.asp");
 $cookie_jar->add_cookie_header($req);
 
 my $res=$ua->request($req);
 
 # depuración a lo bestia
 # print $res->content if ($debug);
 
 if (!($res->content =~ /enviado con éxito/)) {
     print ( "Error al enviar el mensaje:n" );
     &pretty_print($linea);
     return 1;
 }
 else {
     print "Mensaje enviado correctamenten" if ($debug);
     return 0;
 }
}

sub enviar_mensaje{
 my ($linea, $telefono, $repeat) = @_;
 print "- Servidor $plugs[$plug][0] -n";
 my $func = $plugs[$plug][3];
 &$func($linea,$telefono,$repeat);
}

sub help{
   print "esms 0.9.1, Copyright © 2001 José Juan Zapater Vera batsman.geo@yahoo.comnn";
   print "esms comes with ABSOLUTELY NO WARRANTY. This is free software,n";
   print "and you are welcome to redistribute it under certain conditions.n";
   print "n";
   print "Más información en http://esms.sourceforge.net nn";
   print "Uso: esms <telefono> [/px]n";
   for(my $n=1;$n<=scalar(@plugs);$n++){
      print "/p",$plugs[$n-1][0]," ",$plugs[$n-1][1],"n";
   }
   print "nEjemplo:n";
   print " fortune -s | esms 123456789 /pmovistarn";
   print " uname -a | esms Linus n";
   print "nEste último buscará 'Linus' en el fichero de aliasn";
   print   "tt" . $ENV{"HOME"} . "/.esmsaliasn";
   print "Ejemplo de .esmsalias:n";
   print "yo      123456789n";
   print "Linus   1111111111n";
   exit(0);
}

if ($ARGV[0] eq ""){
   help();
}
my $telefono = $ARGV[0];
my $name = $telefono;
if ( $telefono !~ /^[0-9]+/ ) {
   $telefono = &obtener_telefono($telefono);
}
print "Teléfono obtenido: $telefono.n";
if ($telefono == 0)
{
   print "No se pudo encontrar el teléfono asociado a $name.n";
   exit(1);
}

if ($ARGV[1] =~ /^/p/ ){
   $plug=-1;
   for(my $n=1;$n<=scalar(@plugs);$n++){
      if ($plugs[$n-1][0] eq substr($ARGV[1],2)){
         $plug=$n-1;
      }
   }
   if ($plug==-1) {
      &help;
   }
}

$columns=$plugs[$plug][2];
my @in = <STDIN>;
my $mensaje = join ('', @in);

$mensaje =~ s/n/©/g;
$mensaje =~ s/t/ /g;
my $linea = wrap ("","",$mensaje);
my @lineas = split(/n/,$linea);
my $numlineas = @lineas;
$mensaje =~ s/©/n/g;
$| = 1; ## turn auto-flush on

print "Envío de mensaje a móviln";
print "Teléfono: $telefonon";
print "Mensaje:n";
&pretty_print($mensaje);

print "El mensaje ha sido fragmentado en $numlineas paquetes.n"
    if ($numlineas > 1);
print "El mensaje no ha sido fragmentado.n"
    if ($numlineas == 1);
my $j=1;
for (my $i=1; ($i<=$numlineas) && ($j<=$nreintentos); $i++){
    $lineas[$i-1] =~ s/©/n/g;
    $j=1;
    while ($j<=$nreintentos && &enviar_mensaje("$lineas[$i-1]n$i/$numlineas MFP", $telefono, $j )!=0){
   $j++;
    }
}
if ($j<=$nreintentos){
   exit(0); # Sin errores
}
else{
   exit(1); # Con errores
}