Automation Whatsapp With Selenium C#

Introduction

In this article, we will learn how to automate the Whatsapp web using Selenium with C#. In this article, we have access to the QR code and send the message using selenium automation.

Let's start the code.

I am using VS Code Window Services.

Step 1

Create a new Window services Project.

Automation Whatsapp With Selenium C#

Now give the Project Name, I have given the name Whatsapp_Demo. 

Step 2

Change the Service1.cs name to Whatsapp_Demo.cs

Step 3

Open Program.cs and change the code.

using System.Threading;
static void Main() {
    #if DEBUG
    Whatsapp_Demo relnServ = new Whatsapp_Demo();
    relnServ.OnDebug();
    Thread.Sleep(Timeout.Infinite);
    #else
    if (args != null && args.Length > 0 && args[0] == "-startAsConsole") {
        Whatsapp_Demo relnServ = new Whatsapp_Demo();
        relnServ.OnDebug();
        //Thread.Sleep(Timeout.Infinite);
    } else {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] {
            new Whatsapp_Demo()
        };
        ServiceBase.Run(ServicesToRun);
    }
    #endif
}

Step 4:

Install Nuget Package of Selenium.WebDriver

Step 5

Download the chromedriver.exe using this URL Chrome driver

I have downloaded the 101.0.4951.41 you can check the version of your chrome web browser. 

You just copy the downloaded chromedriver.exe  to Project bin debug folder

Automation Whatsapp With Selenium C#

Step 6

Now open Whatsapp_Demo.cs and enter F7 the .cs file open. 

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Whatsapp_Demo {
    public partial class Whatsapp_Demo: ServiceBase {
        Thread mainServiceThread = null;
        ServiceController sc = new ServiceController("Whatsapp_Demo");
        ManualResetEvent eventForConsoleStart = new ManualResetEvent(false);
        IWebDriver driver = new ChromeDriver();
        public static string logininfo = "";
        public Whatsapp_Demo() {
            InitializeComponent();
        }
        public void Main() {
            while (true) {
                run();
            }
            eventForConsoleStart.WaitOne();
        }
        public void run() {
            var currenturl = driver.Url;
            if (currenturl.Contains("web.whatsapp.com") == false) {
                driver.Navigate().GoToUrl("https://web.whatsapp.com");
            }
            Console.WriteLine("Login to WhatsApp Web Scan The QR CODE From Browser");
            if (logininfo != "LOGIN") {
                CheckLoggedIn();
            } else if (logininfo == "LOGIN") {
                SendMessage();
            }
        }
        public void CheckLoggedIn() {
            Thread.Sleep(5000);
            var checked1 = driver.FindElements(By.XPath("//*[@id='app']/div/div/div[2]/div[1]/div/div[2]/div")).SingleOrDefault();
            if (checked1 == null) {
                logininfo = "LOGIN";
            } else {
                logininfo = "NOTLOGIN";
            }
        }
        public void SendMessage() {
            driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(4);
            var checked1 = driver.FindElements(By.XPath("//*[@id='app']/div/div/div[2]/div[1]/div/div[2]/div")).SingleOrDefault();
            if (checked1 == null) {
                Console.WriteLine("ENTER THE MOBILE NUMBER ");
                var mobile = Console.ReadLine();
                mobile = "91" + mobile;
                Console.WriteLine("ENTER THE MESSAGE ");
                var msg = Console.ReadLine();
                driver.Navigate().GoToUrl("https://web.whatsapp.com/send?phone=" + mobile + "&text=" + Uri.EscapeDataString(msg));
                Thread.Sleep(2000);
                var errormsg = driver.FindElements(By.XPath("//*[@id='app']/div/span[2]/div/span/div/div/div/div/div/div[2]/div/div/div/div")).SingleOrDefault();
                if (errormsg != null) {
                    Thread.Sleep(2000);
                    var messageshow = driver.FindElement(By.XPath("//*[@id='app']/div/span[2]/div/span/div/div/div/div/div/div[1]")).Text;
                    Console.WriteLine("Message Failed Due To " + messageshow);
                } else {
                    driver.FindElement(By.XPath("//*[@id='main']/footer/div[1]/div/span[2]/div/div[2]/div[2]/button")).Click(); //Click SEND Arrow Button
                    Console.WriteLine("Message Send Successfully ");
                }
            } else {
                logininfo = "NOTLOGIN";
            }
        }
        public void OnDebug() {
            OnStart(null);
            mainServiceThread.Join();
        }
        protected override void OnStart(string[] args) {
            mainServiceThread = new Thread(Main);
            mainServiceThread.IsBackground = false;
            mainServiceThread.Start();
        }
        protected override void OnStop() {
            try {
                sc.Stop();
                var timeout = new TimeSpan(0, 0, 20);
                sc.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
            } catch (Exception ex) {
                EventLog.WriteEntry("Whatsapp service : " + ex.Message);
            } finally {
                eventForConsoleStart.Set();
            }
        }
    }
}

Before starting the testing you should have changed the Project output type window application to console application.

To change the project output go to project property, you have shown the output type. 

The coding part is done now to debug the project. After debugging the project a chrome browser opens, and in the browser WhatsApp web opens.

Now you have to scan the QR code using WhatsApp.

After scanning the QR Code the web Whatsapp login now comes to the Console you have entered the mobile.

Automation Whatsapp With Selenium C#

and enter the message. Now the message sends successfully. 

Conclusion

In the article, we have seen how to send messages to any number using web WhatsApp.

HAPPY CODING.  


Similar Articles