preface
In a previous article on how to “elegantly” invoke Youdao Translation in Python, we clearly wrote about how to unlock the veil of Youdao Translation layer by layer, and I said that was just the beginning of the imagination. Now I’m back. When you meet some foreign little brother little sister very enchanted, want to get acquainted with communication, but English level or other level is still in the stage of improvement, this small tool can help you tide over difficulties! Teach you how to flirt with code. In this article, I will explain the implementation of this translation in detail! For the realization of the main function: through wechat chat monitor some key password, open the translation mode of their own words and the translation mode of the opposite words!
Translation interface
WeChat API
Monitoring your own messages
Keyword judgment
Request Youdao translation
Of course, if you have a Korean friend, what he says is automatically translated into Chinese and sent to you, and what you say is automatically translated into Korean and sent to him. The little elder brother that has ability to have resource little elder sister can try foreign girl doll!
The detailed design
Now that the idea in front is clear, let’s go step by step and solve all the problems. There are two main aspects, one is a separate wechat API and a separate request youdao translate some other rules, on the other hand, the integration of the two can make people humanized operation!
Of course, after solving these two items, you can realize some logic switch, and I used my logic to achieve a simple!
Environment: Win/Linux compiler: PyCharm Additional modules: ITchat, Requests
WeChat API
Wechat disclosed the API of wechat web version. The Itchat module in Python can be used directly. Of course it takes time to learn the ropes. I put in some of the necessary learning steps.
1. Scan the itchat module to log in. No parameters can be added, but after the hotReaload is added, code scanning is not needed in a short period of time, otherwise, the efficiency of each startup code scanning will be delayed.
import itchat
itchat.auto_login(hotReload=True)
Copy the code
UserName is the only encrypted field of the user. Of course, the file Transfer Assistant has a special ID, and other search friend names can also be obtained by json string. Anyway, this field is pretty easy to get.
itchat.send("Hello",toUserName = userName)
Copy the code
3. The most important thing is the message monitoring, for message monitoring, most baidu to the result is to make the program into a robot, monitor the opposite message and then automatically reply, but the author is not this effect, I want to monitor their mobile wechat messages and then analyze what what what what.
This is true of normal eavesdropping
The message type is itchat.content.text. Can also listen to a variety of types of their own degrees
@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
return msg['Text']#return "string" is sent to act as a robot when an incoming message is received
itchat.run()
Copy the code
If you print(MSG) from you send to he/she, you will find that your message is also monitored. So you can retrieve the contents and actively send messages using itChat’s SEND API. Of course, the body of the content that you’re sending and all sorts of other information is in there, and PY also happens to be very handy for manipulating dictionaries.
The message type is itchat.content.text
@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
# XXXXX logic processing if self sent
itchat.send(transtr, toUserName=msg['ToUserName'])# Send the string transtr to the person you sent it to
# XXXXX logic handles if ta sends
return transtr# this plus is if the opposite message listening. So if you send a message from the other side and you return it, it will be sent automatically
itchat.run()
Copy the code
Youdao API
For the other ones, which have been analyzed previously, we need to pay attention to the translation language, such as Chinese-To-English (EN), Japanese (JA), Korean (KO) and so on. So you can just click on a couple of typical ones and put them in logic.
The overall logical
Of course, I want to write a logic that can control the beginning and end of sending a translation. So I listen for two Boolean types that control the entire start and pause mode, where JUd is used to determine if I’m in load (b) translation mode for what I’m saying. The isreturn parameter controls whether to translate what the doll says. Key words here I choose start as the beginning, stop as the end control what you say. In translation mode, stop translation is used to control the start and stop of speech. English, Japanese, Korean, French, etc.
So, once it’s up and running, we’ve got everything under control, and of course, we’ve tested the efficiency, and even though the ItChat and Youdao translation data are sent over HTTP, it’s actually pretty efficient, it’s acceptable for chat. The latency isn’t that big. It meets basic needs. But don’t do it too quickly or too often, in case Youdao blocks your IP and you can’t request it.
Code and results
In this way, I put the project code for the complete out.
Github address (wechat module) : github.com/javasmall/p… Welcome to star!
# More Please follow the public account bigsai
import itchat
import requests
import hashlib
import time
import urllib.parse
jud=FalseThe default value is disable
isreturn=False# Reply
To='en'The default language for translation is English
def nmd5(str):# md5 encryption
m = hashlib.md5()
b = str.encode(encoding='utf-8')
m.update(b)
str_md5 = m.hexdigest()
return str_md5
def formdata(transtr):
# Message to be encrypted
global To
headerstr = '5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'
bv=nmd5(headerstr)
ts=str(round(time.time()*1000))
salt=ts+'90'
strexample='fanyideskweb'+transtr+salt+'n%A-rKaT5fb[Gy?;N5@Tj'
sign=nmd5(strexample)
i=len(transtr)
dict={'i':transtr,'from':'AUTO'.'to':To,'smartresult': 'dict'.'client':'fanyideskweb'.'salt':salt,
'sign':sign,
'ts':ts,
'bv':bv,
'doctype':'json'.'version':'2.1'.'keyfrom':'fanyi.web'.'action':'FY_BY_REALTlME'
}
return dict
url='http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
header={'User-Agent':'the Mozilla / 5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'.'Referer':'http://fanyi.youdao.com/'.'Origin': 'http://fanyi.youdao.com'.'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'.'X-Requested-With':'XMLHttpRequest'.'Accept':'application/json, text/javascript, */*; Q = 0.01 '.'Accept-Encoding':'gzip, deflate'.'Accept-Language':'zh-CN,zh; Q = 0.9 '.'Connection': 'keep-alive'.'Host': 'fanyi.youdao.com'.'cookie':'_ntes_nnid=937f1c788f1e087cf91d616319dc536a,1564395185984; OUTFOX_SEARCH_USER_ID_NCOO=; OUTFOX_SEARCH_USER_ID = - 10218418 - @11.136.67.24; JSESSIONID=; ___rl__test__cookies=1'
}
itchat.auto_login(hotReload=True)# login
# register message response event, message type itchat.content.text, TEXT message
@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
Call information
global jud
global To
global isreturn
text=msg['Text']
dict = formdata(text)
if "Translation mode" in text:
isreturn =True
elif "Stop translating." in text:
isreturn=False
if "Start" in text:
jud=True
elif "Stop" in text:
jud=False
elif "English" in text:
To = 'en'
elif "Japanese" in text:
To = 'ja'
elif "Korean" in text:
To = 'ko'
elif "French" in text:
To = 'fr'
if jud:# indicates that it needs to be run
dict['to']=To
dict['from'] ='AUTO'
dict = urllib.parse.urlencode(dict)
dict = str(dict)
req = requests.post(url, timeout=1, data=dict, headers=header)
val = req.json()
transtr = val['translateResult'] [0] [0] ['tgt']
print(msg)
itchat.send(transtr, toUserName=msg['ToUserName'])
## Return to listen for what is being said
if isreturn:
dict['from'] ='AUTO'
dict['to'] ='zh-CHS'## translated into Chinese
dict = urllib.parse.urlencode(dict)
# dict = str(dict)
req = requests.post(url, timeout=1, data=dict, headers=header)
val = req.json()
transtr = val['translateResult'] [0] [0] ['tgt']
print(msg)
return 'ta said.+str(transtr)# this plus is if the opposite message listening. For example, if you are a two-way translator, you can try
After the bind message responds to the event, let itChat run and listen for messages
itchat.run()
Copy the code
Since I don’t really have a doll, I can only simulate the simple running test results (self-directed by a teammate’s phone).
conclusion
Of course, this may be very interesting, or may be very boring and simple, but different people may have different views, different time, different communication may have different views, so please do not like to spray, of course, if you have suggestions for improvement, please also point out! Github address for python related repositories and projects: https://github.com/javasmall/python/tree/master/%E7%88%AC%E8%99%AB/Include/%E5%BE%AE%E4%BF%A1, (WeChat file directory) interested can play, Star, star! If the feeling is still ok, please move your little hands little collection, little praise 👍!
Welcome to pay attention to the public number: Bigsai long-term struggle output!