服務器申請和端口配置
第一步申請服務器,這裏我選擇的是阿里雲的服務器,如果後面需用到申請域名方便申請證書其他也方便管理,學生機也很便宜,三個月不到30塊錢!
選擇安裝系統(小白我選windows,跟用自己電腦差不多)
windows服務器用的時候可以遠程桌面連接,如圖2
查看修改實例##
買下自己的服務器後,到控制檯,查看一下自己的實例(即服務器) 如圖3
安全組端口設置 如圖
需開放80 和 443公衆號僅支持的對接端口,
21,22fpt文件傳輸端口和ssh連接需要就開,3389用於遠程桌面連接的,
授權對象填 0.0.0.0/0 即可
服務器VNC密碼設置
如圖四
主要是以防防火牆開了阻止所有網絡接入,還可以VNC再開啓,我就幹了這事,然後所有東西都重置了一遍,設置VNC密碼很簡單,第一次的話進入輸入兩邊密碼就行,一定要記住,否則很麻煩。
以防萬以,記住遠程桌面連接不上了還有VNC
遠程連接 如圖5
輸入服務器公網ip 用戶名默認是Administrator
工具下載安裝
連接進入服務器後下載python,編輯器等自己開發常用工具,和上傳文件的工具
與微信服務器對接簽名驗證代碼
目的是填寫這裏,相當於進入大門
步入正題
公衆號後臺基本配置需要我們的項目地址和自己設置的token來驗證
代碼部分
```python
# -*- coding: utf-8 -*-
import hashlib
from flask_bootstrap import Bootstrap
from flask import Flask,request,abort,make_response
from flask import jsonify,render_template
import xml.etree.cElementTree as ET
import time
import json
#設置token常量
TOKEN = 'weixin'
app = Flask(__name__)
bootstrap = Bootstrap(app)
#/wechat表示網絡文件夾全部路徑爲
#http://你的ip地址/wechat 即可實現訪問
@app.route("/wechat",methods =['GET','POST'])
#接受的請求方法get、post須列表儲存
def wechat():
try:
#此處利用flask的request接收請求發來的參數
signature = request.args.get('signature')
timestamp = request.args.get('timestamp')
nonce = request.args.get('nonce')
if not all([signature,timestamp,nonce]):
abort(400)
ls=[timestamp,TOKEN,nonce]
#字典排序
ls.sort()
#連接成字符串
temp_str = ''.join(ls)
#進行sha1加密
sign = hashlib.sha1(temp_str.encode('utf-8')).hexdigest()
#簽名對比
if sign != signature:
abort(403)
else:
#接入簽名驗證微信服務器發送爲get請求,因此判斷一下get請求
if request.method == "GET":
#返回echostr即可成功對接
echostr = request.args.get('echostr')
if not echostr:
abort(400)
return echostr
if __name__ == '__main__':
app.run("0.0.0.0",port=80, debug =True)
#此爲接入部分代碼,代碼然後運行,再去公衆號後臺填入提交即可
回覆簡單文本、圖片以及關注事件處理
如果成功驗證即可開始繼續下一步
```python
# -*- coding: utf-8 -*-
import hashlib
from flask_bootstrap import Bootstrap
from flask import Flask,request,abort,make_response
from flask import jsonify,render_template
import xml.etree.cElementTree as ET
import time
import json
#文本回復xml格式模板
TEXT_REPLAY = '''
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>
'''
#圖片回覆xml模板
IMAGE_REPLAY = '''
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>
</xml>
'''
TOKEN= 'weixn'
app = Flask(__name__)
bootstrap = Bootstrap(app)
#/wechat表示網絡文件夾全部路徑爲
#http://你的ip地址/wechat 即可實現訪問
@app.route("/wechat",methods =['GET','POST'])
def wechat():
try:
signature = request.args.get('signature')
timestamp = request.args.get('timestamp')
nonce = request.args.get('nonce')
if not all([signature,timestamp,nonce]):
abort(400)
ls=[timestamp,TOKEN,nonce]
#字典排序
ls.sort()
#連接成字符串
temp_str = ''.join(ls)
#進行sha1加密
sign = hashlib.sha1(temp_str.encode('utf-8')).hexdigest()
#簽名對比
if sign != signature:
abort(403)
else:
#表示消息來自微信
if request.method == "GET":
#接入驗證
echostr = request.args.get('echostr')
if not echostr:
abort(400)
return echostr
elif request.method == "POST":
try:
#用request接收發送來的xml消息
xmldata = request.data
#處理xml數據
xml_rec = ET.fromstring(xmldata)
#獲取相關參數
ToUserName = xml_rec.find('ToUserName').text
FromUserName = xml_rec.find('FromUserName').text
MsgType = xml_rec.find('MsgType').text
if MsgType == 'text':
Content = xml_rec.find('Content').text
return REPLAY % (FromUserName,ToUserName,int(time.time()),MsgType,Content)
if MsgType == 'event':
Event = xml_rec.find('Event').text
if Event == 'subscribe':
return REPLAY % (FromUserName,ToUserName,int(time.time()),'text','感謝關注,請先回復 使用 獲取本公衆號使用方法')
if Event == 'CLICK':
return REPLAY % (FromUserName,ToUserName,int(time.time()),'text','')
if MsgType == 'image':
MediaId = xml_rec.find('MediaId').text
return IMAGE_REPLAY % (FromUserName,ToUserName,int(time.time()),MsgType,MediaId)
else:
return REPLAY % (FromUserName,ToUserName,int(time.time()),'text','我還沒學會識別這項技能')
except Exception as e:
raise e
except Exception as e:
raise e
if __name__ == '__main__':
app.run("0.0.0.0",port=80, debug =True)
這一步實現了你發文本,我回文本,你發圖片,我回圖片,你關注我回復感謝,發別的,我回復不會。如下圖
個性化回覆
入門開發也不能這麼簡單,加點料,翻譯,對收到的不同消息類型翻譯,
普通文本翻譯,語音識別翻譯百度的API,圖片識別翻譯騰訊的API
普通文本翻譯:隨便找的能用的翻譯接口,接上就行,讓後將用戶發送的文本消息直接通過接口翻譯,接收返回翻譯的結果json格式,篩選出翻譯的結果,再返回給微信服務器,發送給用戶!
語音翻譯: 這裏有點驚喜 如下圖
在微信開發者文檔裏,用戶發送的語言直接有識別的結果Recognition,那就好辦了,直接利用結果,跟普通文本翻譯一樣是一種選擇。
第二鍾選擇,免費讓用的API,百度開發平臺免費翻譯API
需要申請獲得appid和secret 我已再最開始設置常量代碼截圖看不到
代碼截圖如下,對返回參數提取
將翻譯的結果放到回覆模板裏即可!
圖片翻譯
騰訊翻譯君API 如圖 太強大了
文本翻譯、語音識別翻譯、圖片識別翻譯、都可以後來才發現的,但是我用的是OCR圖片識別文本,然後再文本翻譯,手動捂臉,弄完才知道有圖片直接翻譯,我就直接將圖片翻譯吧,但是下面代碼還是用的OCR加文本翻譯!
閱讀文檔自己閱讀一下,本來想在線調用請求接口,但是發現請求參數那裏的公共參數一直搞不懂,奈何我菜,就直接用了開發者資源,如圖
簡單看一下填寫的參數
複製代碼下來改動一下
然後將翻譯的字符串放到回覆模板裏即可,所有都完成,代碼(我是先圖片識別文本再翻譯)如下
# -*- coding: utf-8 -*-
# filename: handle.py
#import wechatpy
import hashlib
from flask_bootstrap import Bootstrap
from flask import Flask,request,abort,make_response
from flask import redirect,jsonify,render_template
import time
import xml.etree.cElementTree as ET
import requests
import json
TEXT_REPLAY = '''
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>
'''
IMAGE_REPLAY = '''
<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>
</xml>
'''
token = 'weixin'
app = Flask(__name__)
bootstrap = Bootstrap(app)
@app.route("/fanyi",methods =['GET','POST'])
def fanyi():
try:
signature = request.args.get('signature')
timestamp = request.args.get('timestamp')
nonce = request.args.get('nonce')
if not all([signature,timestamp,nonce]):
abort(400)
ls=[timestamp,token,nonce]
#字典排序
ls.sort()
#連接成字符串
temp_str = ''.join(ls)
#進行sha1加密
sign = hashlib.sha1(temp_str.encode('utf-8')).hexdigest()
#簽名對比
if sign != signature:
abort(403)
else:
#表示消息來自微信
if request.method == "GET":
#接入驗證
echostr = request.args.get('echostr')
if not echostr:
abort(400)
return echostr
elif request.method == "POST":
try:
openid = request.args.get('openid')
xmldata = request.data
xml_rec = ET.fromstring(xmldata)
ToUserName = xml_rec.find('ToUserName').text
FromUserName = xml_rec.find('FromUserName').text
MsgType = xml_rec.find('MsgType').text
#Ip_Daili.run(Content)
#文本翻譯 隨便找個能用的翻譯接口
if MsgType == 'text':
Content = xml_rec.find('Content').text
fanyi = 'http://fy.iciba.com/ajax.php?a=fy&f=auto&t=auto&w='+Content
fanyidata = requests.get(fanyi,headers=headers)
data = json.loads(fanyidata.text)
fanyires = data.get('content').get('out')
return TEXT_REPLAY % (FromUserName,ToUserName,int(time.time()),MsgType,fanyires)
#事件接收處理
if MsgType == 'event':
Event = xml_rec.find('Event').text
if Event == 'subscribe':
return TEXT_REPLAY % (FromUserName,ToUserName,int(time.time()),'text','感謝關注,請先回復 使用 獲取本公衆號使用方法\n可發送語音、圖片、位置等返回翻譯的英語結果')
if Event == 'CLICK':
return TEXT_REPLAY % (FromUserName,ToUserName,int(time.time()),'text','')
#圖片翻譯
if MsgType == 'image':
MediaId = xml_rec.find('MediaId').text
#MsgId = xml_rec.find('MsgId').text
PicUrl = xml_rec.find('PicUrl').text
try:
try:
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.ocr.v20181119 import ocr_client, models
cred = credential.Credential("AKIDLSLtAAMhkWrvoQrmW0uXjeJjriuntmzl", "cwTjkTv8krhGY9S0TfZDjytGML3wXrug")
httpProfile = HttpProfile()
httpProfile.endpoint = "ocr.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
client = ocr_client.OcrClient(cred, "ap-beijing", clientProfile)
req = models.GeneralAccurateOCRRequest()
params = '{"ImageUrl":"'+str(PicUrl)+'"}'
req.from_json_string(params)
resp = client.GeneralAccurateOCR(req)
rawstr = resp.to_json_string()
data = json.loads(rawstr)
translate_list = data.get('TextDetections')
examlist = []
examstr = ''
for m in translate_list:
examlist.append(m.get('DetectedText'))
examstr = ''.join(examlist)
except TencentCloudSDKException as err:
print(err)
try:
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.tmt.v20180321 import tmt_client, models
cred = credential.Credential("AKIDLSLtAAMhkWrvoQrmW0uXjeJjriuntmzl", "cwTjkTv8krhGY9S0TfZDjytGML3wXrug")
httpProfile = HttpProfile()
httpProfile.endpoint = "tmt.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
client = tmt_client.TmtClient(cred, "ap-beijing", clientProfile)
req = models.TextTranslateRequest()
params = '{"SourceText":"'+examstr+'","Source":"auto","Target":"en","ProjectId":0}'
req.from_json_string(params)
resp = client.TextTranslate(req)
translrawstr = resp.to_json_string()
result = json.loads(translrawstr)
translate_result = result.get('TargetText')
except TencentCloudSDKException as err:
print(err)
return TEXT_REPLAY % (FromUserName,ToUserName,int(time.time()),'text',translate_result)
except:
return IMAGE_REPLAY % (FromUserName,ToUserName,int(time.time()),MsgType,MediaId)
#語音翻譯
if MsgType == 'voice':
Recognition = xml_rec.find('Recognition').text
try:
salt= random.randint(1,10)
str1 = appid+Recognition+str(salt)+secret
md5 = hashlib.md5()
md5.update(str1.encode("utf-8"))
sign = md5.hexdigest()
baidutranslateAPI = 'http://api.fanyi.baidu.com/api/trans/vip/translate?q='+Recognition+'&from=zh&to=en&appid='+appid+'&salt='+str(salt)+'&sign='+sign
res = requests.get(baidutranslateAPI)
voice_data = json.loads(res.text)
translate_result = voice_data.get('trans_result')[0].get('dst')
return TEXT_REPLAY % (FromUserName,ToUserName,int(time.time()),'text',translate_result)
except:
return TEXT_REPLAY % (FromUserName,ToUserName,int(time.time()),'text','我沒聽清,請再說一邊')
#地理位置翻譯
if MsgType == 'location':
#location_X = xml_rec.find('location_X')
#location_Y = xml_rec.find('location_Y')
#Scale = xml_rec.find('Scale')
Label = xml_rec.find('Label').text
try:
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.tmt.v20180321 import tmt_client, models
cred = credential.Credential("AKIDLSLtAAMhkWrvoQrmW0uXjeJjriuntmzl", "cwTjkTv8krhGY9S0TfZDjytGML3wXrug")
httpProfile = HttpProfile()
httpProfile.endpoint = "tmt.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
client = tmt_client.TmtClient(cred, "ap-beijing", clientProfile)
req = models.TextTranslateRequest()
params = '{"SourceText":"'+Label+'","Source":"auto","Target":"en","ProjectId":0}'
req.from_json_string(params)
resp = client.TextTranslate(req)
translrawstr = resp.to_json_string()
result = json.loads(translrawstr)
translate_result = result.get('TargetText')
except TencentCloudSDKException as err:
print(err)
return TEXT_REPLAY % (FromUserName,ToUserName,int(time.time()),'text',translate_result)
else:
return TEXT_REPLAY % (FromUserName,ToUserName,int(time.time()),'text','我還沒學會識別這項技能')
except Exception as e:
raise e
except Exception as e:
raise e
if __name__ == '__main__':
app.run("0.0.0.0",port=80, debug =True)
效果圖如下
至此簡單的不同消息翻譯結束!
python是一門站在巨人肩膀上的開發的語言!
本文不足還請請諒解,是個剛入門的小白,還在學習的路上。