本教程的作用
零基础手把手教你打造一款微信机器人, 包括好友聊天自动回复和群聊助手两个部分, 零基础! 话不多说, 下面开始实战编码.
第一部分: 好友聊天自动回复
第一步, 安装 python 环境.
打开 python 官网 https://www.python.org/downloads/ , 下载与你的电脑系统相匹配的 python 发行版本, 推荐 python3.5-python3.6, 版本太高了可能有许多未知的 bug, 太低了兼容性不太好.
第二步, 安装 itchat 库
在命令行下输入 pip install itchat 完成安装
第三步, 编写代码
核心代码如下:
- #coding=utf8
- import itchat
- # 当接收到的消息是 Text, 即文字消息
- # 注册 re_msg 的意义在于, 告诉 itchat 每次有符合特定条件的消息, itchat 要把消息作为参数, 去调用 re_msg.
- @itchat.msg_register('Text')
- def text_reply(msg):
- #message: 取出 msg 里面的文本消息
- message = msg['Text']
- # 回复给好友
- replay = u'肖涛已在电脑上登陆网页微信, 但暂时无法进行交流, 可以给他发送电脑 QQ 消息哈'
- #主要是一些关键词设置
- # if B in A 如果 A 中有 B 的话
- if u'干什么' in message:
- replay = u'在忙呢'
- elif u'逼' in message:
- replay = u'含有敏感词汇, 请注意言辞'
- elif u'生气' in message:
- replay = u'生气对身体不好'
- elif u'?' in message:
- replay = u'哈哈, 我也不知道'
- elif u'不理你' in message:
- replay = u'乖, 忙完给你买糖吃'
- elif u'涛' in message:
- replay = u'他是我主人'
- elif u'厉害' in message:
- replay = u'不不不, 辣鸡一个'
- elif u'你好' in message:
- replay = u'你好哇'
- elif u'好吧' in message:
- replay = u'再见'
- return replay
- # 弹出扫码登录界面, 参数这样设置的好处是短时间内退出程序, 再次登录可以不用扫码
- itchat.auto_login(hotReload=True)
- # 开启自动回复
- itchat.run()
以上代码都是本人亲自编写, 如需转载请私信我.
代码截至 2018/11/30 本人调试有效, 最新的代码更新在我的 GitHub: 如有问题欢迎评论.
运行代码
- import itchat
- import requests
- def get_response(msg):
- apiUrl = 'http://www.tuling123.com/openapi/api' #改成你自己的图灵机器人的 API
- 'key': 'ce697b3fc8b54d5f88c2fa59772cb2cf', # Tuling Key
- 'info': msg, # 这是我们发出去的消息
- 'userid': 'wechat-robot', # 这里可随意修改
- }
- # 通过如下命令发送一个 post 请求
- r = requests.post(apiUrl, data=data).JSON()
- return r.get('text')
- @itchat.msg_register(itchat.content.TEXT)
- # 用于接收来自朋友间的对话消息 #如果不用这个, 朋友发的消息便不会自动回复
- def print_content(msg):
- return get_response(msg['Text'])
- # 用于接收群里面的对话消息
- @itchat.msg_register([itchat.content.TEXT], isGroupChat=True)
- def print_content(msg):
- return get_response(msg['Text'])
- itchat.auto_login(True)
- itchat.run()
来源: http://www.jianshu.com/p/4b7b4f4fb0e4