【问题标题】:How integrate in my python code the google translator api correctly?如何在我的 python 代码中正确集成谷歌翻译 api?
【发布时间】:2022-01-14 16:27:45
【问题描述】:

我实际上正在做一个将消息从一个频道转发到另一个频道的机器人。 它应用了一些更改,例如替换单词、避免语音或图像(如我的代码上部所定义的那样),并且以这种方式完美运行。

但我想添加一个功能,在对其执行操作之后翻译消息并转发结果:

" [对其进行操作后转发的消息]


[在对其进行操作并翻译成法语后转发的消息]

"

所以有实际代码,我导入了谷歌翻译 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

【问题讨论】:

  • How to Ask: "请勿发布代码、数据、错误消息等的图片 - 将文本复制或输入到问题中。"另外我真的建议创建一个minimal reproducible example,这里有将近 200 行代码,可能不一定都是。

标签: python telegram-bot google-translation-api


【解决方案1】:

基于example of 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."

根据您的错误,您尝试使用 event 来使用 Translator() 类的属性。不要使用event,您应该使用Translator() 创建一个对象并使用该对象执行翻译。

假设message_text 是一个字符串。您的代码应该类似于下面的代码。

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

请注意,googletrans 不是官方的 Google 翻译 API,因此如果您发送的翻译请求过多,将会受到限制。我强烈建议使用official Google Translate API,这样您就不会遇到前进的限制问题。 请参阅以下来自 googletrans 的警告 文档:

  • 单个文本的最大字符数限制为 15k。
  • 由于 google translate 网页版的限制,此 API 不保证该库在任何时候都能正常工作。 (所以 如果您不关心稳定性,请使用此库。)
  • 如果您想使用稳定的 API,我强烈建议您使用Google’s official translate API
  • 如果您收到 HTTP 5xx 错误或类似 #6 的错误,可能是因为 Google 已禁止您的客户端 IP 地址。

【讨论】:

    猜你喜欢
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    • 2010-10-10
    相关资源
    最近更新 更多