如何使用Google API在Python中连接Google联系人并集成至AI发WhatsApp消息
实现方案:Python连接Google联系人+WhatsApp消息发送集成
一、连接Google联系人API
1. 准备工作与依赖安装
- 在Google Cloud控制台创建项目,启用People API
- 创建OAuth 2.0客户端ID,下载
credentials.json到项目目录 - 安装所需依赖库:
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib pandas
2. 编写代码获取Google联系人
import os import pickle from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from googleapiclient.discovery import build # 只读联系人的权限范围 SCOPES = ['https://www.googleapis.com/auth/contacts.readonly'] def get_google_contacts(): creds = None # 读取已保存的授权token,避免重复验证 if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # 无有效凭据时重新授权 if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # 保存token供后续使用 with open('token.pickle', 'wb') as token: pickle.dump(creds, token) # 调用People API获取联系人 service = build('people', 'v1', credentials=creds) results = service.people().connections().list( resourceName='people/me', pageSize=1000, personFields='names,phoneNumbers').execute() connections = results.get('connections', []) # 整理为姓名-手机号的字典 contacts = {} for person in connections: names = person.get('names', []) phones = person.get('phoneNumbers', []) if names and phones: name = names[0].get('displayName') # 去除手机号中的空格、横杠等符号 phone = phones[0].get('value').replace(' ', '').replace('-', '') contacts[name] = phone return contacts
二、整合本地Excel联系人与Google联系人
基于你已有的Excel读取逻辑,合并两个联系人数据源:
import pandas as pd # 读取Excel联系人(复用你现有代码逻辑) def get_excel_contacts(excel_path): df = pd.read_excel(excel_path) # 假设Excel列名为'姓名'和'手机号',可根据实际调整 excel_contacts = dict(zip(df['姓名'], df['手机号'])) return excel_contacts # 合并联系人:Google联系人会覆盖Excel中重复姓名的条目 excel_contacts = get_excel_contacts('your_contacts.xlsx') google_contacts = get_google_contacts() all_contacts = {**excel_contacts, **google_contacts}
三、通过WhatsApp发送消息(基于pywhatkit)
使用pywhatkit实现无API密钥的便捷消息发送,依赖Chrome浏览器:
1. 安装依赖
pip install pywhatkit
2. 发送消息代码
import pywhatkit import time def send_whatsapp_message(phone_number, message): # 统一手机号格式为+国家区号开头(如+8613xxxxxxxxx) if not phone_number.startswith('+'): phone_number = '+86' + phone_number # 根据你的地区调整区号 try: # 等待10秒后发送(给Chrome启动时间),发送后自动关闭标签页 pywhatkit.sendwhatmsg_instantly(phone_number, message, wait_time=10, tab_close=True) print(f"消息已发送至{phone_number}") # 增加间隔避免频繁发送被限制 time.sleep(15) except Exception as e: print(f"发送失败:{str(e)}") # 示例:遍历所有联系人发送AI生成的消息 for name, phone in all_contacts.items(): # 这里替换为你的AI模型生成的消息内容 ai_generated_message = f"你好{name},这是AI模型发送的定制消息!" send_whatsapp_message(phone, ai_generated_message)
四、集成到AI模型的关键要点
- 将
all_contacts作为全局变量或传入AI模型的处理函数,让AI可按需选择目标联系人 - 直接将AI生成的文本内容传入
send_whatsapp_message的message参数即可完成消息发送 - 批量发送时建议添加异常捕获与重试机制,避免单条发送失败中断整个流程
内容的提问来源于stack exchange,提问作者Kumar Ayush
相关产品推荐
相关产品推荐

