首页 > 编程问答 >使用 pywhatkit 发送 Whatsapp 消息时出错

使用 pywhatkit 发送 Whatsapp 消息时出错

时间:2024-07-31 10:58:50浏览次数:7  
标签:python whatsapp pywhatkit

我的程序应该使用 pywhatkit 库通过语音识别获取用户的输入来发送whatsapp消息。

这是发送消息的功能。

def WhatsApp():
    speak("For Whom should i send message")
    Contacts = {
        'mom' : 63XXXXXXX,   # these are numbers (hidden)
        'karthik' : 75XXXXXXx,
        'me' : 81XXXXXXX,
        'jayaram' : 99XXXXXXXX
    }
    to = takeCommand() #takes my voice input using speech_recognition
    speak("what message should i send")
    msg = takeCommand()
    speak(f"sending message to {to}")
    try:
        pwt.sendwhatmsg_instantly(f"+91{Contacts[to]}",msg,5,True,15)
    except Exception as e:
        speak(f"error sending message")
        print(e) 

当我说发送whatsapp消息到我的语音助手时,它会问我要发送给谁以及应该发送什么消息。

我使用 pywhatkit 立即发送 Whatsapp 消息功能,以便消息可以快速发送,但它只是打开 Whatsapp 网页并返回。

我的问题:

  • Whatsapp网页正在打开并转到联系号码,我的消息将准备发送,但它不会发送我的消息并在一段时间后关闭选项卡。

注意:

  • 我还尝试更改关闭选项卡时间pwt.sendWhatmsg_instantly(a,b,c,d,closetab time) 的函数参数但没有使用结果是相同的。

请帮助我找到一种更好的方法来通过 pywhatkit 立即发送消息并解决错误。


此错误发生的原因是 WhatsApp Web 最近更新了安全协议。现在需要使用“pywhatkit.sendwhats_image”函数发送图像才能使代码正常工作。

以下是对代码的更正和解释:

import pywhatkit as pwt
import speech_recognition as sr
import pyttsx3

listener = sr.Recognizer()
engine = pyttsx3.init()

def speak(text):
    engine.say(text)
    engine.runAndWait()

def takeCommand():
    try:
        with sr.Microphone() as source:
            print("Listening...")
            listener.pause_threshold = 1  # Wait for 1 second after user stops speaking
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            print(f"You said: {command}")
            return command
    except sr.UnknownValueError:
        print("Sorry, I didn't understand.")
    except sr.RequestError as e:
        print(f"Could not request results from Google Speech Recognition service; {e}")
    return ""

def WhatsApp():
    speak("For whom should I send a message?")
    contacts = {
        'mom': 63XXXXXXX,   # these are numbers (hidden)
        'karthik': 75XXXXXXx,
        'me': 81XXXXXXX,
        'jayaram': 99XXXXXXXX
    }
    to = takeCommand()
    speak("What message should I send?")
    msg = takeCommand()
    speak(f"Sending message to {to}")
    try:
        # Replace 'image.png' with the actual path to your image
        pwt.sendwhats_image(f"+91{contacts[to]}", 'image.png', msg, 15, True, 5)
        speak("Message sent successfully!")
    except Exception as e:
        speak("Error sending message")
        print(e)

WhatsApp()

解释:

  1. 导入必要的库:
  2. pywhatkit 用于 WhatsApp 自动化
  3. speech_recognition 用于语音识别
  4. pyttsx3 用于文本转语音

  5. 初始化语音识别器和文本转语音引擎:

  6. listener = sr.Recognizer() 创建一个语音识别器对象。
  7. engine = pyttsx3.init() 初始化文本转语音引擎。

  8. 定义 speak 函数:

  9. 此函数接受文本作为输入并使用文本转语音引擎将其说出。

  10. 定义 takeCommand 函数:

  11. 此函数使用语音识别从用户那里获取语音输入,将其转换为文本,并返回该文本。

  12. 定义 WhatsApp 函数:

  13. 存储联系人及其电话号码的字典。
  14. 使用 takeCommand() 函数询问用户要向谁发送消息。
  15. 使用 takeCommand() 函数询问用户要发送什么消息。
  16. 使用 sendwhats_image() 函数发送消息。
    • 重要: 需要将 'image.png' 替换为的图像的实际路径。
  17. 包含错误处理以捕获发送消息时可能发生的任何异常。

  18. 调用 WhatsApp() 函数以启动该过程。

如何运行代码:

  1. 安装必要的库: pip install pywhatkit speechrecognition pyttsx3
  2. 将代码保存为 Python 文件(例如, whatsapp_message.py )。
  3. 在与代码文件相同的目录中放置一张图像(例如, image.png )。
  4. 运行代码: python whatsapp_message.py

这将启动语音助手,并提示说出要向谁发送消息以及要发送什么消息。

标签:python,whatsapp,pywhatkit
From: 75578301

相关文章

  • 如何在Google Colaboratory上导入并使用PyWhatKit?
    我想使用pywhatkit库自动从GoogleColab在WhatsApp上发送消息。到目前为止,我已经尝试过这样做:pipinstallpywhatkit输出:Requirementalreadysatisfied:pywhatkitin/usr/local/lib/python3.7/dist-packages(5.3)Requirementalreadysatisfied:wikipediain......
  • 使用 pywhatkit 发送 Whatsapp 消息但出现错误
    嘿,我是python编程新手,我正在尝试使用Pywhatkit在特定时间向特定号码发送Whatsapp消息。这是我的代码importpywhatkitpywhatkit.sendwhatmsg("anumber","Hi",0,43)这是我在运行此代码时收到的错误|||请帮我解决这个问题。PSD:\PROJECTS\python>pyth......
  • 三种语言实现二维前缀和(C++/Python/Java)
    题目输入一个n行m列的整数矩阵,再输入q个询问,每个询问包含四个整数x1,y1,x2,y2表示一个子矩阵的左上角坐标和右下角坐标。对于每个询问输出子矩阵中所有数的和。输入格式第一行包含三个整数n,m,q接下来n行,每行包含m个整数,表示整数矩阵。接下来q行,每行包含四个整数......
  • Python rocketMq 客户端的同步和异步模式
    同步模式fromrocketmq.clientimportPushConsumer,ConsumeStatusimporttimedefcallback(msg):print(msg.id,msg.body,msg.get_property('property'))returnConsumeStatus.CONSUME_SUCCESSdefstart_consume_message():consumer=PushCon......
  • python中元组的学习
    元组目录元组元组的概念元组操作元组的常用方法元组的遍历元组的概念Tuple(元组)与列表相似,不同之处遭遇元组的元素不能修改元组表示多个元素组成的序列用于储存一串信息,数据之间使用,分隔元组用()定义#元组的创建info_tuple=("zhangsan",18,1.75)info_tuple2=(1,)#......
  • 尝试通过Python访问.zip文件中的.gz文件
    我有一个包含大量.gz文件的.zip文件,我需要对其进行处理。我想打开.zip,我可以通过以下代码轻松完成:zf=zipfile.ZipFile("file.zip","r")forgzfileinzf.filelist:withgzip.GzipFile(fileobj=zf.open(gzfile.filename,"r"),mode="r")asf:df......
  • python导入包报错ImportError: cannot import name ‘Protocol‘
    python32.pyTraceback(mostrecentcalllast):File"2.py",line5,in<module>importptwt#use"fromsrcimportptwt"foraclonedtherepoFile"……lib/python3.6/site-packages/ptwt/_util.py",line2......
  • Python - Creating your own Iterator
    Inourfirstexample,wewillcreateiterableobjects,which,wheniteratedover,willgiveoutcubesofnumbers,andtheseobjectswillsupportmultipleiterations.classCubes:def__init__(self,start,stop):self.start=startsel......
  • 三种语言实现前缀和(C++/Python/Java)
    题目输入一个长度为n的整数序列。接下来再输入m个询问,每个询问输入一对l,r对于每个询问,输出原序列中从第l个数到第r个数的和。输入格式第一行包含两个整数n和m。第二行包含n个整数,表示整数数列。接下来m行,每行包含两个整数l和r,表示一个询问的区间范围。......
  • Python - 旨在通过命令提示符执行数据清理,但代码似乎无法运行
    我从一位同事那里收到了这段代码,我打算用它来处理100csv文件以提取有关粒子的值。代码如下所示:importsysimportcsv#Usage#skdata_decode.py[inputfile1][inputfile2]...#(Itispossibletousefiledcardtospecifyinputfiles.)##l......