You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3语音助手if/elif分支不识别发送WhatsApp消息指令问题求助

问题根因分析

核心问题出在条件判断的语法错误,Python支持链式比较规则,你写的if 'dad' in rec == True:会被解释器解析为if ('dad' in rec) and (rec == True):,而存储语音识别结果的rec变量是字符串类型,不可能等于布尔值True,所以这个判断永远不成立,自然无法进入对应分支。

修复方案

直接去掉判断里多余的== True即可,另外还可以做两个优化点:

  • 替换前缀的时候匹配完整的指令前缀,避免替换掉消息内容里偶然出现的message to xx字段
  • 对提取出来的消息内容做前后空格去除,避免多余空白

修复后的代码片段如下:

elif 'send message to ' in rec:
    if 'dad' in rec:
        # 完整替换指令前缀,去除前后多余空白
        msj = rec.replace('send message to dad', '').strip()
        talk('Sending message to dad...' + msj)
        print(dad, msj)
        pywhatkit.sendwhatmsg_instantly(dad, msj, 20)
    elif 'mom' in rec:
        msj = rec.replace('send message to mom', '').strip()
        talk('Sending message to mom...' + msj)
        print(mom, msj)
        pywhatkit.sendwhatmsg_instantly(mom, msj, 20)
其他可选优化

如果后续要扩展更多联系人,还可以用字典存储联系人映射,避免写重复的分支逻辑,示例如下:

# 提前定义联系人映射,key是指令里的名字,value是号码
contact_map = {
    'dad': dad,
    'mom': mom
}
elif 'send message to ' in rec:
    for name, phone in contact_map.items():
        if name in rec:
            msj = rec.replace(f'send message to {name}', '').strip()
            talk(f'Sending message to {name}...' + msj)
            print(phone, msj)
            pywhatkit.sendwhatmsg_instantly(phone, msj, 20)
            break

内容的提问来源于stack exchange,提问作者Joaqho C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 19:45:05