Skip to content

Instantly share code, notes, and snippets.

@d33tah
Created August 13, 2022 13:30
Show Gist options
  • Save d33tah/58e9eae6cb6b415f5d8126852507cb93 to your computer and use it in GitHub Desktop.
Save d33tah/58e9eae6cb6b415f5d8126852507cb93 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3.8
import unicodedata
import atexit
import sys
import logging
import time
import asyncio
import nio
from google.cloud import translate
client = nio.AsyncClient("https://matrix.org", "@google-translate-bot:matrix.org")
@atexit.register
def crashloop_protection(*args, **kwargs):
time.sleep(60.0)
async def sendmsg(room_id, msg) -> None:
result = await client.room_send(
room_id=room_id,
message_type="m.room.message",
content={
"msgtype": "m.text",
"body": msg,
}
)
logging.info('sent notification(msg=%r) => %s', msg, result)
def is_char_cyrillic(c):
try:
return unicodedata.name(c).startswith('CYRILLIC ')
except ValueError:
return False
def translate_text(text, project_id="modern-sublime-359312"):
client = translate.TranslationServiceClient()
location = "global"
parent = f"projects/{project_id}/locations/{location}"
response = client.translate_text(
request={
"parent": parent,
"contents": [text],
"mime_type": "text/plain",
"target_language_code": "pl",
}
)
return response.translations[0].translated_text
async def message_callback(room, event) -> None:
msg = str.split(event.body, maxsplit=1)[-1]
if sum([int(is_char_cyrillic(x)) for x in msg]) / len(msg) < 0.6:
return
translated = translate_text(msg)
await sendmsg(room.room_id, translated)
async def main():
client.add_event_callback(message_callback, nio.RoomMessageText)
await client.login(open('haslo.txt').read().strip())
sys.stdout.flush()
await client.sync_forever(timeout=30000)
if __name__ == "__main__":
logging.basicConfig(level="DEBUG")
asyncio.get_event_loop().run_until_complete(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment