elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Usando Git para manipular el directorio de trabajo, el índice y commits (segunda parte)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  [VB.net] Porteo de la implementacion del api de WhatsApiNet WhatsApp WhatsAppAPI
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: 1 [2] 3 4 5 Ir Abajo Respuesta Imprimir
Autor Tema: [VB.net] Porteo de la implementacion del api de WhatsApiNet WhatsApp WhatsAppAPI  (Leído 63,620 veces)
chesteralex

Desconectado Desconectado

Mensajes: 1


Ver Perfil
Re: [VB.net] Porteo de la implementacion del api de WhatsApiNet WhatsApp WhatsAppAPI
« Respuesta #10 en: 14 Febrero 2015, 00:46 am »

Buen día,

Antes que nada agradecer las maravillosas aportaciones que hacen en el foro.

Tengo una duda con respecto al codigo que se esta agregando en este ejemplo, yo he seguido todo los pasos pero me nunca entra en la condicion:

Código
  1. wa.Connect()
  2.        Dim datFile As String = getDatFileName(WANum)
  3.        Dim nextChallenge() As Byte
  4.        If (File.Exists(datFile)) Then
  5.            Dim foo As String = File.ReadAllText(datFile)
  6.            nextChallenge = Convert.FromBase64String(foo)
  7.        End If

No me encuentra el archivo y nunca se crea el .dat que dice según el debugger.
Estoy haciendo algo mal?, me falta algún paso?

Agradezco sus comentarios.


« Última modificación: 14 Febrero 2015, 03:22 am por Eleкtro » En línea

ChuchoVega

Desconectado Desconectado

Mensajes: 2


Ver Perfil
Re: [VB.net] Porteo de la implementacion del api de WhatsApiNet WhatsApp WhatsAppAPI
« Respuesta #11 en: 27 Febrero 2015, 03:52 am »

Hola! Gracias por el tutorial! pero necesito un poco de ayuda..
He seguido los pasos pero me daba varios errores. Entonces empece a importar librerias hasta que me quedo un solo error en la linea:
   AddHandler wa.OnGetGroups, AddressOf wa_OnGetGroups
Pregunto: No tendras un ejemplo funcionando que puedas subir?
DE verdad me interesa el tema.. Gracias por tu ayuda de antemano..
PD estoy usando vb 2013

por favor por favor por favor  :huh:

Hola! findesemana, una pregunta, cuales fueron las librerías que empezaste a importar? a mi aun me sigue marcando algunos errores, si me pudieras decir cuales fueron las librerías que le agregaste te lo agradecería mucho.
!!


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [VB.net] Porteo de la implementacion del api de WhatsApiNet WhatsApp WhatsAppAPI
« Respuesta #12 en: 27 Febrero 2015, 07:15 am »

Odio este tipo de APIs desarrolladas para .Net sin ningún tipo de documentación .Net (XML), simplemente llegan a dificultar el majeo manejo hasta imposibilitar la comprensión y la utilización de los miembros definidos en el interior de la librería debido a un desarrollo inapropiado/descuidado al no existir documentación visualizable ni accesible en tiempo de diseño (mediante IntelliSense, Object Inspector) para una plataforma en donde hay que cuidar ciertos detalles esenciales si publicas algo cómo esto para el público.

Tras descargarme el código fuente de la última versión de WhatsAppi.Net, desarrollado en C#, y analizarlo muy, muy por encima, he podido comprobar que consta de 508 miembros públicos sin documentar, la mayoría de las classes definidas (95%) usan muchos usings de NameSpaces que no se utilizan (es decir, son totalmente innecesarios), hay un total de 427 conflictos de convenciones de nombres que no se han corregido, hay varios formatos de Strings con cantidades incorrectas de parámetros (ej: String.Format("{0}", 0, 1) ), absolutamente TODOS los event-handlers están incorrectamente definidos (no utilizan la firma 'sender, e'), y lo más importante de todo, uno de sus miembros tiene una considerable fuga de recursos ya que no libera las instancias disposables de los miembros definidos en la Class 'KeyStream', todo esto entre otro tipo de fallos generales que se pueden comprobar con un análisis básico de código en VS.

Sinceramente, yo personalmente no recomiendo la utilización de ninguna librería que esté desarrollada de una manera tan descuidada, a menos que usar esa librería sea el úncio recurso viable que exista para llevar a cabo la tarea requerida (cosa que dezconozco).


Pero debido a la gran espectación que ha causado este tema ...este post (y también porque estaba un poco aburrido xD), me he tomado el tiempo de analizar, corregir, y actualizar el snippet de ejemplo que compartió el compañero @79137913 en el primer post, puesto que a muchos usuarios les ha sido dificil comprender la integración del código, o le han dado errores de algún tipo al intentar integrarlo.

Aunque por otro lado, debo confesar que yo NO utilizo WhatsApp, así que las mejoras/adaptaciones/modificaciones que he realizado en el código original, son modificaciones que he llevado a cabo bastante 'a ciegas' ya que no podré testear los resultados en un dispositivo.





Primero, antes de mostrar la actualización del código, comentaré algunos fallos (que considero bastante graves) que ustedes deberán tener en cuenta si utilizan el código original que compartió el amigo @79137913 sin hacerle ninguna modificación adicional.

Por orden de importancia/gravedad:

1.
Código
  1.    Public Sub InitWA(ByVal NickName As String, Optional ByVal debug As Boolean = False)
  2.       WAPass = File.ReadAllText(My.Application.Info.DirectoryPath & "\WAPASS.txt")
  3.       wa = New WhatsApp(WANum, WAPass, NickName, debug)
  4.       AddHandler wa.OnLoginSuccess, AddressOf wa_OnLoginSuccess
  5.       AddHandler wa.OnLoginFailed, AddressOf wa_OnLoginFailed
  6.       AddHandler wa.OnGetMessage, AddressOf wa_OnGetMessage
  7.       AddHandler wa.OnGetMessageReceivedClient, AddressOf wa_OnGetMessageReceivedClient
  8.       AddHandler wa.OnGetMessageReceivedServer, AddressOf wa_OnGetMessageReceivedServer
  9.       AddHandler wa.OnNotificationPicture, AddressOf wa_OnNotificationPicture
  10.       AddHandler wa.OnGetPresence, AddressOf wa_OnGetPresence
  11.       AddHandler wa.OnGetGroupParticipants, AddressOf wa_OnGetGroupParticipants
  12.       AddHandler wa.OnGetLastSeen, AddressOf wa_OnGetLastSeen
  13.       AddHandler wa.OnGetTyping, AddressOf wa_OnGetTyping
  14.       AddHandler wa.OnGetPaused, AddressOf wa_OnGetPaused
  15.       AddHandler wa.OnGetMessageImage, AddressOf wa_OnGetMessageImage
  16.       AddHandler wa.OnGetMessageAudio, AddressOf wa_OnGetMessageAudio
  17.       AddHandler wa.OnGetMessageVideo, AddressOf wa_OnGetMessageVideo
  18.       AddHandler wa.OnGetMessageLocation, AddressOf wa_OnGetMessageLocation
  19.       AddHandler wa.OnGetMessageVcard, AddressOf wa_OnGetMessageVcard
  20.       AddHandler wa.OnGetPhoto, AddressOf wa_OnGetPhoto
  21.       AddHandler wa.OnGetPhotoPreview, AddressOf wa_OnGetPhotoPreview
  22.       AddHandler wa.OnGetGroups, AddressOf wa_OnGetGroups
  23.       AddHandler wa.OnGetSyncResult, AddressOf wa_OnGetSyncResult
  24.       AddHandler wa.OnGetStatus, AddressOf wa_OnGetStatus
  25.       AddHandler wa.OnGetPrivacySettings, AddressOf wa_OnGetPrivacySettings
  26.       AddHandler WhatsAppApi.Helper.DebugAdapter.Instance.OnPrintDebug, AddressOf Instance_OnPrintDebug
  27.       wa.Connect()
  28.       Dim datFile As String = getDatFileName(WANum)
  29.       Dim nextChallenge() As Byte
  30.       If (File.Exists(datFile)) Then
  31.           Dim foo As String = File.ReadAllText(datFile)
  32.           nextChallenge = Convert.FromBase64String(foo)
  33.       End If
  34.       wa.Login(nextChallenge)
  35.       ProcessChat(wa)
  36.   End Sub

Por cada vez que se llame al método 'InitWA', éste AÑADIRÁ (que no reemplazará) los listeners de los eventos especificados en el código, ya que en ningún momento se está comprobando si un evento está ya siendo escuchado, ni tampoco se están eliminando handlers anteriores con el uso de la declaración 'RemoveHandler', esto ocasionaría un comportamiento anormal en en los event-handlers definidos en el código.

Hay que tenerlo MUY en cuenta por ejemplo al desconectar (wa.Disconnect), y volver a llamar al método 'InitWa', por cada vez que se hiciera eso...


2.
Citar
Código
  1.    Public Sub OnGetMedia(file As String, url As String, data() As Byte)
  2.       My.Computer.FileSystem.WriteAllBytes(String.Format("preview_{0}.jpg", file), data, False)
  3.       Dim WA_WC As New WebClient
  4.       WA_WC.DownloadFileAsync(New Uri(url), file, 0)
  5.   End Sub

La aplicación que utilice este método, incrementará el consumo RAM indefinidamente según la cantidad de veces que se instancie el WebClient, ya que la instancia del WebClient jamás se llega a liberar.


3.
Citar
Código
  1.    Public Function SendWA(ByVal MSG As String, Num As String) As Boolean
  2.       Dim usrMan As New WhatsUserManager()
  3.       Dim tmpUser = usrMan.CreateUser(Num, "User")
  4.       wa.SendMessage(Num, MSG)
  5.       Return True
  6.   End Function

La función realmente no cumple ninguna utilidad, ya que en cualquier circunstancia siempre devolverá verdadero.

Lo que habría que tratar de devolver es Verdadero si el mensaje se envia, y Falso en caso contrario,
además, quizas ni siquiera haya que fijarse en devolver True o False, ya que la función "WhatsAppApi.SendMessage" devuelve una cadena de texto cuyo contenido desconozco, pero quizás contnega detalles sobre la validación de la operación ("Succes" o "Fail"), no lo se, ya que no puedo comprobarlo sin WhatsApp (y no voy a hacerle Reflection al ensamblado solo para descubrir que valor de texto envia dicha función).


4.
Citar
Código
  1.    Public Sub wa_OnGetMessageLocation(from As String, id As String, lon As Double, lat As Double, url As String, name As String, preview() As Byte)
  2.       File.WriteAllBytes(String.Format("{0}{1end sub.jpg", lat, lon), preview)
  3.   End Sub

El formato es erroneo, ya que el segundo parámetro está abierto, por lo tanto la longitud (lon) no se tendrá en cuenta en el formato del texto.





El código original estaba bastante vb6-estilizado, aunque es algo comprensible viniendo de un programador experimentado en VB6, por otro lado yo no acepto el uso de los wrappers de VB6 en .Net, y la estructurización del código era un poco "arreu" (descuidado) cómo decimos en mi tierra.

Por lo demás, he respetado mayormente el funcionamiento y la sintaxis del snippet original de @79137913.

¿Qué es lo que he hecho?
  • Corregir los errores mencionados arriba.
  • Corregir todas las convenciones de nombres en los miembros del código original (métodos y parámetros mal nombrados) para facilitarle la tarea de búsqueda/identificación al compiler.
      También he corregido aquellas definiciones de nombres que podían resultar en ambiguaciones (ej: file),
      pues quiero recordarles que algunas palabras reservadas cómo "'type', 'from', es preferible "escaparlas" al definirlas como nombres de variables,
      y otros nombres como "file", al importar el espacio de nombres "System.IO.File", directamente es preferible evitar ese tipo de nombramientos ambiguos y utilizar algo más específico (ej: fileObj, fileName, filePath, etc).
  • Añadir los Imports de los Namespaces requeridos para el uso del código, por los problemas que algunos usuarios han tenido con eso.
  • Traslación de Módulo a Clase.
  • Implementación de la interfáz IDisposable, para liberar la instancia de WhatsApp (WA) correctamente.
  • Implementación de una excepción específica, 'WALoginFailedException', que sustituye a la terminación de ejecución en el método 'OnLoginFailed' del código original.
  • Documentar todos los miembros del código. Aunque sigue siendo una documentación MUY incompleta a falta de documentación oficial por parte de los desarrolladores de la API para .Net.

¿Cómo utilizarlo?
Esteticamente el código modificado es diferente, pero su utilización es practicamente igual al código original,
especifiquen sus datos en las propiedades "Number", "Password" y/o "PasswordFilepath";
el método original 'InitWa' ha sido reemplazado por el nuevo método 'Initializecomponent';
el método original 'ProcessChat' ha sido reemplazado por el nuevo método 'ProcessChatAsync', y el nuevo método 'ProcessChat' ahora es sincrónico;
el método original 'SendWA' ha sido reemplazado por el nuevo método 'SendMessage' para enviar un mensaje, y el nuevo método 'TestMessage' para testear un mensaje con un usuario temporal.

Ejemplo de uso:

Código
  1. Public Class TestForm
  2.  
  3.    Private wa As WhatsAppHelper
  4.  
  5.    Private Sub Test()
  6.  
  7.        Me.wa = New WhatsAppHelper(nickName:="", [debug]:=False)
  8.  
  9.        Using wa
  10.  
  11.            Debug.WriteLine(Me.wa.Number)
  12.            Debug.WriteLine(Me.wa.Password)
  13.            Debug.WriteLine(Me.wa.TextEncoding.ToString)
  14.  
  15.            wa.ProcessChatAsync()
  16.            wa.SendMessage(msg:="mensaje", num:="num")
  17.  
  18.        End Using
  19.  
  20.    End Sub
  21.  
  22. End Class





Espero que a alguien le sirva este código para despejar mejor las dudas, tengan en cuenta que esto no lo he desarrollado para mi, yo odio WhatsApp y ni lo tengo ni lo uso, este código es con la única intención de intentar ayudarles, pero si tienen alguna duda o error al usarlo entonces será mejor que la consulten con el compañero @79137913 y no conmigo, porque, vuelvo a repetir, no puedo testear las modificaciones que hice (ni el ejemplo de uso que compartí).

Source:
Código
  1. #Region " Option statements "
  2.  
  3. Option Explicit On
  4. Option Strict On
  5. Option Infer Off
  6.  
  7. #End Region
  8.  
  9. #Region " Imports "
  10.  
  11. Imports System.IO
  12. Imports System.Linq
  13. Imports System.Net
  14. Imports System.Text
  15. Imports System.Threading
  16. Imports System.Threading.Tasks
  17.  
  18. Imports WhatsAppApi
  19. Imports WhatsAppApi.Account
  20. Imports WhatsAppApi.Helper
  21. Imports WhatsAppApi.Response
  22. Imports WhatsAppApi.ApiBase
  23.  
  24. #End Region
  25.  
  26. #Region " WhatsAppHelper "
  27.  
  28. ''' <summary>
  29. ''' Class WhatsAppHelper.
  30. ''' This class cannot be inherited.
  31. ''' </summary>
  32. Public NotInheritable Class WhatsAppHelper : Implements IDisposable
  33.  
  34. #Region " Objects "
  35.  
  36.    ''' <summary>
  37.    ''' The <see cref="WhatsAppApi.WhatsApp"/> instance.
  38.    ''' </summary>
  39.    Private WithEvents wa As WhatsApp
  40.  
  41.    ''' <summary>
  42.    ''' </summary>
  43.    Private WithEvents waDebugger As DebugAdapter
  44.  
  45. #End Region
  46.  
  47. #Region " Properties "
  48.  
  49.    ''' <summary>
  50.    ''' Gets the...
  51.    ''' </summary>
  52.    ''' <value>.</value>
  53.    Public ReadOnly Property Number As String
  54.        Get
  55.            Return "5492236685519"
  56.        End Get
  57.    End Property
  58.  
  59.    ''' <summary>
  60.    ''' Gets the...
  61.    ''' </summary>
  62.    ''' <value>.</value>
  63.    Public ReadOnly Property PasswordFilepath As String
  64.        Get
  65.            Return Path.Combine(Application.StartupPath, "WAPASS.txt")
  66.        End Get
  67.    End Property
  68.  
  69.    ''' <summary>
  70.    ''' Gets the...
  71.    ''' </summary>
  72.    ''' <value>.</value>
  73.    Public ReadOnly Property Password As String
  74.        Get
  75.  
  76.            Try
  77.                Return File.ReadAllText(Me.PasswordFilepath, Me.TextEncoding)
  78.  
  79.            Catch ex As FileNotFoundException
  80.                Throw New FileNotFoundException("WhatsApp password file not found.", Me.PasswordFilepath)
  81.  
  82.            Catch ex As Exception
  83.                Throw
  84.  
  85.            End Try
  86.  
  87.        End Get
  88.    End Property
  89.  
  90.    ''' <summary>
  91.    ''' Gets the...
  92.    ''' </summary>
  93.    ''' <value>.</value>
  94.    Public ReadOnly Property TextEncoding As Encoding
  95.        Get
  96.            Return Encoding.Default
  97.        End Get
  98.    End Property
  99.  
  100. #End Region
  101.  
  102. #Region " Exceptions "
  103.  
  104.    ''' <summary>
  105.    ''' Exception that is thrown when WhatsApp login has failed.
  106.    ''' </summary>
  107.    <Serializable>
  108.    Public NotInheritable Class WALoginFailedException : Inherits Exception
  109.  
  110.        ''' <summary>
  111.        ''' Initializes a new instance of the <see cref="WALoginFailedException"/> class.
  112.        ''' </summary>
  113.        Public Sub New()
  114.            MyBase.New("WhatsApp Login Failed")
  115.        End Sub
  116.  
  117.        ''' <summary>
  118.        ''' Initializes a new instance of the <see cref="WALoginFailedException"/> class.
  119.        ''' </summary>
  120.        ''' <param name="message">The message that describes the error.</param>
  121.        Public Sub New(message As String)
  122.            MyBase.New(message)
  123.        End Sub
  124.  
  125.    End Class
  126.  
  127. #End Region
  128.  
  129. #Region " Constructors "
  130.  
  131.    ''' <summary>
  132.    ''' Initializes a new instance of the <see cref="WhatsAppHelper"/> class.
  133.    ''' </summary>
  134.    ''' <param name="nickName">.</param>
  135.    ''' <param name="debug">.</param>
  136.    Public Sub New(ByVal nickName As String,
  137.                   Optional ByVal debug As Boolean = False)
  138.  
  139.        Me.InitializeComponent(nickName, debug)
  140.  
  141.    End Sub
  142.  
  143.    ''' <summary>
  144.    ''' Prevents a default instance of the <see cref="WhatsApp"/> class from being created.
  145.    ''' </summary>
  146.    Private Sub New()
  147.    End Sub
  148.  
  149. #End Region
  150.  
  151. #Region " Private Methods "
  152.  
  153.    ''' <summary>
  154.    ''' </summary>
  155.    ''' <param name="nickName">.</param>
  156.    ''' <param name="debug">.</param>
  157.    Private Sub InitializeComponent(ByVal nickName As String,
  158.                                    Optional ByVal debug As Boolean = False)
  159.  
  160.        Me.wa = New WhatsApp(Me.Number, Me.Password, nickName, debug)
  161.        Me.waDebugger = DebugAdapter.Instance
  162.        Me.wa.Connect()
  163.  
  164.        Dim datFile As String = Me.GetDatFileName(Me.Number)
  165.        Dim nextChallenge As Byte() = Nothing
  166.  
  167.        If File.Exists(datFile) Then
  168.            Dim text As String = File.ReadAllText(datFile, Me.TextEncoding)
  169.            nextChallenge = Convert.FromBase64String(text)
  170.        End If
  171.  
  172.        Me.wa.Login(nextChallenge)
  173.  
  174.    End Sub
  175.  
  176.    ''' <summary>
  177.    ''' </summary>
  178.    ''' <param name="pn">.</param>
  179.    ''' <returns>.</returns>
  180.    Private Function GetDatFileName(ByVal pn As String) As String
  181.  
  182.        Dim filename As String = String.Format("{0}.next.dat", pn)
  183.        Return Path.Combine(Application.StartupPath, filename)
  184.  
  185.    End Function
  186.  
  187.    ''' <summary>
  188.    ''' </summary>
  189.    ''' <param name="filename">.</param>
  190.    ''' <param name="url">The url to download.</param>
  191.    ''' <param name="data">.</param>
  192.    Private Sub DownloadMedia(ByVal filename As String,
  193.                              ByVal url As String,
  194.                              ByVal data As Byte())
  195.  
  196.        File.WriteAllBytes(String.Format("preview_{0}.jpg", filename), data)
  197.  
  198.        Dim waClient As New WebClient
  199.        Try
  200.            Using waClient
  201.                waClient.DownloadFileAsync(New Uri(url), filename, 0)
  202.            End Using
  203.  
  204.        Catch ex As Exception
  205.            Throw
  206.  
  207.        Finally
  208.            If waClient IsNot Nothing Then
  209.                waClient.Dispose()
  210.            End If
  211.  
  212.        End Try
  213.  
  214.    End Sub
  215.  
  216. #End Region
  217.  
  218. #Region " Public Methods "
  219.  
  220.    ''' <summary>
  221.    ''' </summary>
  222.    ''' <param name="msg">.</param>
  223.    ''' <param name="num">.</param>
  224.    ''' <returns>.</returns>
  225.    Public Function SendMessage(ByVal msg As String,
  226.                                ByVal num As String) As String
  227.  
  228.        Return wa.SendMessage([to]:=num, txt:=msg)
  229.  
  230.    End Function
  231.  
  232.    ''' <summary>
  233.    ''' </summary>
  234.    ''' <param name="msg">.</param>
  235.    ''' <param name="num">.</param>
  236.    ''' <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns>
  237.    Public Function TestMessage(ByVal msg As String,
  238.                                ByVal num As String) As Boolean
  239.  
  240.        Dim tmpUser As WhatsUser = New WhatsUserManager().CreateUser(num, "User")
  241.  
  242.        Try
  243.            wa.SendMessage([to]:=num, txt:=msg)
  244.  
  245.        Catch ex As Exception
  246.            Return False
  247.  
  248.        End Try
  249.  
  250.        Return True
  251.  
  252.    End Function
  253.  
  254.    ''' <summary>
  255.    ''' </summary>
  256.    Public Sub ProcessChatAsync()
  257.  
  258.        Task.Factory.StartNew(Sub()
  259.                                  Me.ProcessChat(Me.wa)
  260.                              End Sub)
  261.  
  262.    End Sub
  263.  
  264.    ''' <summary>
  265.    ''' </summary>
  266.    Public Sub ProcessChat()
  267.  
  268.        While Me.wa IsNot Nothing
  269.  
  270.            Try
  271.                Me.wa.PollMessages()
  272.  
  273.            Catch ex As Exception
  274.                ' Throw
  275.  
  276.            End Try
  277.  
  278.            Thread.Sleep(millisecondsTimeout:=100)
  279.  
  280.        End While
  281.  
  282.    End Sub
  283.  
  284. #End Region
  285.  
  286. #Region " Event-Handlers "
  287.  
  288.    ''' <summary>
  289.    ''' Handles the OnGetPrivacySettings event of the <see cref="WA"/> instance.
  290.    ''' </summary>
  291.    ''' <param name="settings">.</param>
  292.    Private Sub WA_OnGetPrivacySettings(ByVal settings As Dictionary(Of VisibilityCategory, VisibilitySetting)) _
  293.    Handles wa.OnGetPrivacySettings
  294.  
  295.        ' Put your code here.
  296.  
  297.    End Sub
  298.  
  299.    ''' <summary>
  300.    ''' Handles the OnGetStatus event of the <see cref="WA"/> instance.
  301.    ''' </summary>
  302.    ''' <param name="form">.</param>
  303.    ''' <param name="type">.</param>
  304.    ''' <param name="name">.</param>
  305.    ''' <param name="status">.</param>
  306.    Private Sub WA_OnGetStatus(ByVal form As String,
  307.                               ByVal type As String,
  308.                               ByVal name As String,
  309.                               ByVal status As String) _
  310.    Handles wa.OnGetStatus
  311.  
  312.        ' Put your code here.
  313.  
  314.    End Sub
  315.  
  316.    ''' <summary>
  317.    ''' Handles the OnGetSyncResult event of the <see cref="WA"/> instance.
  318.    ''' </summary>
  319.    ''' <param name="index">.</param>
  320.    ''' <param name="sid">.</param>
  321.    ''' <param name="existingUsers">.</param>
  322.    ''' <param name="failedNumbers">.</param>
  323.    Private Sub WA_OnGetSyncResult(ByVal index As Integer,
  324.                                   ByVal sid As String,
  325.                                   ByVal existingUsers As Dictionary(Of String, String),
  326.                                   ByVal failedNumbers As String()) _
  327.    Handles wa.OnGetSyncResult
  328.  
  329.        ' Put your code here.
  330.  
  331.    End Sub
  332.  
  333.    ''' <summary>
  334.    ''' Handles the OnGetGroups event of the <see cref="WA"/> instance.
  335.    ''' </summary>
  336.    ''' <param name="groups">.</param>
  337.    Private Sub WA_OnGetGroups(ByVal groups As WaGroupInfo()) _
  338.    Handles wa.OnGetGroups
  339.  
  340.        ' Put your code here.
  341.  
  342.    End Sub
  343.  
  344.    ''' <summary>
  345.    ''' Handles the OnGetPhotoPreview event of the <see cref="WA"/> instance.
  346.    ''' </summary>
  347.    ''' <param name="from">.</param>
  348.    ''' <param name="id">.</param>
  349.    ''' <param name="data">.</param>
  350.    Private Sub WA_OnGetPhotoPreview(ByVal [from] As String,
  351.                                     ByVal id As String,
  352.                                     ByVal data As Byte()) _
  353.    Handles wa.OnGetPhotoPreview
  354.  
  355.        Try
  356.            File.WriteAllBytes(String.Format("preview_{0}.jpg", [from]), data)
  357.  
  358.        Catch ex As Exception
  359.            Throw
  360.  
  361.        End Try
  362.  
  363.    End Sub
  364.  
  365.    ''' <summary>
  366.    ''' Handles the OnGetPhoto event of the <see cref="WA"/> instance.
  367.    ''' </summary>
  368.    ''' <param name="from">.</param>
  369.    ''' <param name="id">.</param>
  370.    ''' <param name="data">.</param>
  371.    Private Sub WA_OnGetPhoto(ByVal [from] As String,
  372.                              ByVal id As String,
  373.                              ByVal data As Byte()) _
  374.    Handles wa.OnGetPhoto
  375.  
  376.        Try
  377.            File.WriteAllBytes(String.Format("{0}.jpg", [from]), data)
  378.  
  379.        Catch ex As Exception
  380.            Throw
  381.  
  382.        End Try
  383.  
  384.    End Sub
  385.  
  386.    ''' <summary>
  387.    ''' Handles the OnGetMessageVcard event of the <see cref="WA"/> instance.
  388.    ''' </summary>
  389.    ''' <param name="from">.</param>
  390.    ''' <param name="id">.</param>
  391.    ''' <param name="name">.</param>
  392.    ''' <param name="data">.</param>
  393.    Private Sub WA_OnGetMessageVcard(ByVal [from] As String,
  394.                                     ByVal id As String,
  395.                                     ByVal name As String,
  396.                                     ByVal data As Byte()) _
  397.    Handles wa.OnGetMessageVcard
  398.  
  399.        Try
  400.            File.WriteAllBytes(String.Format("{0}.vcf", name), data)
  401.  
  402.        Catch ex As Exception
  403.            Throw
  404.  
  405.        End Try
  406.  
  407.    End Sub
  408.  
  409.    ''' <summary>
  410.    ''' Handles the OnGetMessageLocation event of the <see cref="WA"/> instance.
  411.    ''' </summary>
  412.    ''' <param name="from">.</param>
  413.    ''' <param name="id">.</param>
  414.    ''' <param name="lon">.</param>
  415.    ''' <param name="lat">.</param>
  416.    ''' <param name="url">.</param>
  417.    ''' <param name="name">.</param>
  418.    ''' <param name="preview">.</param>
  419.    Private Sub WA_OnGetMessageLocation(ByVal [from] As String,
  420.                                        ByVal id As String,
  421.                                        ByVal lon As Double,
  422.                                        ByVal lat As Double,
  423.                                        ByVal url As String,
  424.                                        ByVal name As String,
  425.                                        ByVal preview() As Byte) _
  426.    Handles wa.OnGetMessageLocation
  427.  
  428.        Try
  429.            File.WriteAllBytes(String.Format("{0}{1}end sub.jpg", lat, lon), preview)
  430.  
  431.        Catch ex As Exception
  432.            Throw
  433.  
  434.        End Try
  435.  
  436.    End Sub
  437.  
  438.    ''' <summary>
  439.    ''' Handles the OnGetMessageVideo event of the <see cref="WA"/> instance.
  440.    ''' </summary>
  441.    ''' <param name="from">.</param>
  442.    ''' <param name="id">.</param>
  443.    ''' <param name="filename">.</param>
  444.    ''' <param name="fileSize">.</param>
  445.    ''' <param name="url">.</param>
  446.    ''' <param name="preview">.</param>
  447.    Private Sub WA_OnGetMessageVideo(ByVal [from] As String,
  448.                                     ByVal id As String,
  449.                                     ByVal filename As String,
  450.                                     ByVal fileSize As Integer,
  451.                                     ByVal url As String,
  452.                                     ByVal preview As Byte()) _
  453.    Handles wa.OnGetMessageVideo
  454.  
  455.        Me.DownloadMedia(filename, url, preview)
  456.  
  457.    End Sub
  458.  
  459.    ''' <summary>
  460.    ''' Handles the OnGetMessageAudio event of the <see cref="WA"/> instance.
  461.    ''' </summary>
  462.    ''' <param name="from">.</param>
  463.    ''' <param name="id">.</param>
  464.    ''' <param name="filename">.</param>
  465.    ''' <param name="filesize">.</param>
  466.    ''' <param name="url">.</param>
  467.    ''' <param name="preview">.</param>
  468.    Private Sub WA_OnGetMessageAudio(ByVal [from] As String,
  469.                                     ByVal id As String,
  470.                                     ByVal filename As String,
  471.                                     ByVal filesize As Integer,
  472.                                     ByVal url As String,
  473.                                     ByVal preview As Byte()) _
  474.    Handles wa.OnGetMessageAudio
  475.  
  476.        Me.DownloadMedia(filename, url, preview)
  477.  
  478.    End Sub
  479.  
  480.    ''' <summary>
  481.    ''' Handles the OnGetMessageImage event of the <see cref="WA"/> instance.
  482.    ''' </summary>
  483.    ''' <param name="from">.</param>
  484.    ''' <param name="id">.</param>
  485.    ''' <param name="filename">.</param>
  486.    ''' <param name="size">.</param>
  487.    ''' <param name="url">.</param>
  488.    ''' <param name="preview">.</param>
  489.    Private Sub WA_OnGetMessageImage(ByVal [from] As String,
  490.                                     ByVal id As String,
  491.                                     ByVal filename As String,
  492.                                     ByVal size As Integer,
  493.                                     ByVal url As String,
  494.                                     ByVal preview As Byte()) _
  495.    Handles wa.OnGetMessageImage
  496.  
  497.        Me.DownloadMedia(filename, url, preview)
  498.  
  499.    End Sub
  500.  
  501.    ''' <summary>
  502.    ''' Handles the OnGetPaused event of the <see cref="WA"/> instance.
  503.    ''' </summary>
  504.    ''' <param name="from">.</param>
  505.    Private Sub WA_OnGetPaused(ByVal [from] As String) _
  506.    Handles wa.OnGetPaused
  507.  
  508.        ' Put your code here.
  509.  
  510.    End Sub
  511.  
  512.    ''' <summary>
  513.    ''' Handles the OnGetTyping event of the <see cref="WA"/> instance.
  514.    ''' </summary>
  515.    ''' <param name="from">.</param>
  516.    Private Sub WA_OnGetTyping(ByVal [from] As String) _
  517.    Handles wa.OnGetTyping
  518.  
  519.        ' Put your code here.
  520.  
  521.    End Sub
  522.  
  523.    ''' <summary>
  524.    ''' Handles the OnGetLastSeen event of the <see cref="WA"/> instance.
  525.    ''' </summary>
  526.    ''' <param name="from">.</param>
  527.    ''' <param name="lastseen">.</param>
  528.    Private Sub WA_OnGetLastSeen(ByVal [from] As String,
  529.                                ByVal lastseen As Date) _
  530.    Handles wa.OnGetLastSeen
  531.  
  532.        ' Put your code here.
  533.  
  534.    End Sub
  535.  
  536.    ''' <summary>
  537.    ''' Handles the OnGetMessageReceivedServer event of the <see cref="WA"/> instance.
  538.    ''' </summary>
  539.    ''' <param name="from">.</param>
  540.    ''' <param name="id">.</param>
  541.    Private Sub WA_OnGetMessageReceivedServer(ByVal [from] As String,
  542.                                              ByVal id As String) _
  543.    Handles wa.OnGetMessageReceivedServer
  544.  
  545.        ' Put your code here.
  546.  
  547.    End Sub
  548.  
  549.    ''' <summary>
  550.    ''' Handles the OnGetMessageReceivedClient event of the <see cref="WA"/> instance.
  551.    ''' </summary>
  552.    ''' <param name="from">.</param>
  553.    ''' <param name="id">.</param>
  554.    Private Sub WA_OnGetMessageReceivedClient(ByVal [from] As String,
  555.                                              ByVal id As String) _
  556.    Handles wa.OnGetMessageReceivedClient
  557.  
  558.        ' Put your code here.
  559.  
  560.    End Sub
  561.  
  562.    ''' <summary>
  563.    ''' Handles the OnGetGroupParticipants event of the <see cref="WA"/> instance.
  564.    ''' </summary>
  565.    ''' <param name="gjid">.</param>
  566.    ''' <param name="jids">.</param>
  567.    Private Sub WA_OnGetGroupParticipants(ByVal gjid As String,
  568.                                          ByVal jids As String()) _
  569.    Handles wa.OnGetGroupParticipants
  570.  
  571.        ' Put your code here.
  572.  
  573.    End Sub
  574.  
  575.    ''' <summary>
  576.    ''' Handles the OnGetPresence event of the <see cref="WA"/> instance.
  577.    ''' </summary>
  578.    ''' <param name="from">.</param>
  579.    ''' <param name="type">.</param>
  580.    Private Sub WA_OnGetPresence(ByVal [from] As String,
  581.                                 ByVal type As String) _
  582.    Handles wa.OnGetPresence
  583.  
  584.        ' Put your code here.
  585.  
  586.    End Sub
  587.  
  588.    ''' <summary>
  589.    ''' Handles the OnNotificationPicture event of the <see cref="WA"/> instance.
  590.    ''' </summary>
  591.    ''' <param name="type">.</param>
  592.    ''' <param name="jid">.</param>
  593.    ''' <param name="id">.</param>
  594.    Private Sub WA_OnNotificationPicture(ByVal [type] As String,
  595.                                         ByVal jid As String,
  596.                                         ByVal id As String) _
  597.    Handles wa.OnNotificationPicture
  598.  
  599.        ' Put your code here.
  600.  
  601.    End Sub
  602.  
  603.    ''' <summary>
  604.    ''' Handles the OnGetMessage event of the <see cref="WA"/> instance.
  605.    ''' </summary>
  606.    ''' <param name="node">.</param>
  607.    ''' <param name="from">.</param>
  608.    ''' <param name="id">.</param>
  609.    ''' <param name="name">.</param>
  610.    ''' <param name="message">.</param>
  611.    ''' <param name="receiptSent">.</param>
  612.    Private Sub WA_OnGetMessage(ByVal node As ProtocolTreeNode,
  613.                                ByVal [from] As String,
  614.                                ByVal id As String,
  615.                                ByVal name As String,
  616.                                ByVal message As String,
  617.                                ByVal receiptSent As Boolean) _
  618.    Handles wa.OnGetMessage
  619.  
  620.        Dim number As String = [from].Split("@"c).First
  621.  
  622.    End Sub
  623.  
  624.    ''' <summary>
  625.    ''' Handles the OnLoginFailed event of the <see cref="WA"/> instance.
  626.    ''' </summary>
  627.    ''' <param name="data">The data.</param>
  628.    Private Sub WA_OnLoginFailed(ByVal data As String) _
  629.    Handles wa.OnLoginFailed
  630.  
  631.        Throw New WALoginFailedException
  632.  
  633.    End Sub
  634.  
  635.    ''' <summary>
  636.    ''' Handles the OnLoginSuccess event of the <see cref="WA"/> instance.
  637.    ''' </summary>
  638.    ''' <param name="phoneNumber">.</param>
  639.    ''' <param name="data">.</param>
  640.    Private Sub WA_OnLoginSuccess(ByVal phoneNumber As String,
  641.                                  ByVal data As Byte()) _
  642.    Handles wa.OnLoginSuccess
  643.  
  644.        ' next password
  645.        Dim sdata As String = Convert.ToBase64String(data)
  646.  
  647.        Try
  648.            File.WriteAllText(Me.GetDatFileName(Me.Number), sdata)
  649.  
  650.        Catch ex As Exception
  651.            Throw
  652.  
  653.        End Try
  654.  
  655.    End Sub
  656.  
  657.    ''' <summary>
  658.    ''' Handles the OnPrintDebug event of the <see cref="waDebugger"/> instance.
  659.    ''' </summary>
  660.    ''' <param name="value">.</param>
  661.    Private Sub Instance_OnPrintDebug(ByVal value As Object) _
  662.    Handles waDebugger.OnPrintDebug
  663.  
  664.        Debug.Print(value.ToString)
  665.  
  666.    End Sub
  667.  
  668. #End Region
  669.  
  670. #Region " IDisposable "
  671.  
  672.    ''' <summary>
  673.    ''' To detect redundant calls when disposing.
  674.    ''' </summary>
  675.    Private isDisposed As Boolean = False
  676.  
  677.    ''' <summary>
  678.    ''' Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  679.    ''' </summary>
  680.    Public Sub Dispose() Implements IDisposable.Dispose
  681.        Me.Dispose(isDisposing:=True)
  682.        GC.SuppressFinalize(obj:=Me)
  683.    End Sub
  684.  
  685.    ''' <summary>
  686.    ''' Releases unmanaged and - optionally - managed resources.
  687.    ''' </summary>
  688.    ''' <param name="isDisposing">
  689.    ''' <c>true</c> to release both managed and unmanaged resources;
  690.    ''' <c>false</c> to release only unmanaged resources.
  691.    ''' </param>
  692.    Protected Sub Dispose(ByVal isDisposing As Boolean)
  693.  
  694.        If Not Me.IsDisposed Then
  695.  
  696.            If isDisposing Then
  697.  
  698.                Try
  699.                    Me.wa.Disconnect()
  700.                    Me.wa = Nothing
  701.                    Me.waDebugger = Nothing
  702.  
  703.                Catch ex As Exception
  704.                    Throw
  705.  
  706.                End Try
  707.  
  708.            End If
  709.  
  710.        End If
  711.  
  712.        Me.isDisposed = True
  713.  
  714.    End Sub
  715.  
  716. #End Region
  717.  
  718. End Class
  719.  
  720. #End Region

Saludos!
« Última modificación: 27 Febrero 2015, 19:24 pm por Eleкtro » En línea

79137913


Desconectado Desconectado

Mensajes: 1.169


4 Esquinas


Ver Perfil WWW
Re: [VB.net] Porteo de la implementacion del api de WhatsApiNet WhatsApp WhatsAppAPI
« Respuesta #13 en: 27 Febrero 2015, 18:15 pm »

HOLA!!!

@Elektro:
Muy bueno que hayas modificado el codigo, me alegra mucho, en cuanto a el codigo no es mas que un porteo de su version en c# casi textual.

Es cierto que tiene una forma muy de vb6 aunque no es mi estructura, intento respetar los lenguajes.

Confirmo que tu codigo funciona correctamente.

Este post me alienta a revivir una vieja app, que si no te importa, me gustaria que luego revisaras a ver que te parece, estoy empezando a programarla recien si queres mas info contactame por priv.

GRACIAS POR LEER!!!
En línea

"Como no se puede igualar a Dios, ya he decidido que hacer, ¡SUPERARLO!"
"La peor de las ignorancias es no saber corregirlas"

 79137913                          *Shadow Scouts Team*
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: [VB.net] Porteo de la implementacion del api de WhatsApiNet WhatsApp WhatsAppAPI
« Respuesta #14 en: 1 Marzo 2015, 16:48 pm »

Confirmo que tu codigo funciona correctamente.

Me alegra saberlo, realmente lo hice todo "a ciegas" y tenia esa duda de que al final no sirviera de mucho xD.


Este post me alienta a revivir una vieja app, que si no te importa, me gustaria que luego revisaras a ver que te parece, estoy empezando a programarla recien si queres mas info contactame por priv.

jajaja, no hace falta ni que menciones de que app se trata, te estoy leyendo la mente, y creo que a todos los usuarios de elhacker.net nos gustará poder ver esa gran herramienta actualizada, de hecho hace tiempo pensé en hacer una versión .Net de tu programa, pero me desmotivé bastante porque... bueno, porque la app ya existe y es funcional en VB6 así que me pareció un poco tontería el tratar de reinventarla en .Net xD, y tampoco quería que pareciese que intentaba arrebatarte ningún mérito, así que lo mejor es que lo hagas tú, y yo te ayudo si quieres y si lo necesitases, por supuesto.

Un saludo!
En línea

gusontop

Desconectado Desconectado

Mensajes: 3


Ver Perfil
Re: [VB.net] Porteo de la implementacion del api de WhatsApiNet WhatsApp WhatsAppAPI
« Respuesta #15 en: 5 Marzo 2015, 16:49 pm »

Buen día,

Antes que nada agradecer las maravillosas aportaciones que hacen en el foro.

Tengo una duda con respecto al codigo que se esta agregando en este ejemplo, yo he seguido todo los pasos pero me nunca entra en la condicion:

Código
  1. wa.Connect()
  2.        Dim datFile As String = getDatFileName(WANum)
  3.        Dim nextChallenge() As Byte
  4.        If (File.Exists(datFile)) Then
  5.            Dim foo As String = File.ReadAllText(datFile)
  6.            nextChallenge = Convert.FromBase64String(foo)
  7.        End If

No me encuentra el archivo y nunca se crea el .dat que dice según el debugger.
Estoy haciendo algo mal?, me falta algún paso?

Agradezco sus comentarios.

A mi me esta pasando lo mismo y no consigo que realize en envio del mensaje. ¿Podeis ayudarnos?
Gracias.
En línea

79137913


Desconectado Desconectado

Mensajes: 1.169


4 Esquinas


Ver Perfil WWW
Re: [VB.net] Porteo de la implementacion del api de WhatsApiNet WhatsApp WhatsAppAPI
« Respuesta #16 en: 5 Marzo 2015, 16:55 pm »

HOLA!!!

Eso es por que no tenes el archivo next challenge en la carpeta del ejecutable.

GRACIAS POR LEER!!!
En línea

"Como no se puede igualar a Dios, ya he decidido que hacer, ¡SUPERARLO!"
"La peor de las ignorancias es no saber corregirlas"

 79137913                          *Shadow Scouts Team*
gusontop

Desconectado Desconectado

Mensajes: 3


Ver Perfil
Re: [VB.net] Porteo de la implementacion del api de WhatsApiNet WhatsApp WhatsAppAPI
« Respuesta #17 en: 5 Marzo 2015, 18:42 pm »

Claro que no tengo el archivo Next Challenge, pero de donde lo saco o como se genera.

Gracias por responder tan pronto.
En línea

ChuchoVega

Desconectado Desconectado

Mensajes: 2


Ver Perfil
Re: [VB.net] Porteo de la implementacion del api de WhatsApiNet WhatsApp WhatsAppAPI
« Respuesta #18 en: 5 Marzo 2015, 18:51 pm »

Claro que no tengo el archivo Next Challenge, pero de donde lo saco o como se genera.

Gracias por responder tan pronto.

Gusontop, tengo el mismo problema es lo único que me hace falta para poder hechar a andar la APP, ojala y esto lo puedan responder rápido, de igual manera si encuentro como se debe hacer eso del archivo Next Challenge lo posteo.
En línea

79137913


Desconectado Desconectado

Mensajes: 1.169


4 Esquinas


Ver Perfil WWW
Re: [VB.net] Porteo de la implementacion del api de WhatsApiNet WhatsApp WhatsAppAPI
« Respuesta #19 en: 5 Marzo 2015, 19:17 pm »

HOLA!!!

Chicos les confirmo la razon por la cual el programa no entra en ese if es por que su archivo nextchallenge no existe,  puede haber 2 razones para esto, la primera es que ustedes cambiaron el numero de telefono o que ustedes nunca enviaron un mensaje.

En caso que sea la primera borren el archivo nextchallenge obsoleto, vuelvan a generar la clave e intenten de nuevo.

En caso que sea la seguda es programa no necesita del archivo next challenge la primera vez por que el next challenge estaria en blanco. Yo supongo y solo supogo, si ustedes estan usando un numero que en algun momento tuvo whatsapp lamento informarles que el nextchallenge no lo pueden obtener por estos medios, ya que sino seria muy simple hackear el whatsapp de cualquiera con esos simples pasos. Para crear la contraseña deben si o si usar un numero virgen en whatsapp.(o un numero que siempre ha usado WART.

GRACIAS POR LEER!!!
En línea

"Como no se puede igualar a Dios, ya he decidido que hacer, ¡SUPERARLO!"
"La peor de las ignorancias es no saber corregirlas"

 79137913                          *Shadow Scouts Team*
Páginas: 1 [2] 3 4 5 Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Implementación de la ECC
Criptografía
C3.0 0 3,021 Último mensaje 30 Junio 2011, 02:04 am
por C3.0
WhatsApp de nuevo fuera de servicio. Alternativas a WhatsApp
Noticias
wolfbcn 4 8,152 Último mensaje 18 Octubre 2011, 00:00 am
por Sorke
WhatsApp ha comenzado a bloquear cuentas de forma masiva por usar WhatsApp Plus
Noticias
wolfbcn 3 4,353 Último mensaje 22 Mayo 2015, 02:14 am
por delanoche86
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines