无意中看到GitHub上的大佬给女朋友写的每日定时发送微信消息的程序,想到自己经常也因为各种事情没看到女朋友的消息,导致自己跪搓衣板,所以想自己也学习一下如何实现一个微信自动回复的功能,顺便学习学习。 本程序功能较为简单,运行程序,输入要自动回复对象的微信备注名和要自动回复的内容,然后登录微信,即可实现对指定对象的消息自动回复。 程序中主要用到了itchat这个库,它是一个基于微信网页版的接口微信库,可以实现对微信的各种操作。
》Python学习交流群:835017344,这里是python学习者聚集地,有大牛答疑,有资源共享!有想学习python编程的,或是转行,或是大学生,还有工作中想提升自己能力的,正在学习的小伙伴欢迎加入学习。
实现功能
查询日期;查询天气;机器人聊天。
配置环境及依赖
语言:
<pre class="hljs nginx" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">Python 3.5 及以上
复制代码</pre>
依赖库:
<pre class="hljs nginx" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">itchat
datetime
requests
复制代码</pre>
天气查询API:
<pre class="prettyprint hljs awk" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">http://t.weather.sojson.com/api/weather/city/{city_code}
复制代码</pre>
聊天机器人:
<pre class="hljs less" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">图灵机器人 http://www.turingapi.com
复制代码</pre>
程序说明
获取天气信息
这里主要参考了https://github.com/sfyc23/EverydayWechat这位大神的方法,用了一个存有全国格城市对应代码的列表,根据城市代码在接口中查询对应天气状况。
<pre class="prettyprint hljs python" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">def isJson(resp):
try:
resp.json()
return True
except:
return False
获取天气信息
def get_weather_info(city_code):
weather_url = f'http://t.weather.sojson.com/api/weather/city/{city_code}'
resp = requests.get(url=weather_url)
if resp.status_code == 200 and isJson(resp) and resp.json().get('status') == 200:
weatherJson = resp.json()
# 今日天气
today_weather = weatherJson.get('data').get('forecast')[1]
# 温度
high = today_weather.get('high')
high_c = high[high.find(' ') + 1:]
low = today_weather.get('low')
low_c = low[low.find(' ') + 1:]
temperature = f"温度 : {low_c}/{high_c}"
# 空气指数
aqi = today_weather.get('aqi')
aqi = f"空气质量 : {aqi}"
# 天气
tianqi = today_weather.get('type')
tianqi = f"天气 : {tianqi}"
today_msg = f'{tianqi}\n{temperature}\n{aqi}\n'
return today_msg
复制代码</pre>
图灵机器人接口
这里用到的是http://www.turingapi.com这里的图灵机器人,只需要在网站注册并创建机器人,获得每个用户独有的"userId"和每个机器人独有的"apiKey",根据其要求的请求参数,向其接口http://openapi.tuling123.com/openapi/api/v2请求数据即可。
示例:
<pre class="prettyprint hljs python" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">#图灵机器人接口
def robot(info):
#info = msg['Content'].encode('utf8')
# 图灵API接口
api_url = 'http://openapi.tuling123.com/openapi/api/v2'
# 接口请求数据
data = {
"reqType": 0,
"perception": {
"inputText": {
"text": str(info)
}
},
"userInfo": {
"apiKey": "XXX...XXX", #每个机器人独有的apiKey
"userId": "XXXXXX" #每个用户独有的userId
}
}
headers = {
'Content-Type': 'application/json',
'Host': 'openapi.tuling123.com',
'User-Agent': 'Mozilla/5.0 (Wi`ndows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3486.0 '
'Safari/537.36 '
}
# 请求接口
result = requests.post(api_url, headers=headers, json=data).json()
# 提取text,发送给发信息的人
return result['results'][0]['values']['text']
复制代码</pre>
上面一段程序输入info,通过接口返回机器人的回复。
itchat微信微信接口
itchat官方文档: itchat.readthedocs.io itchatGitHub网址: github.com/littlecoder… 它通过一个装饰器实现对微信消息的监听:
<pre class="hljs css" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">@itchat.msg_register(itchat.content.TEXT)
复制代码</pre>
其中,括号内为itchat监听的消息类型,TEXT表示对文字内容进行监听,此外itchat还支持多种消息类型,如: MAP 地理位置的分享 CARD 名片信息 SHARING 链接分享 PICTURE 表情或照片 RECORDING 语音 ATTACHMENT 附件 VIDEO 视频 FRIENDS 加好友申请,也就是说发起的一个好友申请其实是一条特殊的信息 SYSTEM 系统消息,比如系统推送消息或者是某个群成员发生变动等等 NOTE 通知文本,比如撤回了消息等等 然后通过使用:
<pre class="hljs less" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">itchat.send(text, toUserName=userName)
复制代码</pre>
向指定对象回复消息。其中的userName并不是微信名,是一串数字字母的代码,所以我们可以从刚才监听获取的消息中得到向我们发送消息的对象的userName,即:
<pre class="hljs markdown" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">userName = msg['User']['UserName']
复制代码</pre>
然后我们可以用:
<pre class="hljs markdown" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">msg['User']['RemarkName']
复制代码</pre>
来通过对对象的微信备注名的对比来判断是否是女朋友,是否是我们要回复的对象。我这里只能有一个对象,当然有些人可能有多个女朋友的,容我献上自己的双膝。。。
回复代码示例:
<pre class="prettyprint hljs python" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">@itchat.msg_register([itchat.content.TEXT,itchat.content.PICTURE])
def reply_msg(msg):
global t, name, rtext
userName = msg['User']['UserName']
if t == 2:
if msg['User']['RemarkName'] == name:
if msg['Content'] == "退出":
itchat.send("机器人已退出", toUserName=userName)
t = 0
else:
text = msg['Content']
rep = robot(text)
itchat.send(rep+"\n回复“退出”,退出机器人聊天", toUserName=userName)
elif t == 1:
if msg['User']['RemarkName'] == name:
ctn = msg['Content']
if ctn in city_dict.city_dict:
city_code = city_dict.city_dict[ctn]
wheather = get_weather_info(city_code)
itchat.send(wheather, toUserName=userName)
else:
itchat.send("无法获取您输入的城市信息", toUserName=userName)
t = 0
else:
if msg['User']['RemarkName'] == name:
if msg['Content'] == '你好':
itchat.send('你好', toUserName=userName)
elif msg['Content'] == '天气':
itchat.send('请输入您要查询的城市名', toUserName=userName)
t = 1
elif msg['Content'] == '日期':
itchat.send(nowdate, toUserName=userName)
elif msg['Content'] == '聊天':
itchat.send('你好,我是人工智障', toUserName=userName)
t = 2
else:
itchat.send(rtext + ',自动消息\n回复“日期”,获取日期\n回复“天气”,获取天气\n回复“聊天”,开始和机器人聊天', toUserName=userName)
复制代码</pre>
这样我们就可以对指定对象实现自动回复,并且实现简单的获取日期、天气和机器人聊天的功能。关于itchat我也是刚接触,讲得不详细,具体更多指导内容可以详见上面的官方文档和GitHub链接。
项目地址
小结
很简单的一个小项目,几乎没什么技术含量,可以拿来练练手,也可以在这上面丰富其它更多有意思的东西,也算是每天学习进步一点点哈哈,提升自己的姿势水平。
网友评论