Sunday, February 7, 2021

Omegle BOT using python and Selenium

Omgele Bot cover
Designed by Freepik

Contents

  1. Introduction(Omegle bot using python and Selenium)
  2. Resources
  3. Source Code
  4. Explanation


Introduction:(Omegle bot using python)

Selenium is an open-source python module, it was developed for testing and to automate web-based tasks. It supports different browsers and several environments.
It allows the developers to test and perform tasks on the web-browsers with the help of the respective web drivers.

In this project, we are going to build our Omegle bot which can connect to the Omegle servers through google chrome and can send a particular message(promotional message) to the audience with common interests(interests can be hardcoded into the program or you can customize it in your own way).

To keep the project simple and beginner-friendly we haven't added the code for auto "ReCaptcha verification" the user has to verify it manually. Moreover, if the bot gets stuck in between then it will notify the user repeatedly until the issue is resolved manually.   


Resources:

Get the chrome driver from here.
Before proceeding further make sure you have added the selenium module to your project folder or have downloaded it into the system.

To download the selenium module using PIP(preferred installer program) run the following command in the terminal(Linux) or in command prompt(windows).

pip install selenium
Click here if the PIP command is not working.

import selenium
import time
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from plyer import notification
import msvcrt as m

#This method prompt notifications when ever it is called in the program
def notify():
    notification.notify(
        title='Bot requires Attention',
        message='Bot stuck',
        app_icon=None,  
        timeout=60, 
    )

# Enter driver path in the follwing line
# Code may note work if the driver path is incorrect
driver = webdriver.Chrome(r'C:\\Users\\Username\\Documents\\python\\chromedriver_win32\\chromedriver')
driver.get("https://www.omegle.com/")

#html elemnt names to find and interact with them 
Xpath_text_button = '//img[@id="textbtn"]'
Xpath_new_connect = '//button[@class="disconnectbtn"]'
Xpath_new_message = '//textarea[@class="chatmsg"]'
Xpath_sent_btn = '//button[@class="sendbtn"]'
tags_class_name = '//input[@class="newtopicinput" and @type="text"]'

msg= "enter the custom message here"
driver.get("https://www.omegle.com/")
tags_object = driver.find_elements_by_xpath(tags_class_name)
tags_object[0].send_keys("interest1\ninterest2\ninterest3\n") #Add your interests here followed by \n
time.sleep(2)
ignored_exceptions = (NoSuchElementException,StaleElementReferenceException,)

#find and click the text mode button on the page through xpath
text_mode_button = driver.find_element_by_xpath(Xpath_text_button)
text_mode_button.click()

# counter: counts the number people interacted with
counter = 0
# fail: number of failed attempts
fail = 0

#this message will pop up in the consol after the succesful initialization of the bot
print("Elements detected")
while True:
    try:
        new_connect_button = WebDriverWait(driver, 1000, ignored_exceptions=ignored_exceptions).until(
            expected_conditions.presence_of_element_located((By.XPATH, Xpath_new_connect)))
        sent_btn = driver.find_element_by_xpath(Xpath_sent_btn)
        if driver.find_element_by_class_name('chatmsg') == 0:
            print("chatmsg not found")
            new_connect_button.click()
            print("Clicked on new connection")
        else:

            new_message = WebDriverWait(driver, 1000, ignored_exceptions=ignored_exceptions).until(
                expected_conditions.presence_of_element_located((By.CLASS_NAME, "chatmsg")))
            time.sleep(2)
            new_message.send_keys(msg)
            sent_btn.click()
            time.sleep(1)
            new_connect_button.click()
            new_connect_button = WebDriverWait(driver, 1000, ignored_exceptions=ignored_exceptions).until(
                expected_conditions.presence_of_element_located((By.XPATH, Xpath_new_connect)))
            time.sleep(1)
            new_connect_button.click()
            counter += 1
            fail = 0
            print(counter)
            new_connect_button.click()
    except:
        #executs it when bot is stucked
        fail += 1
        if fail >= 20:
            notify()
            fail = 0
        new_connect_button.click()

    finally:
        continue

Explanation:

In the below snippet I have imported all of the required modules check selenium's official webpage to know their functionalities.
import selenium
import time
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from plyer import notification
import msvcrt as m

This function will show a popup in the windows notification section whenever it is called.
It uses the notify() method defines in plyer.notification and can take the **kwargs as per the requirements.
#This method prompt notifications when ever it is called in the program
def notify():
    notification.notify(
        title='Bot requires Attention',
        message='Bot stuck',
        app_icon=None,  
        timeout=60, 
    )

Setting up the driver inside the program by providing its location to the constructor.
Note: make sure that the path passed inside the constructor is valid.
# Enter driver path in the follwing line
# Code may note work if the driver path is incorrect
driver = webdriver.Chrome(r'C:\\Users\\Username\\Documents\\python\\chromedriver_win32\\chromedriver')
driver.get("https://www.omegle.com/")

Storing the required Xpaths so that we can use them to access the web elements whenever it is required
#html elemnt names to find and interact with them 
Xpath_text_button = '//img[@id="textbtn"]'
Xpath_new_connect = '//button[@class="disconnectbtn"]'
Xpath_new_message = '//textarea[@class="chatmsg"]'
Xpath_sent_btn = '//button[@class="sendbtn"]'
tags_class_name = '//input[@class="newtopicinput" and @type="text"]'
In the below section we are using the xpaths to find the 'interest input box' in order to set the custom interests to target a specific audience on omegle.
msg= "---------- Enter the custom message here---------------"
driver.get("https://www.omegle.com/")
tags_object = driver.find_elements_by_xpath(tags_class_name)
tags_object[0].send_keys("interest1\ninterest2\ninterest3\n") #Add your interests here followed by \n
time.sleep(2)
ignored_exceptions = (NoSuchElementException,StaleElementReferenceException,)
Similarly, we used the xpath to find and click the text mode button.
The variable counter stores the number of successful delivers and var fail stores the number of failed attempts.
#find and click the text mode button on the page through xpath
text_mode_button = driver.find_element_by_xpath(Xpath_text_button)
text_mode_button.click()

# counter: counts the number people interacted with
counter = 0
# fail: number of failed attempts
fail = 0

#this message will pop up in the consol after the succesful initialization of the bot
print("Elements detected")
The following while loop runs infinitely, connects to the stranger with common interests, and sends them the message that we have stored to the msg variable earlier.
if the connection is interrupted or the bot gets stuck due to 'robot verification' for 20 times then the notify function is called to tell the user. Further, the fail variable is reset.
Some of the wait methods are used to pause the bot and allow the webpage to load completely.
while True:
    try:
        new_connect_button = WebDriverWait(driver, 1000, ignored_exceptions=ignored_exceptions).until(
            expected_conditions.presence_of_element_located((By.XPATH, Xpath_new_connect)))
        sent_btn = driver.find_element_by_xpath(Xpath_sent_btn)
        if driver.find_element_by_class_name('chatmsg') == 0:
            print("chatmsg not found")
            new_connect_button.click()
            print("Clicked on new connection")
        else:

            new_message = WebDriverWait(driver, 1000, ignored_exceptions=ignored_exceptions).until(
                expected_conditions.presence_of_element_located((By.CLASS_NAME, "chatmsg")))
            time.sleep(2)
            new_message.send_keys(msg)
            sent_btn.click()
            time.sleep(1)
            new_connect_button.click()
            new_connect_button = WebDriverWait(driver, 1000, ignored_exceptions=ignored_exceptions).until(
                expected_conditions.presence_of_element_located((By.XPATH, Xpath_new_connect)))
            time.sleep(1)
            new_connect_button.click()
            counter += 1
            fail = 0
            print(counter)
            new_connect_button.click()
    except:
        #executs it when bot is stucked
        fail += 1
        if fail >= 20:
            notify()
            fail = 0
        new_connect_button.click()

    finally:
        continue