Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python을 사용하는 Whatsapp?

<시간/>

이 섹션에서 우리는 Whatsapp 챗봇을 만들 것이지만 트위터나 페이스북을 위한 몇몇 다른 챗봇과 달리 whatsapp 챗봇은 whatsapp의 정책 때문에 플랫폼에서 직접 실행되지 않습니다.

그러나 개발자가 브라우저 활동을 자동화할 수 있는 매우 스마트한 파이썬 패키지인 셀레늄을 사용하여 완료하는 방법이 있습니다. 이를 통해 브라우저를 통해 whatsapp-web을 사용할 수 있습니다.

요구사항

작업을 완료하려면 세 가지 기본 요소가 필요합니다. 바로 셀레늄입니다.

pip를 사용하여 셀레늄을 매우 쉽게 설치할 수 있습니다. 터미널에서 아래 명령을 실행하기만 하면 됩니다 −

$pip install selenium
  • Chrome/firefox 또는 기타 웹 드라이버

    크롬 웹드라이버를 사용 중이므로 아래에 귀하의 OS에 따라 크롬 웹드라이버를 다운로드할 수 있는 링크가 있습니다.

  • https://chromedriver.storage.googleapis.com/index.html?path=2.46/

  • Whatsapp 계정.

    Whatsapp 계정을 만들지 않은 경우 계정이 있어야 합니다.

다음은 파이썬을 사용하여 특정 연락처에 Whatsapp 메시지를 보내는 간단한 프로그램입니다.

예시

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
import sys
# Replace below path with the absolute path of the \
#chromedriver in your computer
driver = webdriver.Chrome(r'c:\users\rajesh\Desktop\chromedriver')

driver.get("https://web.whatsapp.com/")
# time.sleep()
wait = WebDriverWait(driver, 600)
# Replace 'My Bsnl' with the name of your friend or group name
target = '"My Bsnl"'

# Replace the below string with your own message
string = sys.argv[1]

x_arg = '//span[contains(@title,' + target + ')]'
group_title = wait.until(EC.presence_of_element_located((
By.XPATH, x_arg)))
print (group_title)
print ("Wait for few seconds")
group_title.click()
message = driver.find_elements_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]')[0]

message.send_keys(string)
sendbutton = driver.find_elements_by_xpath('//*[@id="main"]/footer/div[1]/div[3]/button')[0]
sendbutton.click()
driver.close()

위의 스크립트를 명령 프롬프트에서 실행하고 메시지를 whatsapp 연락처에 인수로 전달해 보겠습니다-

>python whatsppPython.py "Hello"

DevTools listening on ws://127.0.0.1:12954/devtools/browser/a5bb04bd-66a3-4002-999f-6a0824f591da
<selenium.webdriver.remote.webelement.WebElement (session="83e7034b9a6f6b49e9e422e655f270d3", element="0.30994636046479007-1")>
after wait
….
…..

크롬 브라우저가 열리고 다음과 같은 화면이 나타납니다 -

Python을 사용하는 Whatsapp?

모바일 장치에서 whatsapp의 상단 표시줄에서 whatsapp 웹을 선택합니다. 화면에 나타나는 QR코드를 스캔하세요.

여기에서 우리의 경우 특정 연락처("My Bsnl")로 메시지가 전송되는 것을 볼 수 있습니다.

Python을 사용하는 Whatsapp?