一个自动回复机器人
微信自上线以来,一直没有自动回复的功能,想必是有他们的理念。但是有些人群,确实对此功能有一定需求,我举两个栗子:
不愿时刻被消息打扰的人
消息需要批量处理的人们(比如微商)
对此,我设计了几个功能:
功能列表:
收到消息立即自动回复
收到消息延迟指定时间回复
对不同好友定制不同的回复内容
在手机端随时进行控制
#自动回复开关
SWITCH_REPLY=True
#延迟回复开关
SWITCH_DELAY=False
#延迟时间
DELAY_TIME=120
#消息前缀开关
SWITCH_PREFIX=True
#消息前缀内容
PREFIX_CONTENT="[自动回复]"
#回复内容字典
REPLY_DICT={}
#延迟回复字典
DELAY_REPLY_DICT={}
然后通过判断web端在”文件管理器“中接收到的字符串指令来进行不同操作,这一部分的代码比较简单且冗长,这里就不贴出来了,完整源码地址将会在文末给出。
假如此时我们收到了朋友的消息,需要程序给出自动回复。
#获取发送消息的朋友的信息
target_friend=itchat.search_friends(userName = msg['FromUserName'])
if target_friend:
#获取ta的昵称
nickName=target_friend['NickName']
if not REPLY_DICT.__contains__(nickName):
#设置默认回复
REPLY_DICT[nickName]="抱歉我有事暂未看到消息,稍后回复,若有急事可以电话联系(•ω•`)"
reply_content=REPLY_DICT[nickName]
#判断自动回复开关
if SWITCH_REPLY:
#判断延时回复开关
if SWITCH_DELAY:
localtime = time.time()
DELAY_REPLY_DICT[nickName]=[localtime,msg['FromUserName']]
print (DELAY_REPLY_DICT)
if not SWITCH_DELAY:
#判断消息前缀开关
if SWITCH_PREFIX:
reply_content = PREFIX_CONTENT + REPLY_DICT[nickName]
else:
reply_content = REPLY_DICT[nickName]
#发送消息
itchat.send(reply_content, toUserName=msg['FromUserName'])
收到朋友消息即时进行自动回复是很简单的,但是如何去做延时发送回复消息呢?(至于做这个功能有没有必要的问题可以先搁置,不过我认为在很多场景下是需要这个功能的,大家也可以在评论区讨论在什么场景下需要延迟自动回复)现在就回到技术的问题,如何实现可设置时间的延时自动回复。
#延迟发送消息的函数
def delay_reply():
#print("开始执行")
global DELAY_REPLY_DICT
if SWITCH_DELAY:
while len(DELAY_REPLY_DICT)>0:
localtime = time.time()
# print (localtime)
# print (DELAY_REPLY_DICT[item][0])
# print (int(DELAY_TIME))
for item in list(DELAY_REPLY_DICT.keys()):
if SWITCH_REPLY:
reply_content = item + "," + str(round(int(DELAY_TIME) / 60, 1)) + "分钟过去了," + REPLY_DICT[item]
itchat.send(reply_content, toUserName=DELAY_REPLY_DICT[item][1])
# print ("发送消息")
del DELAY_REPLY_DICT[item]
print (DELAY_REPLY_DICT)
global timer1
timer1=threading.Timer(DELAY_TIME,delay_reply)
timer1.start()
到此为止,主要的功能已经实现了,我用一个测试账号对我的微信进行了各种测试,看一下以下截图:
这时功能基本已经完成了
def keep_alive():
text="保持登录"
itchat.send(text, toUserName="filehelper")
global timer2
timer2 = threading.Timer(60*60,keep_alive)
timer2.start()
最后,我们需要将这个程序发布在服务器上,让它全天候为我的微信服务。
这里需要注意,如果仅用python xxxx.py
来运行的话,关闭shell会导致进程结束,所以我们需要使用nohup python xxxx.py &
来全方位守护进程
简单分析微信好友信息
性别比例
def get_sex():
# 获取好友数据
my_friends = itchat.get_friends(update=True)[0:]
sex = {"male": 0, "female": 0, "other": 0}
for item in my_friends[1:]:
s = item["Sex"]
if s == 1:
sex["male"] += 1
elif s == 2:
sex["female"] += 1
else:
sex["other"] += 1
total = len(my_friends[1:])
好友省级分布
def get_data(type):
result=[]
my_friends = itchat.get_friends(update=True)[0:]
for item in my_friends:
result.append(item[type])
return result
def friends_province():
# 获取好友省份
province= get_data("Province")
# 分类
province_distribution = {}
for item in province:
#删除英文省份,因为中国地图表中没有
if bool(re.search('[a-z]',item)):
continue
elif not province_distribution.__contains__(item):
province_distribution[item] = 1
else:
province_distribution[item] += 1
#将省份名为空的删除
province_distribution.pop('')
#提取地图接口需要的数据格式
province_keys=province_distribution.keys()
province_values=province_distribution.values()
return province_keys,province_values
if __name__ == '__main__':
itchat.auto_login(True)
微信好友省份分布
attr,value=friends_province()
map = Map("我的微信好友分布", "@寒食君",width=1200, height=600)
map.add("", attr, value, maptype='china', is_visualmap=True,
visual_text_color='#000')
map.render()
省内分布
def friends_jiangsu():
# 获取好友城市
city_distribution={}
city = get_data("City")
jiangsu_city=["南通市","常州市","淮安市","连云港市","南京市","苏州市","宿迁市","泰州市","无锡市","徐州市","盐城市","扬州市","镇江市"]
for item in city:
item=item+"市"
if item in jiangsu_city:
if not city_distribution.__contains__(item):
city_distribution[item]=1
else:
city_distribution[item]+=1
# 提取地图接口需要的数据格式
city_keys=city_distribution.keys()
city_values=city_distribution.values()
return city_keys,city_values
if __name__ == '__main__':
itchat.auto_login(True)
微信江苏好友分布
attr,value=friends_jiangsu()
map = Map("江苏好友分布","@寒食君", width=1200, height=600)
map.add("", attr, value, maptype='江苏', is_visualmap=True,
visual_text_color='#000')
map.render()
个性签名词云
def friends_signature():
signature = get_data("Signature")
wash_signature=[]
for item in signature:
#去除emoji表情等非文字
if "emoji" in item:
continue
rep = re.compile("1f\d+\w*|[<>/=【】『』♂ω]")
item=rep.sub("", item)
wash_signature.append(item)
words="".join(wash_signature)
wordlist = jieba.cut(words, cut_all=True)
word_space_split = " ".join(wordlist)
coloring = np.array(Image.open("C:/Users/casua/Desktop/test1.JPG"))
my_wordcloud = WordCloud(background_color="white", max_words=800,
mask=coloring, max_font_size=80, random_state=30, scale=2,font_path="C:/Windows/Fonts/STKAITI.ttf").generate(word_space_split)
image_colors = ImageColorGenerator(coloring)
plt.imshow(my_wordcloud.recolor(color_func=image_colors))
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()
基操 勿6 皆坐 观之
完整代码
import itchat
from pyecharts import Bar,Pie,Geo,Map
import re
import jieba
import matplotlib.pyplot as plt
from wordcloud import WordCloud, ImageColorGenerator
import numpy as np
import PIL.Image as Image
def get_sex():
# 获取好友数据
my_friends = itchat.get_friends(update=True)[0:]
sex = {"male": 0, "female": 0, "other": 0}
for item in my_friends[1:]:
s = item["Sex"]
if s == 1:
sex["male"] += 1
elif s == 2:
sex["female"] += 1
else:
sex["other"] += 1
total = len(my_friends[1:])
# 开始画饼
attr = list(sex.keys())
v1 = list(sex.values())
pie = Pie("好友性别比例")
pie.add("", attr, v1, v1, is_label_show=True)
pie.render()
def get_data(type):
result=[]
my_friends = itchat.get_friends(update=True)[0:]
for item in my_friends:
result.append(item[type])
return result
def friends_province():
# 获取好友省份
province= get_data("Province")
# 分类
province_distribution = {}
for item in province:
#删除英文省份,因为中国地图表中没有
if bool(re.search('[a-z]',item)):
continue
elif not province_distribution.__contains__(item):
province_distribution[item] = 1
else:
province_distribution[item] += 1
#将省份名为空的删除
province_distribution.pop('')
#提取地图接口需要的数据格式
province_keys=province_distribution.keys()
province_values=province_distribution.values()
return province_keys,province_values
def friends_jiangsu():
# 获取好友城市
city_distribution={}
city = get_data("City")
jiangsu_city=["南通市","常州市","淮安市","连云港市","南京市","苏州市","宿迁市","泰州市","无锡市","徐州市","盐城市","扬州市","镇江市"]
for item in city:
item=item+"市"
if item in jiangsu_city:
if not city_distribution.__contains__(item):
city_distribution[item]=1
else:
city_distribution[item]+=1
# 提取地图接口需要的数据格式
city_keys=city_distribution.keys()
city_values=city_distribution.values()
return city_keys,city_values
def friends_signature():
signature = get_data("Signature")
wash_signature=[]
for item in signature:
#去除emoji表情等非文字
if "emoji" in item:
continue
rep = re.compile("1f\d+\w*|[<>/=【】『』♂ω]")
item=rep.sub("", item)
wash_signature.append(item)
words="".join(wash_signature)
wordlist = jieba.cut(words, cut_all=True)
word_space_split = " ".join(wordlist)
coloring = np.array(Image.open("C:/Users/casua/Desktop/test1.JPG"))
my_wordcloud = WordCloud(background_color="white", max_words=800,
mask=coloring, max_font_size=80, random_state=30, scale=2,font_path="C:/Windows/Fonts/STKAITI.ttf").generate(word_space_split)
image_colors = ImageColorGenerator(coloring)
plt.imshow(my_wordcloud.recolor(color_func=image_colors))
plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()
if __name__ == '__main__':
itchat.auto_login(True)
# city=get_data("City")
# province=get_data("Province")
# signature=get_data("Signature")
# nickname=get_data("NickName")
# 微信好友省份分布
# attr,value=friends_province()
# map = Map("我的微信好友分布", "@寒食君",width=1200, height=600)
# map.add("", attr, value, maptype='china', is_visualmap=True,
# visual_text_color='#000')
# map.render()
微信江苏好友分布
attr,value=friends_jiangsu()
map = Map("江苏好友分布","@寒食君", width=1200, height=600)
map.add("", attr, value, maptype='江苏', is_visualmap=True,
visual_text_color='#000')
map.render()
# friends_signature()
∞∞∞∞∞
公众号回复“Python”,
邀你加入{ IT派Python技术群 }