简体   繁体   English

如何在我的 python 代码中正确集成谷歌翻译器 api?

[英]How integrate in my python code the google translator api correctly?

I'm actually doing a bot that forward messages from a channel to another channel.我实际上正在做一个将消息从一个频道转发到另一个频道的机器人。 It apply some changes like replace words, avoid voice or images ( as defined in the upper part of my code), and works perfectly this way.它应用了一些更改,例如替换单词,避免使用语音或图像(如我的代码上部定义的那样),并且以这种方式完美运行。

But i'd like to add a functionally that translate the message AFTER the operations performed on it and forward the result like that:但我想添加一个功能,在对其执行操作之后翻译消息并转发结果,如下所示:

" [message forwarded after operations done on it] " [对其进行操作后转发的消息]


[ message forwarded after operations done on it AND translated to French] [在对其进行操作并翻译成法语后转发的消息]

" "

So there's the actual code, I imported google translate api, but don't understand where doing the operations, and how to concatenate without sending me those errors (cf. screenshot)所以有实际的代码,我导入了谷歌翻译 api,但不明白在哪里进行操作,以及如何在不向我发送这些错误的情况下连接(参见屏幕截图)

from telethon import TelegramClient, events
from telethon.tl.types import PeerChannel, MessageActionChatEditPhoto
from telethon.tl.functions.messages import GetBotCallbackAnswerRequest, DeleteMessagesRequest
from datetime import datetime

from googletrans import Translator

import time
import configparser
import re
import os
import logging
import sqlite3
import sys
import asyncio
       

def channel_group(config):
    channel_group_dic = {}
    channel_group_list = []

    for channel_group_from, channel_group_to in config.items('Settings'):
        firts_letter = channel_group_from[:1]
        if firts_letter.lower() == "g" or firts_letter.lower() == "c" or firts_letter.lower() == "b" or firts_letter.lower() == "u":
            channel_group_list.append(int(channel_group_from[1:]))
            channel_group_split = channel_group_to.split(";")
            temp_channel_group_list = []
            for channel_group in channel_group_split:
                first_letter_channel_group = channel_group[:1]
                if first_letter_channel_group.lower() == "g":
                    temp_channel_group_list.append(int("-"+channel_group[1:]))
                if first_letter_channel_group.lower() == "c":
                    temp_channel_group_list.append(int("-100"+channel_group[1:]))
            channel_group_dic[int(channel_group_from[1:])]=temp_channel_group_list
    return channel_group_list, channel_group_dic

        
def eval_list(string):
    string_list = None
    try:
        if isinstance(eval(string), list):
            string_list = eval(string)
    except Exception as e:
        print("Error :",string)
    return string_list

def replace_list(string):
    replace_list = []
    for string in replace.split(";"):
        string_list = eval_list(string)
        if string_list:
            replace_list.append(string_list)
    return replace_list


def skip_list(string):
    skip_list = []
    string_list = eval_list(string)
    if string_list:
        skip_list = string_list
    return skip_list


def skip_message_image_list(string):
    channel_group_list = []
    for channel_group_from in string.split(";"):
        firts_letter = channel_group_from[:1]
        if firts_letter.lower() == "g" or firts_letter.lower() == "c" or firts_letter.lower() == "b" or firts_letter.lower() == "u":
            channel_group_list.append(int(channel_group_from[1:]))
    return channel_group_list
        

    
 
config = configparser.ConfigParser()

config.read('config.ini')


if not os.path.exists('config.ini'):
    print ("config.ini file not found")
    os.system("pause >nul")
    sys.exit()
    
api_id =  config.get('Settings', 'api_id')
api_hash = config.get('Settings', 'api_hash')
replace = config.get('Settings', 'replace')
allow_voice = config.getboolean('Settings', 'allow_voice')
allow_gif = config.getboolean('Settings', 'allow_gif')
skip = config.get('Settings', 'skip')
skip_message_image = config.get('Settings', 'skip_message_image')



skip_message_image_list = skip_message_image_list(skip_message_image)
replace_list = replace_list(replace)
skip_list = skip_list(skip)
channel_group_list_from, channel_group_dic_to = channel_group(config)

##print(channel_group_list_from)
##print(channel_group_dic_to)
##print(replace_list)

if not channel_group_list_from:
    sys.exit("Error")


client = TelegramClient('session', api_id, api_hash)


@client.on(events.NewMessage(chats=channel_group_list_from,outgoing=False))
async def new_message_handler(event):

##        print(event)

        if event.is_channel:
            channel_group_id_from = event.message.peer_id.channel_id
        elif event.is_group:
            channel_group_id_from = event.message.peer_id.chat_id
        else:
            channel_group_id_from = event.message.peer_id.user_id
                   
        channel_group_message_id = event.message.id

        channel_group_message_text = event.message.message

        if event.photo:
            if channel_group_id_from in skip_message_image_list:
                print('Message Image Skipped ### ID:', channel_group_id_from)
                return
  
        for skip in skip_list:
            if skip in channel_group_message_text:
                print('Message Skipped:', channel_group_message_text," ### ID:", channel_group_id_from)
                return
                

        found = False
        for replace in replace_list:
            if replace[0] in channel_group_message_text:
                found = True
                event.message.message = channel_group_message_text.replace(replace[0],replace[1])

        channel_group_message = event.message
        
        message_text = event.raw_text
   **##   message_text_a_translate = event.raw_text
        
        
        
       message_translated = event.translator.translate( message_text, dest='fr', src='en')
       ## print('Message:', channel_group_message_text," ### ID:", channel_group_id_from)**

        if found:
          
            print('Message Edited in EN:', message_text)#affichage du message original apres traitement en anglais
            print('message Edited in FR :', message_translated)#affichage du message apres traitement et traduction en FRANCAIS
            
        if event.voice and not allow_voice:
            return

        if event.gif and not allow_gif:
            return
            
        for channel_group_to in channel_group_dic_to[channel_group_id_from]:            
            try:
                mirror_message = await client.send_message(channel_group_to, message=channel_group_message)
            except Exception as e:
                print("Error:",e)        
                
if __name__ == '__main__':
    client.start()
    print("Waiting Messages...")
    client.run_until_disconnected()
 

Terminal Error终端错误

Based from the example of googltrans , the sample usage of it is:基于googltrans的示例,它的示例用法是:

from googletrans import Translator

translator = Translator()
trans_text = translator.translate('안녕하세요.')
print(trans_text)
 # output: Translated(src=ko, dest=en, text=Hello., pronunciation=None, extra_data="{'confiden...")
print(trans_text.text) # use .text to get the translated word
 # output: "Hello."

Based from your error you tried to use event to use the attributes of the Translator() class.根据您的错误,您尝试使用event来使用Translator() class 的属性。 Instead of using event , you should create an object using Translator() and use the object to perform translation.而不是使用event ,您应该使用Translator()创建一个 object 并使用 object 执行翻译。

Assuming message_text is a string.假设message_text是一个字符串。 Your code should somewhat look like the one below.您的代码应该有点像下面的代码。

from googletrans import Translator

translator = Translator()
message_translated = translator.translate(message_text, dest='fr', src='en')
print(message_translated.text) # this should contain the translated text

Keep in mind that googletrans is not the official Google Translation API so there will be limits applied if you are sending too much translation requests.请记住, googletrans不是官方的 Google 翻译 API,因此如果您发送的翻译请求过多,将会有限制。 I highly suggest to use the official Google Translate API so you won't be encountering limitation issues moving forward.我强烈建议使用官方的 Google 翻译 API ,这样您就不会遇到限制问题。 See warning below from googletrans documentation:请参阅以下来自 googletrans 文档的警告

  • The maximum character limit on a single text is 15k.单个文本的最大字符数限制为 15k。
  • Due to limitations of the web version of google translate, this API does not guarantee that the library would work properly at all times.由于谷歌翻译 web 版本的限制,此 API 不保证该库将始终正常工作。 (so please use this library if you don't care about stability.) (所以如果你不关心稳定性,请使用这个库。)
  • If you want to use a stable API, I highly recommend you to use Google's official translate API .如果你想使用稳定的 API,我强烈建议你使用谷歌官方翻译 API
  • If you get HTTP 5xx error or errors like #6, it's probably because Google has banned your client IP address.如果您收到 HTTP 5xx 错误或类似 #6 的错误,可能是因为 Google 已禁止您的客户端 IP 地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM