Home > Article > Backend Development > Detailed explanation of the sample code for quickly implementing WeChat chat robot based on Python
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()
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:
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!