如何使用表格中的信息群发微信消息?
- 如何读取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)