Created
March 6, 2022 17:56
-
-
Save Aketzu/9a6f41b4af0164ac4d97f3a51b7fb58e to your computer and use it in GitHub Desktop.
UkrzalInfo translator bot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from telethon import TelegramClient, events | |
from telethon.tl.types import PeerUser, PeerChat, PeerChannel | |
import os | |
import sys | |
from google.cloud import translate_v3 as translate | |
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/path/key.json" | |
gclient = translate.TranslationServiceClient() | |
def translate(text): | |
response = gclient.translate_text( | |
request={ | |
"parent": "projects/xxx-1234", | |
"contents": [text], | |
"mime_type": "text/plain", | |
"source_language_code": "uk", | |
"target_language_code": "en" | |
} | |
) | |
return response.translations[0].translated_text | |
CHAN_UKRZALINFO=1419524556 | |
CHAN_TEMP=1234 | |
CHAN_TRANSLATED=4567 | |
# Message flow: | |
# Standard user joins the UkrzalInfo channel and listens for messages. Seen messages are forwarded to temp channel | |
# Bot user is added to temp channel and on message will forward it to translated channel + reply with translation | |
async def handlemsg(event): | |
if not isinstance(event.message.peer_id, PeerChannel): | |
return | |
# normal user | |
if event.message.peer_id.channel_id == CHAN_UKRZALINFO: | |
print(event.stringify()) | |
await tgcli.forward_messages(CHAN_TEMP, event.message.id, event.message.peer_id); | |
# bot | |
if event.message.peer_id.channel_id == CHAN_TEMP: | |
print(event.stringify()) | |
ret = await tgcli.forward_messages(CHAN_TRANSLATED, event.message.id, event.message.peer_id); | |
t2 = translate(event.message.message); | |
await tgcli.send_message(entity=CHAN_TRANSLATED, message=t2, reply_to=ret.id); | |
def main(): | |
global tgcli | |
if sys.argv[1] == 'user': | |
print("start user") | |
tgcli = TelegramClient('User', 1234, 'a1b2c3').start(phone='+35812345678') | |
tgcli.add_event_handler(handlemsg, events.NewMessage) | |
tgcli.run_until_disconnected() | |
elif sys.argv[1] == 'bot': | |
print("start bot") | |
tgcli = TelegramClient('xbot', 1234, 'a1b2c3').start(bot_token='1234:ABCD') | |
tgcli.add_event_handler(handlemsg, events.NewMessage) | |
tgcli.run_until_disconnected() | |
print("exiting") | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment