python-flask公众号开发-对语音消息、图片消息实现翻译-使用百度翻译API、腾讯图片翻译API

与微信服务器对接签名验证代码

公众号后台基本配置需要我们的项目地址和自己设置的token来验证
在这里插入图片描述
代码部分


```python
# -*- coding: utf-8 -*-
import hashlib
from flask import Flask,request,abort
from flask import render_template
import xml.etree.cElementTree as ET
import time
import json
#设置token常量
TOKEN = 'weixin'
app = Flask(__name__)
#/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 import Flask,request,abort
from flask import jsonify,render_template
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__)
#/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 import Flask,request,abort
from flask import 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__)
@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是一门站在巨人肩膀上的开发的语言!
本文不足还请请谅解,是个刚入门的小白,还在学习的路上。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一加六

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值