如何使用表格中的信息群發微信消息?
- 如何讀取csv? → 使用內置模塊csv
- 如何按對應信息發送到微信?→ 使用第三方庫wxpy
以下代碼素材自取:鏈接:https://pan.baidu.com/s/1nmzgCr_wwttWUgYwnc2eIg 提取碼:dwlw
import csv from wxpy import * import time # 運行代碼之前需要先將表格里的姓名換成你的朋友的微信名字。 def read_info(): f = open(r'F:\temp\Script_Day10/sample.csv','r',encoding='utf-8') reader = csv.DictReader(f) return [info for info in reader]#[{},{},{}] #'xx-同學請於 xx 時間參加 xx 課程,課程地址是 xxx。收到請回復,謝謝' def make_msg(raw_info): t = '{n}-同學請於{t}時間參加{s}課程,課程地址是{a}。收到請回復,謝謝!' return [t.format(n=info['姓名'], t=info['上課時間'], s=info['課程'], a=info['上課地址'] ) for info in raw_info] # -> list ['xxx','xxx'] def send(msg_list): bot = Bot() for msg in msg_list: fren_name = msg.split('-')[0] f = bot.friends().search(fren_name) # list if len(f) == 1: f[0].send(msg) else: print(fren_name) print('Please check this name') time.sleep(5) if __name__ == '__main__': raw_info = read_info() msg_list = make_msg(raw_info) send(msg_list)
現在要給4個人發送不同的邀請信息,銷售給了你一份 csv 名單,但名單里人是不全的,只有其中3個人。則需發送消息給名單上的人,打印不在名單上的那個人,代碼如下:
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/2/22 16:18 # @Author : xiaodai # coding:utf-8 import csv import time from wxpy import * # 將要發送的好友的名字存到list中 FRIENDS = ['王', '君', '姐', '小明'] CSV_PATH = r'F:\temp\upload_pic/MeetingMsg.csv' # 定義函數獲取csv中的內容 def read_csv(path): f = open(path, 'r', encoding='utf-8') reader = csv.DictReader(f) # print([info for info in reader]) return [info for info in reader] # 定義獲取發送內容的函數 def get_msg(infos, name): template = "{name},提醒下,{time}記得來參加{event},地點在{location},{note}" for info in infos: if info['微信昵稱'] == name: msg = template.format( name=info['微信昵稱'], time=info['時間'], event=info['事件'], location=info['地址'], note=info['備注'] ) return msg # 如果在infos列表中沒有找到對應的微信昵稱,則輸出None return None # 定義用於群發操作的函數 def send_to_friends(infos, friends): # 初始化微信機器人 bot = Bot() for friend in friends: # 搜素好友 friend_search = bot.friends().search(friend) # 如果搜索結果僅有一個,則發送圖片,否則返回錯誤信息 if len(friend_search) == 1: msg = get_msg(infos, friend) if msg: friend_search[0].send(msg) else: print("發送失敗!用戶名不在csv中:" + friend) else: print("發送失敗!請檢查用戶名:" + friend) time.sleep(3) # 調用群發函數 send_to_friends(read_csv(CSV_PATH), FRIENDS)
