In the previous article How to use python“ elegant ” Call Youdao translation We have clearly written how to untie the veil of Tao translation layer by layer , And I said that's just the beginning of the hole . Now I'm back . When you meet Some little foreign brothers and sisters are very excited 、 Want to get to know each other , But the English level or other level is still improving , This little tool can help you through the difficulties !Teach you how to flirt gracefully with code. In this paper , I will explain in detail the specific implementation of this translation ! For the main functions of the implementation : Listen to some key passwords through wechat chat , Turn on the translation mode of what you say and the translation mode of what you say on the opposite side !
Design thinking : There is a call translation , We can go with Translation interface
and The WeChat api
Do some interesting things together , Mainly using wechat api Yes Monitor your own messages , Then some Keyword determination
As a switch 、 Change the translation language and so on ( Logic can be set by itself ), Then go Ask for a translator , Use the program to automatically send the translated words to the other party . Then pretend to think of yourself as an unknown Mengxin ------ It depends on how you operate ( Manual funny )
Of course , If you have a Korean friend , What he said automatically translated into Chinese , To you , What you said will be automatically translated into Korean and sent to him . Little brother and little sister with ability and resources can go to Try girls Dolls !
Since the thinking ahead is very clear , So let's go step by step , How to overcome all these problems . There are two main aspects , One
It's alone WeChat api And individual Ask for a translation of some other rules , The other
The aspect is to integrate the two , The operation that can make everyone sexual !
Of course, after solving these two problems , You can implement some logic switches by yourself , And I used my logic to simply implement !
Environmental Science :win/linux
compiler :pycharm
Additional modules :itchat、requests
Wechat party has made public the api.python Medium itchat
Modules can be used directly . Of course, it will take time to fumble . I put on some necessary learning steps .
1 . about itchat Module scan code login . No parameters can be added later , But with this hotReaload After a short period of time can not need to scan , Otherwise Every time you start scanning, it's delayed efficiency .
import itchat
itchat.auto_login(hotReload=True)
2 . As for another messenger api It's also very simple. , hinder userName Is the only encrypted field of the user , Of course , The file transfer assistant has a special id, There are other search friends through the return of json Strings can also be obtained using the id. All in all, this field is easy to get .
itchat.send(" Hello ",toUserName = userName)
3 . The most important thing is to monitor the news , For message monitoring , Most of Baidu's results are made into robots , Listen to the opposite message and reply automatically , But what I want is not this effect , I want to listen to the messages sent by wechat on my mobile terminal and analyze them .
It's the same for normal monitoring
# Register message response events , The message type is itchat.content.TEXT, Text message . Can also monitor a variety of types of Baidu
@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
return msg['Text']#return “ character string ” When receiving the news from the opposite side , It's going to work as a robot
itchat.run()
however , If you do it again print(msg). You will find that your own messages will also be monitored , Here is from you send to he/she. So you can get the contents of yourself utilize itchat
send out send
Of api
Take the initiative to send messages . Of course , All kinds of information, such as the main body of the content you send, are in it ,py It's also very convenient to operate the dictionary .
So the final design of this part is like this :
If it's the message from the opposite side, we will directly return The string will send , If it's my own message , own send Call to send message !
# Register message response events , The message type is itchat.content.TEXT, Text message
@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
#xxxxx Logic processing if you send
itchat.send(transtr, toUserName=msg['ToUserName'])# The string transtr Send it to the person you sent it to
#xxxxx Logical processing if ta Hair
return transtr# This plus if it's a monitor for messages sent from the opposite side . That is to say, send a message to you directly return It will automatically send
itchat.run()
For the rest of the previous analysis , What we need to pay attention to here is the translated language , For example, translation from Chinese to English (en
)、 Japanese (ja
)、 Korean (ko
) wait . So you just need to order some typical logic processing .
Of course , I want to write a logic to control the start of sending translation 、 end . So I use Two Boolean type
Control the whole start and stop , among jud
It's used to judge whether you open the device of what you say (b) Translation mode . And the parameters isreturn
Used to control whether or not to translate the doll's words . Here I choose Start
For a start , stop it
Control what you say as an end . and Translation mode
, Stop translating
It's used to control what starts and stops saying . English 、 Japanese 、 Korean 、 French 、 Etc. as the key words of translation language change .
that , Once the program runs , Everything is under our control , Of course , Tested efficiency , Although that itchat, And Youdao translate data through http Transmission of , But in fact Efficiency is OK , Transmission efficiency is acceptable for chat . The delay is not very big , Able to meet basic needs . But don't be too fast or too frequent , To prevent you from ip You can't ask for it .
That's it , I give the code of the project completely .
project github Address ( Wechat module ):https://github.com/javasmall/python
welcome star!
# More attention to the official account :bigsai
import itchat
import requests
import hashlib
import time
import urllib.parse
jud=False# The default is not to turn on first
isreturn=False# Whether to reply
To='en'# The default language 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):
# Information 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?;[email protected]'
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':'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=; [email protected]; JSESSIONID=; ___rl__test__cookies=1'
}
itchat.auto_login(hotReload=True)# Sign in
# Register message response events , The message type is itchat.content.TEXT, A text message
@itchat.msg_register(itchat.content.TEXT)
def text_reply(msg):
# Return message call message
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 it " 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:# Explain the need to 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'])
## Back to monitor what the other side said
if isreturn:
dict['from']='AUTO'
dict['to']='zh-CHS'## Translate 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 say :'+str(transtr)# This plus if it's a monitor for messages sent from the opposite side . For example, you can try two-way translation
# After binding message response event , Give Way itchat Run up , Listen to the message
itchat.run()
Since I really don't have dolls, I can only simulate
Simply run the test results ( Take your teammate's cell phone and guide yourself )
Of course , This may be fun , Maybe it's boring and simple , It's just that different people may have different opinions , Different time periods 、 Different communication may have different views , So please don't spray if you don't like it , Of course , If there are suggestions for improvement , Also please indicate !
python Related warehouses and projects github Address :https://github.com/javasmall/python/tree/master/%E7%88%AC%E8%99%AB/Include/%E5%BE%AE%E4%BF%A1
,( Wechat file directory ) You can play if you are interested ,star star! If you feel OK, please move your hands to collect 、 A little bit of praise !
Welcome to the official account :bigsai
Long term fighting output !