whatsapp рассылка сообщений скрипт python selenium
Whatsapp Automation with Selenium
Send messages to multiple people with just a few lines of Python Code
Do you ever wonder sending messages automatically by just running a simple python script? Yes, you heard it right, it can be done easily by using a package like selenium.
Selenium is a very smart package in python with which developers can automate the browser’s activity. With this, we can make use of Whatsapp-web through the browser and use it to automate message transfers.
Basic Requirement-
Procedure-
Step 1: Installing Selenium-
Selenium is used as browser Automation software. It can be installed using the following code on the terminal-
Step 2: Downloading Webdriver-
We will be using the Chrome web driver for automation. Download the chrome web driver from this link ( download the appropriate version as per your PC).
Extract the given file to the given location, as we will need the location later.
You can refer to this documentation for any doubts in downloading and setting it up.
Step 3: Install the open-source Chromium Web Browser-
Write the following code on the terminal to install the web browser.
The below code helps us to send Whatsapp text messages to the target user.
The above code imports the specific libraries. We use the browser as the object which uses the functionality of the chrome web driver and ‘ /usr/bin/chromedriver’ is the location of the web driver,
The wait object does the chrome driver to wait for 600ms. We use this for the web driver to load until the open the chrome driver opens for the automation.
The target variable assigns the name of the contact we are sending it and the string the content of the message. Now, x_arg is helped to find the particular target contact on the search box on WhatsApp web and at last, it did with function click() to maneuver to the particular contact.
The input_box finds the text box element (which can be found by right-clicking the mouse button and selecting the particular div class). Finally, we run a loop of a particular number for sending to the target.
Now when the web driver opens scan the QR code…
Simple Whatsapp Automation Using Python3 and Selenium
In my stories before (https://medium.com/@DeaVenditama/how-i-build-whatsapp-automation-tools-74f10c93e9b8) I tell you the general steps how to do it, now I will technically explain how to do it in code. I use Python 3 and Selenium in this tutorial, and I assume the reader knows the basics of Python.
First of all, we must have Python 3 installed; you can download it from https://www.python.org/ and follow the install instruction. After Python3 installed, install Selenium Automation Framework to automate all the things that we want to do later. I recommend using pip to install Selenium.
Selenium Hello World
After Selenium successfully installed, to test if it is correctly installed on your machine or not, run this Python code and check if there are any error messages.
Save this code in a file called automate.py or any python file name and then run it, it will show Google Chrome Window and automatically go to google.com.
Automate Whatsapp
copy the code above and paste it in automation.py, run it, and it will show a Whatsapp Web interface. Scan the QR code, wait until the loading is complete and press enter on the terminal/command prompt to continue the process to send the messages.
This is the explanation of Python code above,
these two lines of code is a Python variable to store the name of the contact and the messages.
It will open a Whatsapp Web interface which automatically asks you to scan the QR code, input() is used to pause the process until you press enter button in terminal.
the inp_xpath_search variable is an XPath path which used to find search input box. After the search box found it will click the search box, input the name of the contact and then enter it automatically.
Click the contact which found in the search result
Find the message text box, enter a message and press enter automatically
driver.quit() used to kill the instance of chromedriver or any driver you used, and if you don’t include this line, the process will always running in your computer memory.
Ok, this is the end of the tutorial, in next stories I will show you how to wrap the code in a Python class so you can use it more dynamic and reusable. Maybe I will cover some new feature like scraping contact or messages.
Thank you….
deepak3081996 / whatsapp.py
This comment has been minimized.
Copy link Quote reply
deathstalkr commented Jun 16, 2018
This is much better and user-friendly too. check this out
This comment has been minimized.
Copy link Quote reply
ravisharma00 commented Sep 6, 2018
This comment has been minimized.
Copy link Quote reply
ravisharma00 commented Sep 6, 2018
Pls Whatsapp +91 9785201393
This comment has been minimized.
Copy link Quote reply
abhi143u11 commented Oct 25, 2018
This is much better and user-friendly too. check this out
Hey I tried the above script and works like charm what if I want to send multiple people at the same time can you guide with that and also when the name has space it seems not detecting can you please check its my early days in learning python
This comment has been minimized.
Copy link Quote reply
webeyez commented Dec 6, 2018 •
This is much better and user-friendly too. check this out
This script is working, though you need to check and change the name of classes.
This comment has been minimized.
Copy link Quote reply
webeyez commented Dec 6, 2018
This is slightly improved version of Solomon code, it will keep you logged in.
This comment has been minimized.
Copy link Quote reply
madhavparikh99 commented May 14, 2020
I tried the code provided by the @webeyez and got stuck on the following error
NoSuchElementException: Message: no such element: Unable to locate element: <"method":"xpath","selector":"//span[@title = "vinee"]">(Session info: chrome=81.0.4044.138)
This comment has been minimized.
Copy link Quote reply
jashusr commented Mar 1, 2021
import pywhatkit as kit
import datetime
import sys
ask = input(»’do you want to send a scheduled message (y/n)
choose n if you want to send message now : »’)
while True:
if ask == «n»:
no = input(«enter the phone no with country code :»)
mess = input(«enter your message: «)
h = datetime.datetime.now().hour
m = datetime.datetime.now().minute + 1
This comment has been minimized.
Copy link Quote reply
harishkrishna10 commented Apr 30, 2021
How to implement this code, anyone suggest please iam trying to message to multiple whatsapp group members in a group
This comment has been minimized.
Copy link Quote reply
chanchalchhabra commented Jul 10, 2021 •
Hi. I need to send whatsapp messages(with and without attachments both) to unsaved contacts. Can you please share how can we do that?
I do not have much knowledge on this. I took code from one repository it was working fine few days ago but now the «Send» is not working. After lot of google search I understood looks like whtasapp might have done some html version changes so the the code which i have is not compatible with it. I tried to get the new Xpath for send button but no luck.
here is the code: I added print messages to trace the failure and I am getting this user defined message: Fail during click on send button.
The commented lines are the new Xpaths I picked from «inspect».
Thanks in advance for support.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Python-скрипт на 20 строк, который каждый день желает родителям доброго утра через WhatsApp
Автор материала, перевод которого мы сегодня публикуем, говорит, что современные люди, жизнь которых переполнена работой, часто забывают писать сообщения своим родным и близким. Он, глядя на то, как его родители каждое утро шлют ему в WhatsApp вдохновляющие цитаты и полезные советы о здоровье, решил, что пришло время ответить им взаимностью.
В этом руководстве мы напишем простой Python-скрипт, предназначенный для отправки WhatsApp-сообщений. В ходе работы будем пользоваться Python-пакетом Twilio. Для организации ежедневного запуска скрипта в заданное время разместим код в облаке.
Одним из подходов к решению этой задачи является использование Python-пакета Selenium и веб-версии WhatsApp вместо сервиса Twilio, на который, после исчерпания возможностей бесплатного предложения, нужно оформлять платную подписку. Но так как работа с веб-версией WhatsApp требует периодического сканирования QR-кода с помощью мобильного телефона, автоматизировать отправку сообщений при таком подходе не получится.
Работа над проектом будет состоять из трёх шагов:
Шаг 1. Настройка Twilio
Создадим бесплатную учётную запись на сайте Twilio, подтвердим адрес электронной почты и номер телефона.
Регистрация учётной записи Twilio
Кроме того, в рамках бесплатного предложения Twilio необходимо использовать WhatsApp-песочницу (WhatsApp Sandbox). Это означает, что вы не сможете пользоваться собственным номером телефона, и то, что вам придётся пройти через процедуру выдачи разрешения на получение WhatsApp-сообщений.
Собственным номером для работы с сообщениями можно пользоваться после того, как WhatsApp разрешит Twilio использовать ваш номер. Для того чтобы получить разрешение, нужно заполнить форму. Из материалов техподдержки Twilio можно узнать о том, что, хотя Twilio и работает напрямую с WhatsApp, на получение разрешения может понадобиться некоторое время. К тому же, там говорится об ограниченных масштабах выдачи разрешений. В результате многим приходится пользоваться WhatsApp-песочницей Twilio.
Всё это особой радости не вызывает, но то, что доступно нам в рамках бесплатного предложения Twilio, позволяет решить нашу задачу. Кроме того, получается, что WhatsApp-песочница — это пока единственный широкодоступный вариант.
Теперь нужно подключить телефон получателя сообщений к песочнице, после чего на этот телефон можно будет отправлять сообщения. Для того чтобы узнать о том, как это сделать, вам нужно перейти в раздел консоли Twilio, который посвящён WhatsApp. В частности, тут предлагается отправить WhatsApp-сообщение с указанным текстом на определённый номер.
Страница консоли Twilio с инструкциями по подключению телефона, на который можно будет отправлять сообщения
Запрос на подключение, отправленный с телефона
Сохраните выданный вам WhatsApp-номер в контактах. Ему можно назначить любое имя. Я, чтобы не усложнять себе жизнь, назвал этот контакт Twilio Sandbox, а потом отправил на него сообщение с телефона отца (это можно видеть на предыдущем рисунке). Эта процедура выполняется лишь один раз.
Теперь нужно перейти в консоль Twilio и получить SID и токен аутентификации для своей учётной записи. Эти данные помогут Twilio узнать вас при программной работе с сервисом.
Шаг 2. Изучение и модификация кода
Загрузите этот GitHub-репозиторий и распакуйте архив.
Здесь вы найдёте файл с исходным кодом ( whatsapp_messaging.py ) и пакет для развёртывания проекта ( aws_lambda_deploy.zip ).
Сейчас мы разберём этот код. Вот, для удобства, скриншот с пронумерованными строками.
Код файла whatsapp_messaging.py с пронумерованными строками
Шаг 3. Развёртывание проекта на AWS и настройка триггера
Для этого мы используем AWS Lambda — это бессерверная вычислительная среда, в которой можно размещать фрагменты кода, вызов которых, в соответствии с нуждами пользователя, инициируют различные события и триггеры. Наш код планируется запускать всего раз в день, поэтому использование чего-то вроде EC2-сервера на AWS, работающего круглосуточно, окажется пустой тратой вычислительных ресурсов и денег. Наша Lambda-функция будет вызываться ежедневно в определённое время по запросу из триггера, а её выполнение будет занимать совсем немного времени.
Начало создания Lambda-функции
Экран создания Lambda-функции
Нам нужно создать новое правило ( Rule ). Ему необходимо назначить имя ( Rule name ). При желании можно добавить к нему описание ( Rule description ).
Сведения о триггере
Сведения о Lambda-функции
Итоги
Сообщение, отправленное Python-скриптом
Мы завершили работу над проектом. Теперь можно, в телефоне получателя сообщений, в контактах WhatsApp, поменять имя контакта Twilio Sandbox на собственное (я поменял его на Son). Наша система, кроме того, позволяет общаться с получателем сообщений из панели управления Twilio.
Уважаемые читатели! Используете ли вы Twilio в своих проектах?
Скрипт для WhatsApp-сообщений в 20 строках кода Python
Sep 30, 2019 · 7 min read
В повседневной рутине мы часто забываем о близких. А ведь можно воспользоваться WhatsApp! То, с какой регулярностью родители шлют мне с утра пораньше сообщения — засыпая меня мудрыми цитатами и проявляя заботу о моём здоровье — не давало мне покоя, пока я не придумал, что с этим делать.
В данном руководстве мы напишем простой скрипт Python для отправки сообщений через WhatsApp. Делать мы это будем с помощью пакета Twilio. Чтобы запускать скрипт каждый день в определённое время, поместим наш код в облако AWS (Amazon Web Services).
Теперь можно начинать!
Одно из реш е ний — использовать пакет Selenium на Python и веб-версию WhatsApp, а не Twilio, так как в нем по окончании периода бесплатного использования надо оформлять платную подписку. Однако WhatsApp время от времени запрашивает сканирование QR-кода через мобильное устройство, поэтому автоматизация была бы невозможна.
Сделаем ее в три этапа:
Этап 1: начальная установка Twilio
Twilio was made for creators like you. We build our APIs to be simple to use, powerful in production, and endlessly…
Создаём бесплатный профиль на Twilio и подтверждаем адрес электронной почты и номер телефона.
Помимо бесплатного периода, в профиле Twilio предусмотрена тестовая среда Twilio Sandbox для WhatsApp, в которой нельзя использовать свой номер: чтобы получать сообщения по WhatsApp, нужно разовое разрешение.
Все проблемы решаются с получением номера — после того как WhatsApp разрешит Twilio использовать ваш номер. Далее надо заполнить форму и немного подождать.
Как получить номер WhatsApp Twilio для использования в рабочей среде?
Все клиенты Twilio могут создавать и тестировать отправку и получение сообщений WhatsApp с помощью тестовой среды WhatsApp Sandbox.
Чтобы использовать свой номер и шаблоны сообщений в Twilio, пример использования должен быть проверен и подтверждён со стороны WhatsApp. Twilio работает с подтверждениями для клиентов напрямую с WhatsApp. На начало 2019 доступность подтверждений ограничена и клиенты продолжают тестирования.
Может кого-то это и смущает, но не нас: наше решение с бесплатным периодом отлично справляется со своей задачей. К тому же сейчас это единственный способ.
Теперь нужно подключить телефон к тестовой среде WhatsApp Sandbox и можно начинать получать сообщения.
Перейдём к бета-версии WhatsApp в разделе обучения консоли.