[英]How integrate in my python code the google translator api correctly?
我實際上正在做一個將消息從一個頻道轉發到另一個頻道的機器人。 它應用了一些更改,例如替換單詞,避免使用語音或圖像(如我的代碼上部定義的那樣),並且以這種方式完美運行。
但我想添加一個功能,在對其執行操作之后翻譯消息並轉發結果,如下所示:
" [對其進行操作后轉發的消息]
[在對其進行操作並翻譯成法語后轉發的消息]
"
所以有實際的代碼,我導入了谷歌翻譯 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()
基於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()
class 的屬性。 而不是使用event
,您應該使用Translator()
創建一個 object 並使用 object 執行翻譯。
假設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,因此如果您發送的翻譯請求過多,將會有限制。 我強烈建議使用官方的 Google 翻譯 API ,這樣您就不會遇到限制問題。 請參閱以下來自 googletrans 文檔的警告:
- 單個文本的最大字符數限制為 15k。
- 由於谷歌翻譯 web 版本的限制,此 API 不保證該庫將始終正常工作。 (所以如果你不關心穩定性,請使用這個庫。)
- 如果你想使用穩定的 API,我強烈建議你使用谷歌官方翻譯 API 。
- 如果您收到 HTTP 5xx 錯誤或類似 #6 的錯誤,可能是因為 Google 已禁止您的客戶端 IP 地址。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.