python學習---實現(xiàn)微信公眾號聊天機器人

最近在學習python,想做一個聊天機器人,百度了很多資料,有的也是根據別人分享的文檔一步步操作,但過程中還是遇到了一些問題,因此 我自己總結了一下我的步驟:

1. 申請一個公眾號, 具體的可以百度微信公眾號跟著步驟申請一個就行 自己玩的話 訂閱號就可以了

(https://mp.weixin.qq.com/)

2. 申請一個服務器

我用的是新浪云,不要問我為什么選擇這個, 我也是剛開始跟著一個教程做的
創(chuàng)建一個云應用

image

選擇python開發(fā)語言 這里我選擇的共享環(huán)境 具體計費及配額旁邊都有說明,輸入二級域名(自己起個名字就行),輸入應用名稱---->確認創(chuàng)建

新浪云的代碼管理有兩種方式 SVN 和git 為了方便我選擇了git

3. 在本地建一個文件夾 weixin

新建config.yaml文件

name: wxpytest

version: 1

libraries:

- name: webpy

  version: "0.36"

- name: lxml

  version: "2.3.4"

新建index.wsgi文件

# coding: UTF-8

import os

import sae

import web

from weixinInterface import WeixinInterface

urls = (

'/weixin','WeixinInterface'

)

app_root = os.path.dirname(__file__)

templates_root = os.path.join(app_root, 'templates')

render = web.template.render(templates_root)

app=web.application(urls, globals()).wsgifunc()

application = sae.create_wsgi_app(app)

新建weixinInterface.py文件

# -*- coding: utf-8 -*-

import hashlib

import web

import lxml

import time

import os

from lxml import etree

import urllib2

import robot

class WeixinInterface:

    def __init__(self):

        self.app_root = os.path.dirname(__file__)

        self.templates_root = os.path.join(self.app_root, 'templates')

        self.render = web.template.render(self.templates_root)

    def GET(self):

        #獲取輸入參數(shù)

        data = web.input()

        signature=data.signature

        timestamp=data.timestamp

        nonce=data.nonce

        echostr = data.echostr

        #自己的token

        token="你的token" #這里改寫你在微信公眾平臺里輸入的token

        #字典序排序

        list=[token,timestamp,nonce]

        list.sort()

        sha1=hashlib.sha1()

        map(sha1.update,list)

        hashcode=sha1.hexdigest()

        #sha1加密算法

        #如果是來自微信的請求,則回復echostr

        if hashcode == signature:

            return echostr

新建一個文件夾/weixin/templates,新建一個文件reply_text.xml

$def with (toUser,fromUser,createTime,content)
<xml>
<ToUserName><![CDATA[$toUser]]></ToUserName>
<FromUserName><![CDATA[$fromUser]]></FromUserName>
<CreateTime>$createTime</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[$content]]></Content>
</xml>

https://www.sinacloud.com/doc/sae/tutorial/code-deploy.html
參考官方文檔部署代碼

4.設置微信公眾號,進入開發(fā)--->基本配置

image.png

例如我的域名是test.applinzi.com
ur填寫為:https://test.applinzi.com/weixin
查找自己的域名參考下圖:
image.png

token和代碼里寫的token保持一致就行
EncodingAesKey 隨機生成就好了
消息加密方式選擇明文或兼容都可以
點擊提交
如果出現(xiàn)token驗證失敗請檢查你的token和代碼里填寫的是否一致,url是否正確

5. 調用圖靈api實現(xiàn)機器人聊天

首先需要去圖靈官網注冊 開通一個機器人
新建robot.py

# -*- coding=utf-8 -*-
import requests

KEY = "創(chuàng)建機器人后生成的apikey"

def get_response(msg):
    apiUrl='http://www.tuling123.com/openapi/api'
    data={
       'key':KEY,
       'info':msg,
       'userid':'機器人名字',
   }
    try:
       r=requests.post(apiUrl, data=data).json()
       return r.get('text').encode("utf-8")
    except:
       return msg
    return msg

修改weixinInterface.py文件

# -*- coding: utf-8 -*-
import hashlib
import web
import lxml
import time
import os
from lxml import etree
import urllib2
import robot
class WeixinInterface:

    def __init__(self):
        self.app_root = os.path.dirname(__file__)
        self.templates_root = os.path.join(self.app_root, 'templates')
        self.render = web.template.render(self.templates_root)

    def GET(self):
        #獲取輸入參數(shù)
        data = web.input()
        signature=data.signature
        timestamp=data.timestamp
        nonce=data.nonce
        echostr = data.echostr
        #自己的token
        token="********" #這里改寫你在微信公眾平臺里輸入的token
        #字典序排序
        list=[token,timestamp,nonce]
        list.sort()
        sha1=hashlib.sha1()
        map(sha1.update,list)
        hashcode=sha1.hexdigest()
        #sha1加密算法
        #如果是來自微信的請求,則回復echostr
        if hashcode == signature:
            return echostr
            
    def POST(self):
        str_xml = web.data()#獲得post來的數(shù)據
        xml = etree.fromstring(str_xml)#進行XML解析
        msgType=xml.find("MsgType").text
        fromUser=xml.find("FromUserName").text
        toUser=xml.find("ToUserName").text
        if msgType == 'text':
            content=xml.find("Content").text
          
            rpyMsg=robot.get_response(content)
            return self.render.reply_text(fromUser,toUser,int(time.time()), rpyMsg)
        else:
            pass

由于robot導入了requests包,我們需要把requests,urllib3,idna,chardet,certifi包拉到本地放在weixin目錄下
并且修改index.wsgi文件

# coding: UTF-8
import os
import sae
import web
import sys

from weixinInterface import WeixinInterface

urls = (
'/weixin','WeixinInterface'
)

app_root = os.path.dirname(__file__)
templates_root = os.path.join(app_root, 'templates')
render = web.template.render(templates_root)
app=web.application(urls, globals()).wsgifunc()
application = sae.create_wsgi_app(app)
sys.path.insert(0,os.path.join(app_root, 'requests'))
sys.path.insert(0,os.path.join(app_root, 'urllib3'))
sys.path.insert(0,os.path.join(app_root, 'chardet'))
sys.path.insert(0,os.path.join(app_root, 'certifi'))
sys.path.insert(0,os.path.join(app_root, 'idna'))
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容