itchat-python搭建微信机器人
2019-02-21 21:20
639 查看
itchat-python搭建微信机器人
itchat是python开源第三方库,用于搭建微信机器人,几十行代码就能帮你实现自动的处理所有信息。比如,添加好友,搭建自动回复机器人,还原撤销信息,分析好友男女比例,地理分布情况,爬朋友圈做数据分析…
本文只是简单实现聊天机器人,想了解更多关于itchat的用法请参照:https://itchat.readthedocs.io/zh/latest/
安装
pip install itchat
登录
itchat.auto_login(hotReload=True)
执行后会出现一个二维码,扫码登录。hotReload=True可以保留登录状态,以至于往后的重启程序可以跳过扫码登录。
消息类型
参数 | 类型 |
---|---|
TEXT | 文本 |
MAP | 位置 |
CARD | 名片 |
SHARING | 分享 |
PICTURE | 图片表情 |
RECORDING | 语音 |
ATTACHMENT | 附件 |
VIDEO | 小视频 |
发送消息
send(msg='text',toUserName=None)
msg:发送的内容
toUserName:发送对象,None表示自己内容类型:
图片:@img@img_path
视频:@vid@vid_path
文件:@fil@file_path
ps:接收到的附件路径一般默认存放在当前路径的msg[‘FileName’]下
注册会话监听
#TEXT:监听的消息类型 @itchat.msg_register(TEXT) def text_reply(msg): #过滤掉某人,NickName是昵称 if msg.User['NickName'] == 'xxx': pass else: # return_text = tuling(msg.text) #这种send方法会自己回复自己的消息 # msg.user.send(u'收到了') #只回复对方的消息 return u'收到了'
图灵聊天机器人
在图灵机器人官网(http://www.tuling123.com)注册账号,创建机器人,如果只是学习的话,可以使用免费版,一个账号最多可以创建5个机器人,一个机器人日调用接口数5000次。
#申请机器人后会拿到一个key key = '3c925fbee6f84ad2aa032ab05d4581b0' def tuling(info): url = "http://www.tuling123.com/openapi/api?key=%s&info=%s" % (key, info) r = requests.get(url) #返回消息 return r.json().get('text')
附上完整代码(文本图片群聊)
# coding: utf-8 # @Time : 2019/2/20 23:32 # @Author : lsn # @File : itchat_demo.py # @Software: PyCharm import itchat import requests from itchat.content import * key = '3c925fbee6f84ad2aa032ab05d4581b0' def tuling(info): url = "http://www.tuling123.com/openapi/api?key=%s&info=%s" % (key, info) r = requests.get(url) return r.json().get('text') @itchat.msg_register(TEXT) def text_reply(msg): if msg.User['NickName'] == 'xxx': pass else: return_text = tuling(msg.text) # msg.user.send(return_text) return return_text @itchat.msg_register( [PICTURE, RECORDING, ATTACHMENT, VIDEO]) def download_files(msg): print msg['Type'] print msg['FileName'] msg['Text'](msg['FileName']) return '@%s@%s' % ({'Picture': 'img', 'Video': 'vid'}.get(msg['Type'], 'fil'), msg['FileName']) @itchat.msg_register(TEXT, isGroupChat=True) def group_text_reply(msg): group_list = list() # 针对指定群回复 group_list.append(u'弹一弹') group_list.append(u'养生游戏分享') # 当然如果只想针对@你的人才回复,可以设置if msg['isAt']: if msg.User['NickName'] in group_list: return tuling(msg.text) else: pass itchat.auto_login(hotReload=True)itchat.run()
相关文章推荐
- 用python itchat写一个微信机器人自动回复
- 有了 itchat, python 调用微信个人号从未如此简单(新增 py3 支持)
- Python微信好友信息意义及取值分析(基于itchat)
- Python实现微信好友签名词云的构建(itchat、jieba、wordcloud)
- Python itchat模块在微信上的各种小应用
- python使用itchat发送微信消息提醒
- 使用python抓取微信好友个性签名并形成词云(itchat;wordcloud)
- python微信模块 itchat
- Python itchat模块在微信上的各种小应用
- python基于itchat实现微信群消息同步机器人
- 在python中使用itchat发送微信消息
- 使用Python itchat个人微信账号头像拼接
- Python itchat个人微信账号接口定时发送群消息
- Python利用itchat对微信中好友数据实现简单分析的方法
- python实现微信接口(itchat)详细介绍
- 在python中使用itchat发送微信消息
- itchat 实现微信智能机器人
- 利用python微信库itchat实现微信自动回复功能
- 在python中使用itchat发送微信消息
- python实现微信接口(itchat)