-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathmain.py
516 lines (440 loc) · 20.2 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
#!/usr/bin/python3.7
import re
from configparser import ConfigParser
from sys import path as syspath
from aiogram import Bot, Dispatcher, executor, types
from aiogram.types import (InlineKeyboardButton, InlineQuery,
InlineQueryResultArticle, InputTextMessageContent)
from loguru import logger
from sentry_sdk import capture_message, init
from api.balancer import trans
from tool.clean import filter_bot
from tool.detect import is_command, lang
# 初始化 bot
try:
cfg = ConfigParser()
cfg.read(syspath[0] + '/config/config.ini')
API_TOKEN = cfg.get('bot', 'token')
ADMIN_ID = cfg.get('bot', 'admin')
SENTRY_SDK = cfg.get('sentry', 'sdk')
GROUP_LIST = [] if cfg.get('group', 'custom') == 'None' else cfg.get(
'group', 'enabled').split(',')
GROUP_LIST_CUSTOM = [] if cfg.get(
'group', 'custom') == 'None' else cfg.get('group', 'custom').split(',')
LANG = cfg.get('lang', 'destination') # 暂时没有使用
except Exception as e:
logger.exception("Config:" + str(e))
capture_message('Config: ' + str(e))
exit()
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
init(SENTRY_SDK, traces_sample_rate=1.0)
delete_btn = types.InlineKeyboardMarkup(resize_keyboard=True, selective=True)
delete_btn.insert(InlineKeyboardButton(text='🗑️', callback_data='delete'))
# 定义函数
@dp.callback_query_handler(text='delete')
async def _(call: types.CallbackQuery):
try:
await call.message.delete()
await call.answer(text="该消息已删除")
except Exception as e:
logger.exception("Delete:" + str(e))
capture_message('Delete: ' + str(e))
def query(text: str, to_lang: str = None) -> str: # type: ignore
try:
if to_lang == None:
if lang(text) == 'zh':
to_lang = 'en'
elif lang(text) == 'en':
to_lang = 'zh'
else:
to_lang = 'zh'
else:
pass
result = trans(text, to_lang)
return result
except Exception as e:
logger.exception("Query:")
capture_message('Query: ' + str(e))
def translate_msg(
message: types.Message,
offset: int = 0,
lang: str = None, # type: ignore
pattern: str = None) -> str: # type: ignore
if message.reply_to_message: # 如果是回复则取所回复消息文本
text = message.reply_to_message.text
else: # 如果不是回复则取命令后文本
text = message.text[offset:] # 去除命令文本
try:
text = filter_bot(text)
except:
pass
text = re.sub(pattern, '', text) if pattern else text
if len(text) == 0:
if message.reply_to_message:
logger_msg(message)
result = query(text, to_lang=lang)
return result
else:
result = '''忘记添加需要翻译的文本?请在命令后添加需要翻译的话,例如:
/en 你好
'''
return \
result
else:
logger_msg(message)
result = query(text, to_lang=lang)
# logger.info(result)
return \
result
def translate_auto(
message: types.Message,
offset: int = 0,
lang: str = None, # type: ignore
pattern: str = None) -> str: # type: ignore
if message.reply_to_message and (len(
re.sub(
r'^(translate|trans|tran|翻译|中文|Chinese|zh|英文|英语|English|en)',
"", message.text)) <= 1): # 如果是回复则取所回复消息文本
text = message.reply_to_message.text
else: # 如果不是回复则取命令后文本
text = message.text[offset:] # 去除命令文本
text = text.replace('@fanyi_bot', '').strip()
if pattern:
text = re.sub(pattern, '', text)
if len(text) == 0:
if message.reply_to_message:
logger_msg(message)
result = query(text)
return result
else:
result = '''忘记添加需要翻译的文本?请在命令后添加需要翻译的话,例如:
/en 你好
'''
return \
result
else:
logger_msg(message)
result = query(text)
# logger.info(result)
return result
def logger_msg(message: types.Message) -> None:
chat_type = message.chat.type
user = message.from_user.username
user_id = message.from_user.id
group = message.chat.title
group_id = message.chat.id
chat_name = message.chat.username or message.from_user.username
if group:
log_msg = f'[{chat_type}, %{group}, %{group_id}, &{chat_name}, \\@{user}, #{user_id}] {message.text}'
logger.info(log_msg)
else:
log_msg = f'[{chat_type}, @{chat_name}, #{user_id}] {message.text} '
logger.info(log_msg)
####################################################################################################
# 欢迎词
@dp.message_handler(commands=['start', 'welcome', 'about', 'help'])
async def command_start(message: types.Message) -> None:
intro = '''使用说明:
- 私聊机器人,自动翻译文字消息;
- 群聊中添加机器人,使用命令翻译指定消息;
- 任意聊天框,输入 @fanyi_bot 实时翻译。
使用样例:
/fy 检测语言并翻译
/zh Translate a sentence into Chinese.
/en 翻译到英文
最近更新
- [2020.11.14] 修复了一个上游引起的 BUG
加入群组 @fanyi_group 参与讨论。'''
await bot.send_chat_action(message.chat.id, action="typing")
await message.answer(intro)
####################################################################################################
# 翻译命令
####################################################################################################
# 中英文
@dp.message_handler(commands=['fy', 'tr', '翻译'])
async def command_fy(message: types.Message) -> None:
await bot.send_chat_action(message.chat.id, action="typing")
result = translate_msg(message, 3) # None -> Chinese + English
await message.reply(result, reply_markup=delete_btn)
# 中文
@dp.message_handler(commands=['zh'])
async def command_zh(message: types.Message) -> None:
await bot.send_chat_action(message.chat.id, action="typing")
result = translate_msg(message, 3, 'zh')
await message.reply(result, reply_markup=delete_btn)
# 英文
@dp.message_handler(commands=['en'])
async def command_en(message: types.Message) -> None:
await bot.send_chat_action(message.chat.id, action="typing")
result = translate_msg(message, 3, 'en')
await message.reply(result, reply_markup=delete_btn)
@dp.message_handler(commands=['id'])
async def command_id(message: types.Message) -> None:
await bot.send_chat_action(message.chat.id, action="typing")
result = str(message.chat.id)
await message.reply(result, reply_markup=delete_btn)
# @logger.catch()
@dp.message_handler(commands=['auto'])
async def command_enable_auto_translation(
message: types.Message,
GROUP_LIST_CUSTOM: list = GROUP_LIST_CUSTOM) -> None:
await bot.send_chat_action(message.chat.id, action="typing")
if str(message.chat.id) in GROUP_LIST_CUSTOM or str(
message.chat.id) in GROUP_LIST:
await message.reply('已经是启用状态 / Already enabled',
reply_markup=delete_btn)
else:
try:
# logger.info(type(GROUP_LIST_CUSTOM))
GROUP_LIST_CUSTOM.append(str(message.chat.id))
cfg = ConfigParser()
cfg_path = syspath[0] + '/config/config.ini'
cfg.read(cfg_path)
cfg.set('group', 'custom', ','.join(GROUP_LIST_CUSTOM))
with open(cfg_path, 'w') as configfile:
cfg.write(configfile)
await message.reply('自动翻译已启动 / Auto-translation enabled',
reply_markup=delete_btn)
except Exception as e:
logger.warning('Failed:' + str(e))
await message.reply('自动翻译启动失败 / Auto-translation enabling failed',
reply_markup=delete_btn)
# @logger.catch()
@dp.message_handler(commands=['not'])
async def command_disable_auto_translation(
message: types.Message,
GROUP_LIST_CUSTOM: list = GROUP_LIST_CUSTOM) -> None:
await bot.send_chat_action(message.chat.id, action="typing")
if str(message.chat.id) in GROUP_LIST_CUSTOM:
await message.reply('已经是关闭状态 / Already disabled',
reply_markup=delete_btn)
else:
try:
GROUP_LIST_CUSTOM.remove(str(message.chat.id))
cfg = ConfigParser()
cfg_path = syspath[0] + '/config/config.ini'
cfg.read(cfg_path)
cfg.set('group', 'custom', ','.join(GROUP_LIST_CUSTOM))
with open(cfg_path, 'w') as configfile:
cfg.write(configfile)
await message.reply('自动翻译已关闭 / Auto-translation disabled',
reply_markup=delete_btn)
except Exception as e:
logger.warning('Failed:' + str(e))
await message.reply('自动翻译关闭失败 / Auto-translation disabling failed',
reply_markup=delete_btn)
####################################################################################################
# 自然指令
####################################################################################################
@dp.message_handler(regexp='^(translate|trans|tran|翻译) ')
async def keyword_fy(message: types.Message) -> None:
result = translate_msg(message, pattern='^(translate|trans|tran|翻译) ')
await bot.send_chat_action(message.chat.id, action="typing")
await message.reply(result, reply_markup=delete_btn)
@dp.message_handler(regexp='^(英文|英语|English|en) ')
async def keyword_en(message: types.Message) -> None:
result = translate_msg(message, lang='en', pattern='^(英文|英语|English|en) ')
await bot.send_chat_action(message.chat.id, action="typing")
await message.reply(result, reply_markup=delete_btn)
@dp.message_handler(regexp='^(中文|Chinese|zh) ')
async def keyword_zh(message: types.Message) -> None:
result = translate_msg(message, lang='zh', pattern='^(中文|Chinese|zh) ')
await bot.send_chat_action(message.chat.id, action="typing")
await message.reply(result, reply_markup=delete_btn)
@dp.message_handler(regexp='^(translate|trans|tran|翻译)')
async def reply_keyword_fy(message: types.Message) -> None:
if message.reply_to_message:
result = translate_msg(message, pattern='^(translate|trans|tran|翻译)')
await bot.send_chat_action(message.chat.id, action="typing")
await message.reply(result, reply_markup=delete_btn)
@dp.message_handler(regexp='^(英文|English|en)')
async def reply_keyword_en(message: types.Message) -> None:
if message.reply_to_message:
result = translate_msg(message, lang='en', pattern='^(英文|English|en)')
await bot.send_chat_action(message.chat.id, action="typing")
await message.reply(result, reply_markup=delete_btn)
@dp.message_handler(regexp='^(中文|Chinese|zh)')
async def reply_keyword_zh(message: types.Message) -> None:
if message.reply_to_message:
result = translate_msg(message, lang='zh', pattern='^(中文|Chinese|zh)')
await bot.send_chat_action(message.chat.id, action="typing")
await message.reply(result, reply_markup=delete_btn)
####################################################################################################
# 私聊自动检测语言并翻译
####################################################################################################
@dp.callback_query_handler(text='translate')
async def query_translate(call: types.CallbackQuery) -> None:
origin_msg = call.message.text.split('▸')[1].split('\n')[0]
translated_msg = call.message.text.split('▸')[-1]
# await bot.send_chat_action(message.chat.id, action="typing")
await call.answer(text="消息已翻译 Message translated")
await bot.edit_message_text("`" + call.message.text.split('▸')[0] + "`" + \
query(translated_msg), call.message.chat.id, call.message.message_id,
parse_mode="markdown")
@dp.callback_query_handler(text=['zh', 'en', 'ja', 'ru', 'vi'])
async def query_specify(call: types.CallbackQuery) -> None:
languages = {'zh': '⚙️', 'en': '⚙️', 'ja': '⚙️', 'ru': '⚙️', 'vi': '⚙️'}
# await bot.send_chat_action(message.chat.id, action="typing")
reply_message = call.message.reply_to_message
reply_text = reply_message.text
action_btn = types.InlineKeyboardMarkup(resize_keyboard=True,
selective=True)
action_btn.insert(
InlineKeyboardButton(text=f'{languages[call.data]}',
callback_data='select'))
action_btn.insert(InlineKeyboardButton(text='🗑️', callback_data='del'))
logger.info('\n\n')
log_msg = f"[Group] {reply_message.chat.title}({reply_message.chat.id})"
logger.info(log_msg)
try:
await call.answer(text=f"正在翻译 Translating...")
await bot.edit_message_text(query(reply_text, call.data),
call.message.chat.id,
call.message.message_id,
parse_mode="markdown",
reply_markup=action_btn)
except Exception as e:
logger.exception('Answer: ' + str(e))
capture_message('Answer: ' + str(e))
# await call.answer(text="消息已翻译 Message translated")
@dp.callback_query_handler(text='del')
async def query_delete(call: types.CallbackQuery) -> None:
# await bot.send_chat_action(message.chat.id, action="typing")
await call.answer(text="消息已删除 Message deleted")
await call.message.delete()
@dp.callback_query_handler(text='select')
async def query_select(call: types.CallbackQuery) -> None:
# await bot.send_chat_action(message.chat.id, action="typing")
action_btn = types.InlineKeyboardMarkup(resize_keyboard=True,
selective=True)
action_btn.insert(InlineKeyboardButton(text='中文', callback_data='zh'))
action_btn.insert(InlineKeyboardButton(text='English', callback_data='en'))
action_btn.insert(InlineKeyboardButton(text='にほんご', callback_data='ja'))
# action_btn.insert(InlineKeyboardButton(text='🇷🇺', callback_data='ru'))
# action_btn.insert(InlineKeyboardButton(text='🇻🇳', callback_data='vi'))
action_btn.insert(InlineKeyboardButton(text='🗑️', callback_data='del'))
try:
await call.answer(text="请选择一种语言 Please select a language")
await bot.edit_message_text(call.message.text,
call.message.chat.id,
call.message.message_id,
parse_mode="markdown",
reply_markup=action_btn)
except Exception as e:
logger.exception('Answer: ' + str(e))
capture_message('Answer: ' + str(e))
@dp.callback_query_handler(text='mute')
async def query_mute(call: types.CallbackQuery) -> None:
origin_msg = call.message.text.split('▸')[1].split('\n')[0]
# await bot.send_chat_action(message.chat.id, action="typing")
try:
await call.answer(text="显示原消息 Original message showed")
await bot.edit_message_text(origin_msg,
call.message.chat.id,
call.message.message_id,
parse_mode="markdown")
except Exception as e:
logger.exception('Answer: ' + str(e))
capture_message('Answer: ' + str(e))
####################################################################################################
# 群聊/私聊
####################################################################################################
@dp.message_handler(content_types=types.message.ContentType.TEXT)
async def text_translate(message: types.Message,
GROUP_LIST_CUSTOM: list = GROUP_LIST_CUSTOM) -> None:
chat_type = message.chat.type
chat_id = message.chat.id
action_btn = types.InlineKeyboardMarkup(resize_keyboard=True,
selective=True)
action_btn.insert(
InlineKeyboardButton(text='语言 Language', callback_data='select'))
action_btn.insert(InlineKeyboardButton(text='🗑️', callback_data='delete'))
if chat_type == 'private':
await bot.send_chat_action(message.chat.id, action="typing")
log_msg = f"[Private] {message.from_user.first_name}(https://t.me/{message.from_user.username}, {message.from_user.id})"
logger.info(log_msg)
result = query(message.text)
try:
await message.reply(result, disable_notification=True)
except Exception as e:
logger.exception('Reply: ' + str(e))
capture_message('Reply: ' + str(e))
elif ((chat_type == 'group') or
(chat_type == 'supergroup')) and (str(chat_id) in GROUP_LIST or
str(chat_id) in GROUP_LIST_CUSTOM):
log_msg = f"[Group] {message.chat.title}({message.chat.id})"
logger.info(log_msg)
await bot.send_chat_action(message.chat.id, action="typing")
if is_command(message.text) == False:
result = query(message.text)
try:
await message.reply(result,
parse_mode='markdown',
disable_notification=True,
disable_web_page_preview=True,
reply_markup=action_btn)
except Exception as e:
logger.exception('Reply: ' + str(e))
capture_message('Reply: ' + str(e))
else:
logger.info('PASS: a command detected')
pass
else: # 过滤所有群聊、频道
# log_msg = f"[Ignored] {message.chat.title}({message.chat.id} not enabled.)"
# logger.debug(log_msg)
# logger.info('PASS: group not enabled / channel')
pass
@dp.message_handler()
async def text_others(message: types.Message) -> None:
logger.info('Other types')
try:
await bot.send_chat_action(message.chat.id, action="typing")
result = query(message.text)
except Exception as e:
logger.exception("Others:" + str(e))
capture_message('Others', str(e))
result = '? ? ?'
await message.answer(result)
####################################################################################################
# 行内查询
####################################################################################################
@dp.inline_handler()
async def inline(inline_query: InlineQuery) -> None:
text = inline_query.query or '输入以翻译 Input to Translate...'
user = inline_query.from_user.username
user_id = inline_query.from_user.id
end_str = ''
if len(text) >= 256:
end_str = '\n\n(达到长度限制,请私聊翻译全文)'
if text == '输入以翻译 Input to Translate...' or len(text) <= 2:
pass
else:
# log_msg = f'[inline, @{user}, #{user_id}] {text} '
zh_str = query(text, 'zh')
en_str = query(text, 'en')
# jp_str = query(text, 'ja')
items = [
InlineQueryResultArticle(
id=str(0),
title=f'{en_str.capitalize()}',
description='English',
input_message_content=InputTextMessageContent(
en_str, disable_web_page_preview=True),
),
InlineQueryResultArticle(
id=str(1),
title=f'{zh_str.capitalize()}',
description='中文',
input_message_content=InputTextMessageContent(
zh_str, disable_web_page_preview=True),
)
]
await bot.answer_inline_query(
inline_query.id,
results=items, # type: ignore
cache_time=500)
if __name__ == '__main__':
logger.info('Working...', )
# executor.start_polling(dp, skip_updates=True)
executor.start_polling(dp)