【发布时间】: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()
【问题讨论】:
-
How to Ask: "请勿发布代码、数据、错误消息等的图片 - 将文本复制或输入到问题中。"另外我真的建议创建一个minimal reproducible example,这里有将近 200 行代码,可能不一定都是。
标签: python telegram-bot google-translation-api