赞
踩
来源:otote.cn
长夜漫漫,无心睡眠。突发奇想。于是就基于itchat和图灵机器人做了个微信机器人。
github地址:https://github.com/otote/wchat_auto
1、有一台服务器,或者装了linux的电脑。Windows也行。最好是有服务器,不然电脑关了机器人也就关闭了。
2、需要安装python环境,因为我用的是python3.6,所以推荐安装python3.6环境。Python2没测试过,可自行测试。
3、安装itchat模块。使用python目录下的pip安装。Linux配置好环境后可以直接用命令:pip install itchat 安装。Windows需要打开cmd窗口,然后将python安装目录下的Scripts目录里的pip.exe拖到cmd窗口,接着输入install itchat后按回车,注意空格隔开。
4、需要申请图灵机器人的api权限,然后将apikey填入代码中的KEY的位置。申请地址
新建一个文件,名字自取,最好用过英文。后缀为py。以otote.py为例。
将以下代码粘贴到otote.py里面后保存退出。(注意将图灵机器人apikey填入代码中的KEY的位置)
- #!/usr/bin/env python3.6
- #coding=utf8
- import requests
- import itchat
-
- KEY = '输入图灵机器人apikey'
-
- flag = False
- stop_reply=False
- default_text="你好,本人不在。联系我请直接拨打电话。或者等本人上线后回复。\n电话号码:110" \
- "\n如果想继续聊天请回复12138进入聊天机器人系统。回复666退出聊天。\n" \
- "祝你愉快! ————来自otote"
- def get_response(msg):
- apiUrl = 'http://www.tuling123.com/openapi/api'
- data = {
- 'key' : KEY,
- 'info' : msg,
- 'userid' : 'wechat-robot',
- }
- try:
- r = requests.post(apiUrl, data=data).json()
- return r.get('text')
- except:
- return
-
- @itchat.msg_register(itchat.content.TEXT)
- def tuling_reply(msg):
- global flag
- global stop_reply
- oldflag=flag
- # defaultReply = 'I received: ' + msg.text
- global default_text
- reply = get_response(msg.text)
- # return reply or defaultReply
- if msg.text=="12138":
- flag=True
- elif msg.text=="666":
- flag=False
- elif msg.text == "启动机器人":
- stop_reply = False
- elif msg.text == "停止机器人":
- stop_reply = True
-
- if not stop_reply:
- if flag :
- if not oldflag:
- return "我们可以开始聊天了。"
- else:
- return reply+"\n\t\t————来自机器人\n退出机器人请回复666"
- else:
- return default_text
- # return reply or test
-
- @itchat.msg_register(itchat.content.RECORDING)#语音消息
- def voice_reply(msg):
- return tuling_reply(msg)
-
- itchat.auto_login(enableCmdQR=2,hotReload=True)
- #itchat.auto_login(hotReload=True)
-
-
- itchat.run()
-
- # nohup python run.py #linux后台自动运行

(1)Windows直接打开cmd窗口输入python 然后将otote.py拖进去(注意空格隔开)然后回车。接着扫描二维码登录即可使用。(关闭cmd后程序自动关闭)
(2)linux 直接用命令python /文件目录/otote.py运行后扫描二维码登录即可。(关闭终端窗口后会关闭机器人。可先扫码登录成功运行后按ctrl+c终止,然后用命令nohup python otote.py运行后即可关闭终端窗口。)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。