FiveTech Support Forums

FiveWin / Harbour / xBase community
Board index FiveWin para Harbour/xHarbour Pruebas con WhatsApp
Posts: 44158
Joined: Thu Oct 06, 2005 05:47 PM
Pruebas con WhatsApp
Posted: Wed Apr 17, 2024 03:57 AM
Modesto Rocabado ha compartido con nosotros este código para enviar mensajes y ficheros usando WhatsApp.

Os agradecemos vuestras pruebas y feedback para afinarlo. Gracias!
Code (fw): Select all Collapse
FUNC SendToWhatsApp( cPhone, cMsg, aAttach )
LOCAL oShell, aFiles := {}, aOthers  := {}, lRet
 If (lRet := !Empty( cPhone ))
  If !Empty( aAttach )
   If( !HB_ISARRAY( aAttach ), aAttach := { aAttach }, )
   AEval( aAttach, {|cFile| If( HB_ISSTRING( cFile ) .AND. File( cFile ), AAdd( aFiles, cFile), AAdd( aOthers, cFile ) ) } )
  EndIf
  cMsg  := StrTran( cMsg, CRLF, "%0D%0A" )
  oShell := CreateObject( "WScript.Shell" )
  ShellExecute( 0, "Open", "whatsapp://send?phone="+cPhone+"&text="+cMsg)
  SysWait( 0.2 )
  If !Empty( aFiles )
   If FW_CopyToClipBoard( aFiles, 15 )
    SysWait( 2 )
    oShell:SendKeys( "^v" )
    SysWait( 1 )
   EndIf
  EndIf
  AEval( aOthers, <|u|
                      If FW_CopyToClipBoard( u, 2 ) .OR. FW_CopyToClipBoard( u )
                       SysWait( 1 )
                       oShell:SendKeys( "^v" )
                       SysWait( 1 )
                      EndIf
                      RETURN NIL
                  > )
   oShell:SendKeys("~")
 EndIf
RETURN lRet
regards, saludos

Antonio Linares
www.fivetechsoft.com
Posts: 3358
Joined: Fri Oct 07, 2005 08:20 PM
Re: Pruebas con WhatsApp
Posted: Wed Apr 17, 2024 04:42 AM
Maestro Antonio L.

Copie la función y la llamo con el siguiente código
Code (fw): Select all Collapse
   SendToWhatsApp( "7293320729", "Hola !",)

o con
   SendToWhatsApp( "+557293320729", "Hola !",)
En mi PC se abre WhatsApp pero no llega el mensaje aunque la función retorna .T. ¿qué le cambio?

Saludos
SOI, s.a. de c.v.
estbucarm@gmail.com
http://www.soisa.mex.tl/
http://sqlcmd.blogspot.com/
Tel. (722) 174 44 45
Carpe diem quam minimum credula postero
Posts: 105
Joined: Sat Jan 14, 2012 03:46 PM
Re: Pruebas con WhatsApp
Posted: Wed Apr 17, 2024 04:10 PM

Mi experiencia con el codigo facilitado

El numero de telefono al que enviar mensaje tiene que ser exactamente como aparece en la información de contacto, es decir, (+)codigo de país + telefono

Añadir SysWait( 1 ) antes del ultimo oShell:SendKeys("~")

Si WhatsApp está abierto en el escritorio, se envia el mensaje de forma automática

Si no está abierto, lanza el programa pero no envia nada, a veces se queda el texto del mensaje a enviar en espera de darle al botón de envío

Seria interesante poder comunicar en modo 'silencioso' sin abrir el programa

Existen varios whatsapp-CLI pero para Python y Go

Fivewinner desde 1.9, programador PHP y Javascript, PWA & HTML5 evangelista
Posts: 318
Joined: Fri Jan 14, 2022 08:37 AM
Re: Pruebas con WhatsApp
Posted: Wed Apr 17, 2024 04:52 PM

IMHO,

Este tipo de soluciones me pareciera a mi que no se mantienen en el tiempo y además están sujetas a demasiadas casuísticas pre

Asi que como mejor alguna solución "estable" python, a través del API con python o un ejecutable python que haga el trabajo, después de recibir unos parámetros (*)

(*) Estaría bien que tuviéramos un .exe python con distintas funcionalidades al que se le pasa como parámetro el nombre de un json y devuelve otro con el mismo nombre y _respuesta de sufijo

Mis 2 eurocents

Posts: 8515
Joined: Tue Dec 20, 2005 07:36 PM
Re: Pruebas con WhatsApp
Posted: Wed Apr 17, 2024 05:24 PM
Armando, no te falta el código de área?
Code (fw): Select all Collapse
   SendToWhatsApp( "+55(11)7293320729", "Hola !",) // +55 -> Brazil, (11) -> São Paulo? Cual ciudad en Brazil?

Regards, saludos.
João Santos - São Paulo - Brasil - Phone: +55(11)95150-7341
Posts: 44158
Joined: Thu Oct 06, 2005 05:47 PM
Re: Pruebas con WhatsApp
Posted: Wed Apr 17, 2024 06:08 PM
Usando python se puede hacer asi:

pip install pywhatkit

whatsapp.py
Code (fw): Select all Collapse
import pywhatkit as pw

# Número de teléfono (incluyendo código de país)
recipient = "+573123456789"

# Mensaje de texto
message = "Hola! Te envío este mensaje con Python."

# Lista de archivos adjuntos (opcionales)
attachments = [
    "/ruta/a/archivo1.pdf",
    "/ruta/a/archivo2.jpg"
]

# Enviar mensaje con o sin archivos adjuntos
if attachments:
    pw.send_whatsap_message(recipient, message, attachments=attachments)
else:
    pw.send_whatsap_message(recipient, message)
Para generar un EXE:
pyinstaller --onefile whatsapp.py
regards, saludos

Antonio Linares
www.fivetechsoft.com
Posts: 3358
Joined: Fri Oct 07, 2005 08:20 PM
Re: Pruebas con WhatsApp
Posted: Wed Apr 17, 2024 10:38 PM

Colegas:

Éxito obtenido, teniendo abierto wathsapp.

Saludos afectuosos

SOI, s.a. de c.v.
estbucarm@gmail.com
http://www.soisa.mex.tl/
http://sqlcmd.blogspot.com/
Tel. (722) 174 44 45
Carpe diem quam minimum credula postero
Posts: 1054
Joined: Sun Oct 09, 2005 10:41 PM
Re: Pruebas con WhatsApp, funciona con condiciones
Posted: Thu Apr 18, 2024 06:23 PM

Estimados amigos....

El envío de mensajes por el WhatsApp funciona, siempre y cuando, al momento de enviar el mensaje desde FW, el usuario que envía, debe estar activo en el WHATSAPP de la pc....

Si estamos en revisando algún otro mensaje que o es el nuestro, el mensaje no llega...

Posts: 344
Joined: Sat Jul 22, 2006 09:04 PM
Re: Pruebas con WhatsApp
Posted: Mon Sep 02, 2024 12:44 PM
Hola buenos días grupo, una consulta para el envío de email, use el ejemplo de Antonio pero me da error en la línea que adjunto
En aFiles agregue el archivo que deseo enviar y luego con la ruta completa y da el mismo error.
Code (fw): Select all Collapse
If FW_CopyToClipBoard( aFiles, 15 )
Cualquier ayuda es bienvenida.
Gracias de antemano
Saludos
FWH - Harbour - BCC7 - PellesC
Posts: 44158
Joined: Thu Oct 06, 2005 05:47 PM
Re: Pruebas con WhatsApp
Posted: Mon Sep 02, 2024 03:13 PM
Marcelo,

aFiles debe tener este formato { ruta_a_mi_fichero, ruta_a_otro_fichero, etc. }

Lo estás haciendo asi ?
regards, saludos

Antonio Linares
www.fivetechsoft.com
Posts: 344
Joined: Sat Jul 22, 2006 09:04 PM
Re: Pruebas con WhatsApp
Posted: Mon Sep 02, 2024 05:13 PM

Si Antonio, correcto así lo estoy haciendo

Saludos

FWH - Harbour - BCC7 - PellesC
Posts: 44158
Joined: Thu Oct 06, 2005 05:47 PM
Re: Pruebas con WhatsApp
Posted: Mon Sep 02, 2024 05:27 PM

Y que error es el que te aparece ?

regards, saludos

Antonio Linares
www.fivetechsoft.com
Posts: 344
Joined: Sat Jul 22, 2006 09:04 PM
Re: Pruebas con WhatsApp
Posted: Mon Sep 02, 2024 05:49 PM
Time from start: 0 hours 0 mins 3 secs
Error occurred at: 09/02/24, 11:26:02
Error description: Error BASE/1066 Argument error: conditional
Args:
[ 1] = U

Stack Calls
===========
Called from: emailforo.prg => SENDTOWHATSAPP( 27 )
Called from: emailforo.prg => MAIN( 11 )
Code (fw): Select all Collapse
#include "fivewin.ch"

FUNCTION main()
         Local cPhone := "+5493462555555"
         Local cMsg   := "prueba"
         Local aAttach:= { curdrive()+":\"+curdir()+"\"+"warnings.log" }

 xbrowse(aAttach)


         SendToWhatsApp( cPhone, cMsg, aAttach )

RETURN nil

FUNCTION SendToWhatsApp( cPhone, cMsg, aAttach )
LOCAL oShell, aFiles := {}, aOthers  := {}, lRet
 If (lRet := !Empty( cPhone ))
  If !Empty( aAttach )
   If( !HB_ISARRAY( aAttach ), aAttach := { aAttach }, )
   AEval( aAttach, {|cFile| If( HB_ISSTRING( cFile ) .AND. File( cFile ), AAdd( aFiles, cFile), AAdd( aOthers, cFile ) ) } )
  EndIf
  cMsg  := StrTran( cMsg, CRLF, "%0D%0A" )
  oShell := CreateObject( "WScript.Shell" )
  ShellExecute( 0, "Open", "whatsapp://send?phone="+cPhone+"&text="+cMsg)
  SysWait( 0.2 )
  If !Empty( aFiles )
   If FW_CopyToClipBoard( aFiles, 15 )
    SysWait( 2 )
    oShell:SendKeys( "^v" )
    SysWait( 1 )
   EndIf
  EndIf
  AEval( aOthers, <|u|
                      If FW_CopyToClipBoard( u, 2 ) .OR. FW_CopyToClipBoard( u )
                       SysWait( 1 )
                       oShell:SendKeys( "^v" )
                       SysWait( 1 )
                      EndIf
                      RETURN NIL
                  > )
   oShell:SendKeys("~")
 EndIf
RETURN lRet
FWH - Harbour - BCC7 - PellesC
Posts: 44158
Joined: Thu Oct 06, 2005 05:47 PM
Re: Pruebas con WhatsApp
Posted: Mon Sep 02, 2024 06:19 PM
Tu código funciona bien aqui

copia este código a tu ejemplo y usa varios MsgInfo()s para ver por donde pasa:
Code (fw): Select all Collapse
static function FW_CopyToClipBoard( uValue, nFormat )

   local lCopied  := .f.
   local aBmp

   if HB_ISPOINTER( uValue ) // assumes GDI+ Image object
      GDIPLUSImageToClipBoard( uValue, GetDesktopWindow() )
      return .t.
   endif

   if uValue != nil

      if nFormat == 15
         if !HB_ISARRAY( uValue ); uValue := { uValue }; endif
         _fwhtmp_ := uValue
         uValue   := {}
         AEval( _fwhtmp_, { |c| If( File( c ), AAdd( uValue, TrueName( c ) ), nil ) } )
         _fwhtmp_ := nil
         if Empty( uValue )
            return .f.
         endif
      endif

      if Empty( nFormat ) .and. HB_ISARRAY( uValue ) .and. ;
         AScan( uValue, { |u| !( ValType( u ) == "C" .and. File( u ) ) } ) == 0
            AEval( uValue, { |c,i| uValue[ i ] := TrueName( c ) } )
            nFormat  := 15
      endif

      if nFormat == 2 .and. HB_ISSTRING( uValue )
         aBmp  := FW_ReadImage( nil, uValue, , .f. )
         if !Empty( aBmp[ 1 ] )
            uValue := aBmp[ 1 ]
         else
            return .f.
         endif
      endif

      if Empty( nFormat )
         if HB_ISSTRING( uValue )
            if IsBinaryData( uValue )
               if Left( MemoryBufferType( uValue ), 4 ) == "IMG."
                  aBmp := FW_ReadImage( nil, uValue, , .f. )
                  if !Empty( aBmp[ 1 ] )
                     uValue   := aBmp[ 1 ]
                     nFormat  := 2
                  endif
               endif
               if Empty( nFormat )
                  return .f.
               endif
            elseif Left( uValue, 4 ) == "http"
               aBmp := FW_ReadImage( nil, uValue, , .f. )
               if !Empty( aBmp[ 1 ] )
                  uValue   := aBmp[ 1 ]
                  nFormat  := 2
               else
                  nFormat  := 1
               endif
            else
               nFormat  := 1
            endif
         elseif HB_ISNUMERIC( uValue )
            if ISHBITMAP( uValue )
               nFormat := 2
            elseif ISENHMETA( uValue )
               nFormat  := 14
            endif
         endif
      endif

      if Empty( nFormat )
         if ValType( uValue ) $ "AH"
            uValue   := FW_ValToExp( uValue )
         elseif ValType( uValue ) $ "DT"
            uValue   := CharRem( "'", FW_DateToSQL( uValue ) )
         else
            uValue   := cValToChar( uValue )
         endif
         nFormat  := 1
      endif

      if nFormat != nil
         if nFormat == 2
            if HB_ISNUMERIC( uValue ) .and. ISHBITMAP( uValue )
               GDIPLUSHBITMAPTOCLIPBOARD( uValue, GetDeskTopWindow() )
               lCopied  := .t.
            endif
         elseif OpenClipBoard( GetDeskTopWindow() )
            EmptyClipboard()
            if nFormat == 1 .and. IsUtf8( uValue )
               uValue    := utf8toutf16( uValue )
               if !( Right( uValue, 2 ) == Chr( 0 ) + Chr( 0 ) )
                  uValue    += ( Chr( 0 ) + Chr( 0 ) )
               endif
               lCopied  := SetClipboardData( 13, uValue )
            elseif nFormat == 15
               lCopied  := SetClipboardData( 15, uValue )
            else
               lCopied  := SetClipboardData( nFormat, uValue )
            endif
            CloseClipboard()
         endif
      endif
   endif

   if aBmp != nil
      PalBmpFree( aBmp )
   endif

return lCopied
regards, saludos

Antonio Linares
www.fivetechsoft.com
Posts: 344
Joined: Sat Jul 22, 2006 09:04 PM
Re: Pruebas con WhatsApp
Posted: Mon Sep 02, 2024 08:16 PM
Antonio, pego el codigo y te escribo algo,
Code (fw): Select all Collapse
         if nFormat == 2
            if HB_ISNUMERIC( uValue ) .and. ISHBITMAP( uValue )
               GDIPLUSHBITMAPTOCLIPBOARD( uValue, GetDeskTopWindow() )
               lCopied  := .t.
            endif
         elseif OpenClipBoard( GetDeskTopWindow() )
            EmptyClipboard()
            if nFormat == 1 .and. IsUtf8( uValue )
               uValue    := utf8toutf16( uValue )
               if !( Right( uValue, 2 ) == Chr( 0 ) + Chr( 0 ) )
                  uValue    += ( Chr( 0 ) + Chr( 0 ) )
               endif
               lCopied  := SetClipboardData( 13, uValue )
            elseif nFormat == 15
               lCopied  := SetClipboardData( 15, uValue )

    ? lCopied

            else
               lCopied  := SetClipboardData( nFormat, uValue )
            endif
            CloseClipboard()
         endif
      endif
   endif

   if aBmp != nil
      PalBmpFree( aBmp )
   endif

return lCopied
Devuelve lCopied y es indefinido osea un blanco, osea no es .f. ni .t.
FWH - Harbour - BCC7 - PellesC