📜 ⬆️ ⬇️

We write chat bot for VKontakte on python using longpoll. Part two. Double cycles, exceptions and other heresy

Greetings, Habr. This article is a continuation of this one . Before reading, I strongly recommend that you read it if you have not done this before.

Today you will learn:

  1. How to get more than one answer, albeit collective
  2. How to connect to this Yandex translator
  3. And how to write to the user that he did everything wrong

Api Yandex Translator


Yandex translator has quite good api and we will use it. We carefully study the documentation and fight. But here Yandex gives us a pig.
Requirements for using translation results
According to the License for the use of Yandex.Translator, the text Translated by the Yandex.Translate service with an active link to the translate.yandex.ru page must be indicated above or below the result of the translation .
')
Text layout requirements
Text must be specified:
in the description of the software product;
in the help of the software product;
on the official website of the software product;
on all pages or screens where service data is used.
Well, we are not proud people, we will survive.

How does it work


The user writes us a message, we ask what language he wants to translate the phrase. After asking the text that needs to be translated and send the result.

Technical implementation


Get the api key
We use this library here.

from yandex_translate import YandexTranslate #  translate = YandexTranslate('  ') 

We kick a longpoll as I described in the 1st part.

 if event.text == '': #     "" if event.from_user: vk.messages.send( #  user_id=event.user_id, message='  ?   .\n :  - ru,  - en' #C  "  ?   .\n :  - ru,  - en".       ) elif event.from_chat: vk.messages.send( # ,    chat_id=event.chat_id, message='  ?   .\n :  - ru,  - en' ) flag = 0 #     2-  for event in longpoll.listen(): if event.type == VkEventType.MESSAGE_NEW and event.to_me and event.text: #     trTo = event.text #    if event.from_user: vk.messages.send( #  user_id=event.user_id, message=' ,    ' ) elif event.from_chat: vk.messages.send( # ,    chat_id=event.chat_id, message=' ,    ' ) for event in longpoll.listen(): if event.type == VkEventType.MESSAGE_NEW and event.to_me and event.text: #     trNormal = 1 #    try: #,     trFrom = translate.detect(event.text) #  trResult = translate.translate(event.text, trFrom + '-' + trTo) # except Exception as e: # -    trNormal = 0 #   print("Exception:", e) #   pass if trNormal == 1: #   if event.from_user: vk.messages.send( #  user_id=event.user_id, message='  «.» translate.yandex.ru\n' + str(trResult['text']) ) flag = 1 #  2-  break elif event.from_chat: vk.messages.send( # ,    chat_id=event.chat_id, message='  «.» translate.yandex.ru\n' + str(trResult['text']) ) flag = 1 break if trNormal == 0: #   if event.from_user: vk.messages.send( #  user_id=event.user_id, message='  ' #..    99%  - ,          ) flag = 1 #  2-  break elif event.from_chat: vk.messages.send( # ,    chat_id=event.chat_id, message='  ' ) flag = 1 break if flag == 1: #     2-  break 

What are exceptions and what they eat


Exceptions are such a thing that, in case of an error, it runs and tells us about it. To handle exceptions, use the try - except construct.

Let's try implementing our code without this construct.

-Transfer
-What language? Specify in two letters.
For example: Russian - ru, English - en
-en
-Enter a phrase to translate.
-Hi Habr
-Translated by Yandex.Translate service translate.yandex.ru
['Hi Habr']

Well, it works, and why do we need your exceptions?

But why:
-Transfer
-What language? Specify in two letters.
For example: Russian - ru, English - en
-abracadabra
-Enter a phrase to translate.
-Hi Habr
...

Meanwhile in the console:

 Traceback (most recent call last): File "C:\Py_trash\habrex.py", line 112, in <module> main() File "C:\Py_trash\habrex.py", line 78, in main trResult = translate.translate(event.text, trFrom + '-' + trTo) File "C:\Users\Hukuma\AppData\Local\Programs\Python\Python37-32\lib\site-packages\yandex_translate\__init__.py", line 150, in translate raise YandexTranslateException(status_code) yandex_translate.YandexTranslateException: None 

And with exceptions:

-Transfer
-What language? Specify in two letters.
For example: Russian - ru, English - en
-Abracadabra
-Enter a phrase to translate.
-Hi Habr
- Wrong language entered

I will analyze the try - except construction in more detail:

 try: #sample code except Exception: #       

I will give an example from wikipedia api:

  try: result = str(wikipedia.summary(event.text)) except wikipedia.exceptions.PageError: print('  ') except wikipedia.exceptions.DisambiguationError: print('') 

As you understand, there may be several exceptions.

At this I say goodbye to you. Good luck

Source: https://habr.com/ru/post/428790/


All Articles