版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/CutelittleBo/article/details/71515006
微信消息关键字提醒
微信消息关键字提醒,获取微信消息,并匹配消息关键字,向邮箱发送带有关键字的消息
Github:https://github.com/sangbobo/WeChatKeyTips
初衷
现在用微信的越来越多,公司的一些通知也用微信来进行发送,无奈自己上微信的频率太低,又怕错过重要消息,所以才有了这个软件。
感谢 ItChat 提供的微信API接口
说明
需要python3.5版本进行运行
需要安装前置
pip install itchat
安装好后运行
python run.py
代码
# -*- coding: UTF-8 -*-
import json
import itchat, time
import smtplib
from itchat.content import *
from email.mime.text import MIMEText
from email.header import Header
# 加载配置信息
def load_config():
f = open("config.json", encoding='utf-8')
return json.load(f)
class WxMessage:
name = ''
type = ''
msg = ''
def __init__(self, name, type, msg):
self.name = name
self.type = type
self.msg = msg
# 获取配置信息
config = load_config()
mail_info = config['mail_info']
keys = config['keys']
# 第三方 SMTP 服务
mail_host = mail_info['host'] # 设置服务器
mail_user = mail_info['account'] # 用户名
mail_pass = mail_info['password'] # 口令
mg = WxMessage('', '', '')
sender = mail_info['sender']
receivers = mail_info['receivers'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
# 注册普通消息
@itchat.msg_register(TEXT)
def friend_msg(msg):
mg.name = msg.user.nickName
mg.type = "朋友"
mg.msg = msg.text
print_msg(mg)
# 注册群聊消息
@itchat.msg_register(TEXT, isGroupChat=True)
def group_msg(msg):
mg.name = msg.actualNickName
mg.type = msg.user.nickName
mg.msg = msg.text
print_msg(mg)
# 打印到的消息
def print_msg(mg):
message_info = "发送类型:" + mg.type + "\n" + "发送人:" + mg.name + "\n" + "内容:" + mg.msg + "\n"
for item in keys:
if item in mg.msg:
send_email(mg, message_info)
break
print_log(message_info)
# 如果匹配到消息,进行发送邮件
def send_email(mg, message_info):
message = MIMEText(message_info, 'plain', 'utf-8')
message['From'] = Header(mg.type, 'utf-8')
message['To'] = Header(mg.name, 'utf-8')
subject = mg.name
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP(mail_host, 25)
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
info = "邮件发送成功"
except smtplib.SMTPException as e:
info = e
print_log(info)
# 输出日志到log
def print_log(msg):
msg = "\n" + msg
f = open(config['log_path'], 'ab+')
f.write(msg.encode("utf-8"))
f.close()
# 登陆微信
itchat.auto_login(True)
# 运行
itchat.run(True)
配置信息
config.json
{
"mail_info": {
"host": "smtp服务器",
"account": "邮箱账号",
"password": "密码",
"sender": "发送者邮箱账号",
"receivers": "接受者邮箱账号"
},
"keys":["桑博","所有人","通知","大家","全体"],
"log_path":"out.txt"
}
记得开启邮件设置中的smtp
建议account 和 sender 和 receivers 都一致,自己给自己发邮件,不然有些服务商可能会把你的邮件当做垃圾邮件,导致发送失败。
keys是关键字列表,邮件会发送带有关键字的消息。
如果有什么问题,可以进行提问。
关于一些可能遇到的问题
在Linux上邮件发送失败
看看25邮件端口是发打开,如果没有打开使用命令
#打开发送邮件的服务器
service sendmail start
在Linux上进行登录的问题
命令行二维码
通过以下命令可以在登陆的时候使用命令行显示二维码:
itchat.auto_login(enableCmdQR=True)
部分系统可能字幅宽度有出入,可以通过将enableCmdQR赋值为特定的倍数进行调整:
如部分的linux系统,块字符的宽度为一个字符(正常应为两字符),故赋值为2
itchat.auto_login(enableCmdQR=2)
默认控制台背景色为暗色(黑色),若背景色为浅色(白色),可以将enableCmdQR赋值为负值:
itchat.auto_login(enableCmdQR=-1)