1. 程式人生 > >基於Python的微信開發(1):Hello World

基於Python的微信開發(1):Hello World

需要安裝一個外掛,itchat。

pip install itchat
然後可以去“圖靈機器人”上註冊一個號,它具有自動回覆功能……

圖靈機器人

新建一個機器人。



拿到APIkey以後,就可以用python接入了。

#coding=utf8

import requests
import itchat

KEY = 'xxxxx' # 這裡填拿到的key

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()
        print(r)
        return r.get('text')
    except:
        return

@itchat.msg_register(itchat.content.TEXT)
def tuling_reply(msg):
    
        defaultReply = 'I received: ' + msg['Text']

        reply = get_response(msg['Text'])
        print(defaultReply, reply); itchat.send(reply,msg['FromUserName'])
        return str('[秦小兔 auto_reply] '+reply)  or defaultReply

itchat.auto_login(hotReload=True)
itchat.run()
執行以後,就可以開啟自動回覆了。