-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
69 lines (55 loc) · 1.88 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import logging
import os
import re
from googletrans import Translator
from telegram import Update
from telegram.ext import Updater, MessageHandler, Filters, CallbackContext
def has_cyrillic(text):
"""
Checking the text for the Cyrillic alphabet
:param text: Text to check for Cyrillic
"""
return bool(re.search('[а-яА-Я]', text))
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)
def is_photo(len):
"""
Checking is message with photo
:param len: Size of the photo tuple in the message
:return: boolean value (True - message with photo, False - message without photo)
"""
return bool(len)
def translate(update: Update, context: CallbackContext) -> None:
"""
Translating message in telegram's chat with the Cyrillic
"""
if is_photo(len(update.message.photo)):
# Take text from photo caption
is_cyr = has_cyrillic(str(update.message.caption))
mes = update.message.caption
else:
# Take text from message itself
is_cyr = has_cyrillic(update.message.text)
mes = update.message.text
if is_cyr:
try:
# Translate message to English
eng_message = translator.translate(mes, dest="en").text
# Reply message with translated text
update.message.reply_text(eng_message, quote=True)
except Exception as e:
logger.error(f"Exception during translate: {e}")
def main():
# Initialize Update
updater = Updater(os.environ.get('TOKEN'))
dispatcher = updater.dispatcher
# Add translating handler
dispatcher.add_handler(MessageHandler((Filters.text | Filters.photo) & ~Filters.command, translate))
# Start bot
updater.start_polling()
updater.idle()
if __name__ == '__main__':
translator = Translator()
main()