Detailed explanation of the sample code for quickly implementing WeChat chat robot based on Python

高洛峰
Release: 2017-03-06 11:39:50
Original
3015 people have browsed it

Recently I heard about a very interesting Turing robot API, which can be used to make a WeChat chat robot. The following is the implementation

# test.py

import requests
import itchat #这是一个用于微信回复的库

KEY = '8edce3ce905a4c1dbb965e6b35c3834d' #这个key可以直接拿来用

# 向api发送请求
def get_response(msg):
  apiUrl = 'http://www.tuling123.com/openapi/api'
  data = {
    'key'  : KEY,
    'info'  : msg,
    'userid' : 'pth-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):
  # 为了保证在图灵Key出现问题的时候仍旧可以回复,这里设置一个默认回复
  defaultReply = 'I received: ' + msg['Text']
  # 如果图灵Key出现问题,那么reply将会是None
  reply = get_response(msg['Text'])
  # a or b的意思是,如果a有内容,那么返回a,否则返回b
  return reply or defaultReply

# 为了让修改程序不用多次扫码,使用热启动
itchat.auto_login(hotReload=True)
itchat.run()
Copy after login

If you want this robot to run forever, you need to upload it to the server, use the screen command to open a new window, and run python3 test.py. At this time, a QR.jpg file will be generated in the same directory, but because generally we use There is no image when connecting to the server through ssh, so you need to use the scp command. After downloading it to the local area, scan the code with your mobile phone and the work is completed.

The effect is as follows:

Detailed explanation of the sample code for quickly implementing WeChat chat robot based on Python

The above is the entire content of this article. I hope it will be helpful to everyone's study. I also hope that everyone will support the PHP Chinese website.

For more detailed explanations on quickly implementing the WeChat chatbot sample code based on Python, please pay attention to the PHP Chinese website for related articles!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!