当前位置:   article > 正文

python微信机器人_微信机器人 必须一直开着python吗

微信机器人 必须一直开着python吗

来源: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的位置)

  1. #!/usr/bin/env python3.6
  2. #coding=utf8
  3. import requests
  4. import itchat
  5. KEY = '输入图灵机器人apikey'
  6. flag = False
  7. stop_reply=False
  8. default_text="你好,本人不在。联系我请直接拨打电话。或者等本人上线后回复。\n电话号码:110" \
  9. "\n如果想继续聊天请回复12138进入聊天机器人系统。回复666退出聊天。\n" \
  10. "祝你愉快! ————来自otote"
  11. def get_response(msg):
  12. apiUrl = 'http://www.tuling123.com/openapi/api'
  13. data = {
  14. 'key' : KEY,
  15. 'info' : msg,
  16. 'userid' : 'wechat-robot',
  17. }
  18. try:
  19. r = requests.post(apiUrl, data=data).json()
  20. return r.get('text')
  21. except:
  22. return
  23. @itchat.msg_register(itchat.content.TEXT)
  24. def tuling_reply(msg):
  25. global flag
  26. global stop_reply
  27. oldflag=flag
  28. # defaultReply = 'I received: ' + msg.text
  29. global default_text
  30. reply = get_response(msg.text)
  31. # return reply or defaultReply
  32. if msg.text=="12138":
  33. flag=True
  34. elif msg.text=="666":
  35. flag=False
  36. elif msg.text == "启动机器人":
  37. stop_reply = False
  38. elif msg.text == "停止机器人":
  39. stop_reply = True
  40. if not stop_reply:
  41. if flag :
  42. if not oldflag:
  43. return "我们可以开始聊天了。"
  44. else:
  45. return reply+"\n\t\t————来自机器人\n退出机器人请回复666"
  46. else:
  47. return default_text
  48. # return reply or test
  49. @itchat.msg_register(itchat.content.RECORDING)#语音消息
  50. def voice_reply(msg):
  51. return tuling_reply(msg)
  52. itchat.auto_login(enableCmdQR=2,hotReload=True)
  53. #itchat.auto_login(hotReload=True)
  54. itchat.run()
  55. # nohup python run.py #linux后台自动运行

(1)Windows直接打开cmd窗口输入python 然后将otote.py拖进去(注意空格隔开)然后回车。接着扫描二维码登录即可使用。(关闭cmd后程序自动关闭)

(2)linux 直接用命令python /文件目录/otote.py运行后扫描二维码登录即可。(关闭终端窗口后会关闭机器人。可先扫码登录成功运行后按ctrl+c终止,然后用命令nohup python otote.py运行后即可关闭终端窗口。)

三、效果预览:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/766189
推荐阅读
相关标签
  

闽ICP备14008679号