No longer afraid to communicate with foreigners! I use Python to implement a wechat chat translation assistant!

Big sai 2020-11-13 06:03:16
longer afraid communicate foreigners use


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 !

 Insert picture description here
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
 Insert picture description here

Detailed design

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 api

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

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 
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

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 .
 Insert picture description here
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 
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

youdao api

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 .
 Insert picture description here

The whole logic

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 .

Code and run results

That's it , I give the code of the project completely .

project github Address ( Wechat module ):
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')
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'
strexample='fanyideskweb'+transtr+salt+'n%A-rKaT5fb[Gy?;[email protected]'
'i':transtr,'from':'AUTO','to':To,'smartresult': 'dict',
return dict
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36',
'Origin': '',
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
'Accept':'application/json, text/javascript, */*; q=0.01',
'Accept-Encoding':'gzip, deflate',
'Connection': 'keep-alive',
'Host': '',
'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 
def text_reply(msg):
# Return message call message 
global jud
global To
global isreturn
dict = formdata(text)
if " Translation mode " in text:
isreturn =True
elif " Stop translating " in text:
if " Start " in text:
elif " stop it " in text:
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['from']= 'AUTO'
dict = urllib.parse.urlencode(dict)
dict = str(dict)
req =, timeout=1, data=dict, headers=header)
val = req.json()
transtr = val['translateResult'][0][0]['tgt']
itchat.send(transtr, toUserName=msg['ToUserName'])
## Back to monitor what the other side said 
if isreturn:
dict['to']='zh-CHS'## Translate into Chinese 
dict = urllib.parse.urlencode(dict)
# dict = str(dict)
req =, timeout=1, data=dict, headers=header)
val = req.json()
transtr = val['translateResult'][0][0]['tgt']
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

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 )
 Insert picture description here


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,( 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 !

本文为[Big sai]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database