Exemple #1
0
        private void ChatForm_Load(object sender, EventArgs e)
        {
            //timer = new System.Timers.Timer();
            //timer.Interval = 6000;
            //timer.Elapsed += Timer_Elapsed;
            thread = new Thread(t =>
            {
                while (wa != null)
                {
                    if (wa.ConnectionStatus == ApiBase.CONNECTION_STATUS.LOGGEDIN)
                    {
                        if (string.IsNullOrEmpty(fileName))
                        {
                            wa.PollMessages();
                            Thread.Sleep(3000);
                            continue;
                        }
                        else
                        {
                            Thread.Sleep(3000);
                            continue;
                        }
                    }
                }
            })

            {
                IsBackground = true
            };
            thread.Start();
        }
Exemple #2
0
        private static void Main(string[] args)
        {
            var tmpEncoding = Encoding.UTF8;

            System.Console.OutputEncoding = Encoding.Default;
            System.Console.InputEncoding  = Encoding.Default;
            string nickname = "WhatsAPI Test";
            string sender   = "3526********";                // Mobile number with country code (but without + or 00)
            string password = "******"; //v2 password
            string target   = "316********";                 // Mobile number to send the message to

            WhatsApp wa = new WhatsApp(sender, password, nickname, true);

            wa.Connect();
            wa.Login();
            wa.PollMessages();

            wa.Message(target, "Hi this is sent using WhatsApiNet");
            wa.PollMessages();

            ProcessChat(wa, "");

            Console.ReadKey();
        }
Exemple #3
0
        private void ProcessMessages(object sender, DoWorkEventArgs args)
        {
            if (sender == null)
            {
                return;
            }

            while (this.isRunning)
            {
                if (!wa.HasMessages())
                {
                    wa.PollMessages();
                    Thread.Sleep(100);
                    continue;
                }

                var tmpMessages = wa.GetAllMessages();
                (sender as BackgroundWorker).ReportProgress(1, tmpMessages);
            }
        }
Exemple #4
0
        private static void ProcessChat(WhatsApp _WhatsAppApi, string _Dest)
        {
            Thread thRecv = new Thread(t =>
            {
                try
                {
                    while (_WhatsAppApi != null)
                    {
                        _WhatsAppApi.PollMessages();
                        Thread.Sleep(100);
                        continue;
                    }
                }
                catch (ThreadAbortException)
                {
                }
            })
            {
                IsBackground = true
            };

            thRecv.Start();

            WhatsUserManager usrMan  = new WhatsUserManager();
            WhatsUser        tmpUser = usrMan.CreateUser(_Dest, "User");

            while (true)
            {
                String line = Console.ReadLine();
                if (String.IsNullOrEmpty(line))
                {
                    continue;
                }

                string command = line.Trim();
                switch (command)
                {
                case "/query":
                    Console.WriteLine("[] Interactive conversation with {0}:", tmpUser);
                    break;

                case "/accountinfo":
                    Console.WriteLine("[] Account Info: {0}", _WhatsAppApi.GetAccountInfo().ToString());
                    break;

                case "/lastseen":
                    Console.WriteLine("[] Request last seen {0}", tmpUser);
                    _WhatsAppApi.SendQueryLastOnline(tmpUser.GetFullJid());
                    break;

                case "/exit":
                    _WhatsAppApi = null;
                    thRecv.Abort();
                    return;

                case "/start":
                    _WhatsAppApi.SendComposing(tmpUser.GetFullJid());
                    break;

                case "/pause":
                    _WhatsAppApi.SendPaused(tmpUser.GetFullJid());
                    break;

                default:
                    Console.WriteLine("[] Send message to {0}: {1}", tmpUser, line);
                    _WhatsAppApi.SendMessage(tmpUser.GetFullJid(), line);
                    break;
                }
            }
        }
Exemple #5
0
        private static void ProcessChat(WhatsApp wa, string dst)
        {
            var thRecv = new Thread(t =>
            {
                try
                {
                    while (wa != null)
                    {
                        wa.PollMessages();
                        Thread.Sleep(100);
                        continue;
                    }
                }
                catch (ThreadAbortException)
                {
                }
            })
            {
                IsBackground = true
            };

            thRecv.Start();

            WhatsUserManager usrMan = new WhatsUserManager();
            var tmpUser             = usrMan.CreateUser(dst, "User");

            while (true)
            {
                string line = Console.ReadLine();
                if (line == null && line.Length == 0)
                {
                    continue;
                }

                string command = line.Trim();
                switch (command)
                {
                case "/query":
                    //var dst = dst//trim(strstr($line, ' ', FALSE));
                    Console.WriteLine("[] Interactive conversation with {0}:", tmpUser);
                    break;

                case "/accountinfo":
                    Console.WriteLine("[] Account Info: {0}", wa.GetAccountInfo().ToString());
                    break;

                case "/lastseen":
                    Console.WriteLine("[] Request last seen {0}", tmpUser);
                    wa.SendQueryLastOnline(tmpUser.GetFullJid());
                    break;

                case "/exit":
                    wa = null;
                    thRecv.Abort();
                    return;

                case "/start":
                    wa.SendComposing(tmpUser.GetFullJid());
                    break;

                case "/pause":
                    wa.SendPaused(tmpUser.GetFullJid());
                    break;

                default:
                    Console.WriteLine("[] Send message to {0}: {1}", tmpUser, line);
                    wa.SendMessage(tmpUser.GetFullJid(), line);
                    break;
                }
            }
        }
Exemple #6
0
 private void send()
 {
     try
     {
         WhatsUserManager manager = new WhatsUserManager();
         user = manager.CreateUser(textBox5MyMobile.Text, textBox4Name.Text);
         var thread = new Thread(t =>
         {
             UpdateTextBox textbox = UpdateDataTextBox;
             wa = new WhatsApp(textBox5MyMobile.Text, textBox6Password.Text, textBox4Name.Text, true);
             wa.OnConnectSuccess += () =>
             {
                 if (textBox3Status.InvokeRequired)
                 {
                     Invoke(textbox, textBox3Status, "Connected...");
                 }
                 wa.OnLoginSuccess += (phone, data) =>
                 {
                     if (textBox3Status.InvokeRequired)
                     {
                         Invoke(textbox, textBox3Status, "\r\nLogin success!");
                     }
                     while (wa != null)
                     {
                         wa.PollMessages();
                         Thread.Sleep(200);
                         continue;
                     }
                 };
                 wa.OnGetMessage += (node, from, id, name, message, receipt_sent) =>
                 {
                     if (textBox3Status.InvokeRequired)
                     {
                         Invoke(textbox, textBox3Status, string.Format("\r\n{0}:{1}", name, message));
                     }
                 };
                 wa.OnLoginFailed += (data) =>
                 {
                     if (textBox3Status.InvokeRequired)
                     {
                         Invoke(textbox, textBox3Status, string.Format("\r\nLogin failed:{0}", data));
                     }
                 };
                 wa.Login();
             };
             wa.OnConnectFailed += (ex) =>
             {
                 if (textBox3Status.InvokeRequired)
                 {
                     Invoke(textbox, textBox3Status, string.Format("\r\nConnect failed: {0}", ex.StackTrace));
                 }
             };
             wa.Connect();
         })
         {
             IsBackground = true
         };
         thread.Start();
     }
     catch (Exception ex) { MessageBox.Show("Connection failed. Check input data, remove polish letters, to telephone number add prefix 48" + ex); }
 }
Exemple #7
0
        public void Start()
        {
            dtEmisores_UsuariosEN = SchoolManager.WhatsApp.LogicaNegocios.Emisores_UsuariosLN.DtEmisorActivoPorUsuario(Usuario, _prioridad);
            if (dtEmisores_UsuariosEN.Rows.Count == 0)
            {
                System.Windows.Forms.MessageBox.Show(string.Format("Usuario: {0}.- No hay emisor para enviar mensajes", Usuario));
                return;
            }
            _listen = true;
            wa      = new WhatsApp(dtEmisores_UsuariosEN.Rows[0]["EMISOR"].ToString(), dtEmisores_UsuariosEN.Rows[0]["APIKEY"].ToString(), dtEmisores_UsuariosEN.Rows[0]["NOMBREPERFIL"].ToString(), true);

            wa.OnLoginSuccess             += wa_OnLoginSuccess;
            wa.OnLoginFailed              += wa_OnLoginFailed;
            wa.OnGetMessage               += wa_OnGetMessage;
            wa.OnGetMessageReceivedClient += wa_OnGetMessageReceivedClient;
            wa.OnGetMessageReceivedServer += wa_OnGetMessageReceivedServer;
            wa.OnNotificationPicture      += wa_OnNotificationPicture;
            wa.OnGetPresence              += wa_OnGetPresence;
            wa.OnGetGroupParticipants     += wa_OnGetGroupParticipants;
            wa.OnGetLastSeen              += wa_OnGetLastSeen;
            wa.OnGetTyping                     += wa_OnGetTyping;
            wa.OnGetPaused                     += wa_OnGetPaused;
            wa.OnGetMessageImage               += wa_OnGetMessageImage;
            wa.OnGetMessageAudio               += wa_OnGetMessageAudio;
            wa.OnGetMessageVideo               += wa_OnGetMessageVideo;
            wa.OnGetMessageLocation            += wa_OnGetMessageLocation;
            wa.OnGetMessageVcard               += wa_OnGetMessageVcard;
            wa.OnGetPhoto                      += wa_OnGetPhoto;
            wa.OnGetPhotoPreview               += wa_OnGetPhotoPreview;
            wa.OnGetGroups                     += wa_OnGetGroups;
            wa.OnGetSyncResult                 += wa_OnGetSyncResult;
            wa.OnGetStatus                     += wa_OnGetStatus;
            wa.OnGetPrivacySettings            += wa_OnGetPrivacySettings;
            DebugAdapter.Instance.OnPrintDebug += Instance_OnPrintDebug;

            dtUltimaConexion = DateTime.Now;
            wa.Connect();
            //wa.Login();
            string datFile = getDatFileName(dtEmisores_UsuariosEN.Rows[0]["EMISOR"].ToString());

            if (File.Exists(datFile))
            {
                try
                {
                    string foo = File.ReadAllText(datFile);
                    nextChallenge = Convert.FromBase64String(foo);
                }
                catch (Exception) { };
            }
            wa.Login(nextChallenge);
            wa.SendGetServerProperties();

            thRecv = new System.Threading.Thread(t =>
            {
                try
                {
                    while (_listen)
                    {
                        wa.PollMessages();
                        System.Threading.Thread.Sleep(100);
                        continue;
                    }
                }
                catch (System.Threading.ThreadAbortException)
                {
                }
            })
            {
                IsBackground = true
            };
            thRecv.Start();

            if (_types != null && _types.Length > 0)
            {
                // Using only the XmlMessageFormatter. You can use other formatters as well
                _queue.Formatter = new XmlMessageFormatter(_types);
            }

            _queue.PeekCompleted    += new PeekCompletedEventHandler(OnPeekCompleted);
            _queue.ReceiveCompleted += new ReceiveCompletedEventHandler(OnReceiveCompleted);

            StartListening();
        }
        public void Start()
        {
            // registration if necessary
            string password = WhatsAppApi.Register.WhatsRegisterV2.RequestExist(PHONE);

            if (String.IsNullOrEmpty(password))
            {
                // register process
                string response = string.Empty;
                if (WhatsAppApi.Register.WhatsRegisterV2.RequestCode(PHONE, out password, out response, "sms"))
                {
                    Console.WriteLine("Response: [ " + response + " ]");
                    if (string.IsNullOrEmpty(password))
                    {
                        Console.Write("SMS sent. Enter code: ");
                        string code = Console.ReadLine();
                        password = WhatsAppApi.Register.WhatsRegisterV2.RegisterCode(PHONE, code, out response);
                        Console.WriteLine("Response: [ " + response + " ]");
                    }
                }
                else
                {
                    Console.WriteLine("Response: [ " + response + " ]");

                    Console.WriteLine("Trying to register by voice.");
                    if (WhatsAppApi.Register.WhatsRegisterV2.RequestCode(PHONE, out password, out response, "voice"))
                    {
                        Console.WriteLine("Response: [ " + response + " ]");
                        if (string.IsNullOrEmpty(password))
                        {
                            Console.Write("WhatsApp making a call. Enter code: ");
                            string code = Console.ReadLine();
                            password = WhatsAppApi.Register.WhatsRegisterV2.RegisterCode(PHONE, code, out response);
                            Console.WriteLine("Response: [ " + response + " ]");
                        }
                        else
                        {
                            Console.WriteLine("Cannot initiate register process (banned?)");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Response: [ " + response + " ]");
                    }
                }
            }

            if (string.IsNullOrEmpty(password))
            {
                Console.WriteLine("Cannot complete register process (invalid code / banned)");
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
                Environment.Exit(-1);
            }

            waClient = new WhatsApp(PHONE, password, "nickname", false);

            bool registered = File.Exists(datFilename);

            //WhatsApp.DEBUG = true;
            //WhatsApp.DEBUGOutBound = true;
            DebugAdapter.Instance.OnPrintDebug += (data) =>
            {
                Console.WriteLine(data);
            };

            waClient.OnError += (id, from, code, text) =>
            {
                Console.WriteLine("ERROR: id={0}, from={1}, code={2}, text={3}", id, from, code, text);
            };

            waClient.OnConnectSuccess += () =>
            {
                Console.WriteLine("Connected success");
            };

            waClient.OnConnectFailed += (ex) =>
            {
                Console.WriteLine("Connected failed: " + ex.Message);
            };

            waClient.OnLoginSuccess += (pn, data) =>
            {
                loggedIn = true;

                string sdata = Convert.ToBase64String(data);
                Console.WriteLine("Login success. Next token: {0}", sdata);
                try
                {
                    File.WriteAllText(datFilename, sdata);
                }
                catch (Exception) { }

                waClient.SendGetPrivacyList();
                waClient.SendGetClientConfig();

                if (waClient.LoadPreKeys() == null)
                {
                    waClient.sendSetPreKeys(true);
                }

                threadReceiver = new Thread(t =>
                {
                    while (waClient != null)
                    {
                        waClient.PollMessages();
                        Thread.Sleep(100);
                    }
                })
                {
                    IsBackground = true
                };

                threadReceiver.Start();
            };

            waClient.OnLoginFailed += (data) => {
                Console.WriteLine("Login failed. Reason: {0}", data);
            };

            waClient.Connect();

            byte[] nextChallenge = null;

            if (registered)
            {
                try
                {
                    string foo = File.ReadAllText(datFilename);
                    nextChallenge = Convert.FromBase64String(foo);
                }
                catch (Exception) { };
            }

            waClient.Login(nextChallenge);
        }