Skip to content

Commit

Permalink
Merge pull request #223 from MikiEremiki/develop
Browse files Browse the repository at this point in the history
Fix. Повышение качества обработки ошибок
  • Loading branch information
MikiEremiki authored Dec 15, 2024
2 parents f8e36d1 + 4acf5cc commit e0b6f63
Show file tree
Hide file tree
Showing 7 changed files with 104 additions and 35 deletions.
5 changes: 0 additions & 5 deletions src/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,6 @@
.token(config.bot.token.get_secret_value())
.persistence(pickle_persistence)
.defaults(Defaults(parse_mode=ParseMode.HTML))
.get_updates_pool_timeout(3)
.get_updates_write_timeout(7)
.get_updates_connect_timeout(7)
.get_updates_read_timeout(7)
.get_updates_connection_pool_size(2)
.rate_limiter(AIORateLimiter())

.build()
Expand Down
40 changes: 36 additions & 4 deletions src/handlers/error_hl.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ async def error_handler(update: Update,
chat_id = context.config.bot.developer_chat_id
outdated_err_msg = (
'Query is too old and response timeout expired or query id is invalid')
del_err_msg = "Message can't be deleted for everyone"
if isinstance(context.error, HTTPError):
await context.bot.send_message(
chat_id=chat_id,
Expand All @@ -39,15 +40,48 @@ async def error_handler(update: Update,
(context.error.message == outdated_err_msg)):
error_hl_logger.error(context.error.message)
raise ApplicationHandlerStop
elif (hasattr(context.error, 'message') and
(context.error.message == del_err_msg)):
error_hl_logger.error(context.error.message)
text = 'Пожалуйста, выполните команду /start и повторите операцию заново'
message_thread_id = update.effective_message.message_thread_id
try:
await update.effective_message.reply_text(
text=text,
message_thread_id=message_thread_id,
)
except BadRequest as e:
error_hl_logger.error(e)
await update.effective_chat.send_message(
text=text,
message_thread_id=message_thread_id,
)
elif (isinstance(context.error, TimedOut) or
isinstance(context.error, NetworkError)):
isinstance(context.error, NetworkError) and
not isinstance(context.error, BadRequest)):
error_hl_logger.error(context.error.message)
error_hl_logger.error('Выполнение запроса занимает много времени')
context.user_data['last_update'] = None
text = ('Пожалуйста, подождите 3 секунды и повторите последнее '
'действие, если проблема остается, вызовите /start и '
'повторите запрос заново.')
message_thread_id = update.effective_message.message_thread_id
try:
await update.effective_message.reply_text(
text=text,
message_thread_id=message_thread_id,
)
except BadRequest as e:
error_hl_logger.error(e)
await update.effective_chat.send_message(
text=text,
message_thread_id=message_thread_id,
)
raise ApplicationHandlerStop
else:
text = ('Произошла не предвиденная ошибка\n'
'Пожалуйста, выполните команду /start и повторите операцию заново')
'Пожалуйста, пробуйте повторить последнее действие, '
'или выполните команду /start и повторите операцию заново')
message_thread_id = update.effective_message.message_thread_id
try:
await update.effective_message.reply_text(
Expand All @@ -74,11 +108,9 @@ async def error_handler(update: Update,

message = (
"An exception was raised while handling an update\n"
f"<pre>"
f"update = {html.escape(json.dumps(update_str,
indent=2,
ensure_ascii=False))}"
f"</pre>"
)
try:
await split_message(context, message)
Expand Down
2 changes: 2 additions & 0 deletions src/handlers/main_hl.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
context.user_data['user'] = update.effective_user
context.user_data['common_data'] = {}

context.user_data['last_update'] = None

start_text = '<b>Вас приветствует Бот Бэби-театра «Домик»</b>\n\n'
description = context.bot_data['texts']['description']
address = context.bot_data['texts']['address']
Expand Down
40 changes: 30 additions & 10 deletions src/handlers/reserve_hl.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
InlineKeyboardButton,
ReplyKeyboardRemove,
)
from telegram.error import TimedOut
from telegram.error import TimedOut, NetworkError
from telegram.ext import ContextTypes, ConversationHandler, TypeHandler
from telegram.constants import ChatType, ChatAction

Expand Down Expand Up @@ -357,7 +357,7 @@ async def choice_time(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.effective_chat.send_message(
text=text,
reply_markup=reply_markup,
message_thread_id=update.callback_query.message.message_thread_id
message_thread_id=update.effective_message.message_thread_id
)

reserve_user_data = context.user_data['reserve_user_data']
Expand Down Expand Up @@ -750,19 +750,28 @@ async def get_name_children(
await update.effective_chat.send_action(ChatAction.TYPING)

text = 'Создаю новые билеты в бд...'
reserve_hl_logger.info(text)
message = await update.effective_chat.send_message(text)
ticket_ids = await create_tickets_and_people(
update, context, TicketStatus.CREATED)

text += '\nЗаписываю новый билет в клиентскую базу...'
await message.edit_text(text)
try:
await message.edit_text(text)
except TimedOut as e:
reserve_hl_logger.error(e)
reserve_hl_logger.info(text)
await write_client_reserve(context,
update.effective_chat.id,
chose_base_ticket,
TicketStatus.CREATED.value)

text += '\nУменьшаю кол-во свободных мест...'
await message.edit_text(text)
try:
await message.edit_text(text)
except TimedOut as e:
reserve_hl_logger.error(e)
reserve_hl_logger.info(text)
result = await decrease_free_seat(
context, schedule_event_id, chose_base_ticket_id)
if not result:
Expand All @@ -773,7 +782,11 @@ async def get_name_children(
text += ('\nНе уменьшились свободные места'
'\nНовый билет отменен'
'\nНеобходимо повторить резервирование заново')
await message.edit_text(text)
try:
await message.edit_text(text)
except TimedOut as e:
reserve_hl_logger.error(e)
reserve_hl_logger.info(text)
context.user_data['conv_hl_run'] = False
await clean_context_on_end_handler(reserve_hl_logger, context)
return ConversationHandler.END
Expand All @@ -783,6 +796,7 @@ async def get_name_children(
await message.edit_text(text)
except TimedOut as e:
reserve_hl_logger.error(e)
reserve_hl_logger.info(text)
await processing_successful_payment(update, context)

state = ConversationHandler.END
Expand Down Expand Up @@ -900,7 +914,10 @@ async def send_clients_data(
if not is_skip_ticket(ticket.status):
base_ticket_and_tickets.append((base_ticket, ticket))

await query.edit_message_text('Загружаю данные покупателей')
try:
await query.edit_message_text('Загружаю данные покупателей')
except TimedOut as e:
reserve_hl_logger.error(e)

text = f'#Мероприятие <code>{event_id}</code>\n'
text += (f'Список людей на\n'
Expand All @@ -916,7 +933,10 @@ async def send_clients_data(

state = ConversationHandler.END
context.user_data['STATE'] = state
await query.answer()
try:
await query.answer()
except NetworkError as e:
reserve_hl_logger.error(e)
context.user_data['conv_hl_run'] = False
return state

Expand Down Expand Up @@ -954,9 +974,9 @@ async def get_phone_for_waiting(
user = context.user_data['user']
thread_id = (context.bot_data['dict_topics_name']
.get('Лист ожидания', None))
text = f'#Лист_ожидания\n' \
f'Пользователь @{user.username} {user.full_name}\n' \
f'Запросил добавление в лист ожидания\n' + text
text = (f'#Лист_ожидания\n'
f'Пользователь @{user.username} {user.full_name}\n'
f'Запросил добавление в лист ожидания\n' + text)
await context.bot.send_message(
chat_id=ADMIN_GROUP,
text=text,
Expand Down
4 changes: 2 additions & 2 deletions src/handlers/sub_hl.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
ReplyKeyboardMarkup, KeyboardButton, Message
)
from telegram.constants import ChatAction
from telegram.error import BadRequest, TimedOut
from telegram.error import BadRequest, TimedOut, NetworkError
from telegram.ext import ContextTypes, ConversationHandler
from yookassa import Payment

Expand Down Expand Up @@ -397,7 +397,7 @@ async def processing_successful_payment(
if query:
try:
await query.answer()
except BadRequest as e:
except NetworkError as e:
sub_hl_logger.error(e)
await query.edit_message_text('Платеж успешно обработан')

Expand Down
29 changes: 17 additions & 12 deletions src/middleware/throttling.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,27 @@ async def check_ttl(update: Update, context: ContextTypes.DEFAULT_TYPE):
last_query_data = last_query.data
if last_query_data == query_data:
logger_ttl.warning(f'Update уже обработан: {update}')
message_thread_id = update.effective_message.message_thread_id
if chat_id in ADMIN_GROUP_ID:
text = ('При необходимости повторной обработки '
'вызови /start в ЛС бота, иначе игнорируй '
'данное сообщение')
message_thread_id = update.message.message_thread_id
try:
await update.effective_message.reply_text(
text=text,
message_thread_id=message_thread_id,
)
except BadRequest as e:
logger_ttl.error(e)
await update.effective_chat.send_message(
text=text,
message_thread_id=message_thread_id,
)
else:
text = ('Подождите 3 секунды и повторите последнее '
'действие, в случае многократного повтора '
'данного сообщения, вызовите /start и '
'повторите запрос заново.')
try:
await update.effective_message.reply_text(
text=text,
message_thread_id=message_thread_id,
)
except BadRequest as e:
logger_ttl.error(e)
await update.effective_chat.send_message(
text=text,
message_thread_id=message_thread_id,
)
raise ApplicationHandlerStop
context.user_data['last_update'] = update

Expand Down
19 changes: 17 additions & 2 deletions src/utilities/utl_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import re
from datetime import time
from pprint import pformat
from typing import List, Sequence, Tuple
from typing import List, Sequence, Tuple, cast

import pytz
from telegram import (
Expand Down Expand Up @@ -199,11 +199,26 @@ async def set_description(bot: ExtBot) -> None:


async def send_log(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
caption = [0]
i = 1
while os.path.exists(f'log/archive/log.txt.{i}'):
caption.append(i)
i += 1
await context.bot.send_document(
chat_id=update.effective_chat.id,
document='log/archive/log.txt'
document='log/archive/log.txt',
caption=caption
)
if context.args:
try:
num = int(context.args[0])
if os.path.exists(f'log/archive/log.txt.{num}'):
await context.bot.send_document(
chat_id=update.effective_chat.id,
document=f'log/archive/log.txt.{num}'
)
except ValueError:
pass
if context.args[0] == 'all':
i = 1
while os.path.exists(f'log/archive/log.txt.{i}'):
Expand Down

0 comments on commit e0b6f63

Please sign in to comment.