[关闭]
@chengweihuang 2019-02-19T12:15:03.000000Z 字数 1336 阅读 552

微信机器人

未分类


  1. # encoding: utf-8
  2. __author__ = 'ChengweiHuang'
  3. __date__ = '2018/11/13 19:48'
  4. #pip install itchat 先导库
  5. # http://www.tuling123.com/ 进入网站 注册账号
  6. import itchat
  7. import requests
  8. import json
  9. def get_response(msg):
  10. # 下面是图灵机器人配置部分
  11. url = "http://openapi.tuling123.com/openapi/api/v2"
  12. data = {
  13. "reqType": 0,
  14. "perception": {
  15. "inputText": {
  16. "text": msg
  17. },
  18. },
  19. "userInfo": {
  20. "apiKey": "a79fcc9fe2fa4b43948db43345d8858b", # 这个地方 写你自己的apiKey
  21. "userId": "qweasfsfsdf"
  22. }
  23. }
  24. # 回复消息
  25. response = requests.post(url, data=json.dumps(data)).json()
  26. return response.get('results')[0].get('values').get('text')
  27. @itchat.msg_register(itchat.content.TEXT) # 当聊天类型 是TEXT 的时候
  28. def write_back(msg):
  29. return get_response(msg["Text"]) # 调用回复函数
  30. if __name__ == "__main__":
  31. itchat.auto_login(True) # 登录微信 设置 True 可以在短期 不用重复登录
  32. itchat.run() # 实时监听聊天

登录篇

  1. import itchat
  2. # pip install itchat
  3. # 实现给好友发消息
  4. itchat.auto_login(True) # 登录 扫描二维码
  5. # itchat.auto_login(True) 设置True 短期之内 不用重复登录
  6. friend = itchat.search_friends('黄志宇')[0]# 搜索好友 以字典的形式 展示出来
  7. # 括号里的 参数写朋友的名字 不写 默认自己
  8. print(friend)
  9. itchat.send('你好',toUserName=friend["UserName"])
  10. itchat.logout()
  11. # 装饰器itchat.msg_reister 可以根据接受消息的类型 寻找对应的注册方法 如果一个消息
  12. # 没有对应的注册方法 ,该消息被舍弃

自动回复篇

  1. # encoding: utf-8
  2. __author__ = 'ChengweiHuang'
  3. __date__ = '2018/11/13 19:29'
  4. import itchat
  5. @itchat.msg_register(itchat.content.TEXT) # 文本消息类型
  6. def write_back(msg):
  7. #print(msg) # 关于聊天的消息 字典形式
  8. itchat.send(msg['Text'],toUserName=msg['FromUserName'])
  9. print(msg['Text'])
  10. itchat.auto_login(True)
  11. itchat.run() # 实时监控聊天信息
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注