python中调用百度翻译api接口实现微信聊天翻译

from hashlib import md5
from random import randint
import json
from urllib.parse import quote
from urllib.request import urlopen
from wxpy import *

#微信机器人
bot = Bot(cache_path=True)

#在百度翻译开放平台注册,即可获得appid和secretkey
#http://api.fanyi.baidu.com/api/trans/product/index

def translate_robot(word):
    appid = 'XXXXXXX'
    secretkey = 'XXXXXXX'
    salt = randint(23456, 56789)
    q = quote(word)

    s = appid + word + str(salt) + secretkey
    m = md5()
    m.update(s.encode('utf-8'))
    sign = m.hexdigest()

    url = 'http://api.fanyi.baidu.com/api/trans/vip/translate?q=' + q + '&from=zh&to=en&appid=' + appid + '&salt=' + str(
        salt) + '&sign=' + sign

    url_word = urlopen(url)
    read_word = url_word.read().decode('utf-8')
    json_word = json.loads(read_word)
    # print(json_word)
    t_word = json_word['trans_result'][0]['dst']
    print(t_word)
    return t_word


#回复自己,如果是文本消息的话,回复翻译内容;如果其他类型的消息,回复表情
@bot.register(bot.self, except_self=False)
def reply_self(msg):
    if (msg.type == 'Text'):
        msg.reply(translate_robot(msg.text))
    else:
        msg.reply(str('[可爱][可爱]'))

#回复朋友,如果是文本消息的话,回复翻译内容;如果其他类型的消息,回复表情
#朋友的微信名指的是她/他自己取的昵称,不是你的备注哦
# friend = bot.friends().search(u'朋友的微信名')[0]
# @bot.register(friend)
# def reply_friend(msg):
# 
#     if (msg.type == 'Text'):
#         msg.reply(translate_robot(msg.text))
#     else:
#         msg.reply(str('[可爱][可爱]'))

embed()


你可能感兴趣的:(python中调用百度翻译api接口实现微信聊天翻译)