首页 > 解决方案 > 如何使用 Python 在 Whatsapp 上自动发送 mp3 文件

问题描述

下面的代码使用 pyautogui 库自动将 mp3 文件发送给 WhatsApp 联系人。它确实适用于 Windows 10。使用的浏览器是 Brave。

pyautogui 库可以对鼠标的移动进行编程。根据您电脑的屏幕大小和您使用的浏览器,您将不得不更改鼠标定位的 x 、 y 像素坐标(pyautogui.click(x, y) 函数。获得正确的坐标非常容易:您使用函数 pyautogui.position() 获取当前鼠标 x, y 坐标。要了解如何使用 pyautogui.position(),您可以观看此短视频:https ://www.youtube.com/watch?v=xVR -8xuBp3k&t=38s

这是代码,需要 pip install pyautogui。

import webbrowser
import pyautogui
import time

# The browser used is Brave on Windows 10. According to your PC,
# you may have to alter the click() coordinates. Watch this video
# to understand how pyautogui is used to get the mouse position:
# https://www.youtube.com/watch?v=xVR-8xuBp3k&t=38s
#
# Then, use pyautogui_get_position.py to get the mouse positions ...

whatsAppUrl = 'https://web.whatsapp.com/'
contactTargetName = '822' # part of target phone number
message = 'Hello, I send you an audio file ...'
attachmentFilePathName = r'D:\Users\Jean-Pierre\Downloads\Audiobooks\Various\Wear a mask. Help slow the spread of Covid-19._1.mp3'

webbrowser.open(whatsAppUrl)
time.sleep(5)

# click on contact search field
pyautogui.click(152, 247)

# select the targer contact
pyautogui.typewrite(contactTargetName)
time.sleep(2)

# activate the targer contact
pyautogui.click(202, 468)
time.sleep(1)

# send text message before sending the audio file
pyautogui.click(988, 1395)
pyautogui.typewrite(message)
pyautogui.click(2105, 1390)

# click on attachment icon
pyautogui.click(894, 1385)

# click on photo/video icon. Sending audio works if it is sent as a photo
# or video !
time.sleep(0.5)
pyautogui.click(894, 1268)

# enter attachment file path name
time.sleep(0.5)
pyautogui.typewrite(attachmentFilePathName)

# click on Open button
pyautogui.click(795,776)

# click on Send icon
print('Time sleeping for 20 seconds to make sure the audio file is uploaded ...')
time.sleep(20)
pyautogui.click(2060,1203)

标签: python-3.xwhatsapppyautogui

解决方案


推荐阅读