Skip to content

Commit 41de0ca

Browse files
Tenta obter o livro do dia novamente caso falhe
Talvez corrija GDGAracaju#94
1 parent fca84e6 commit 41de0ca

File tree

1 file changed

+59
-2
lines changed

1 file changed

+59
-2
lines changed

gdgajubot/bot.py

+59-2
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,7 @@ def __getattribute__(self, name):
369369
return super().__getattribute__(name)
370370

371371
@command('/book')
372-
def packtpub_free_learning(self, message, now=None, reply=True):
372+
def packtpub_free_learning(self, message, now=None, reply=True, retry=False):
373373
"""Retorna o livro disponível no free-learning da editora PacktPub."""
374374
if reply:
375375
logging.info("%s: %s", message.from_user.name, "/book")
@@ -390,7 +390,64 @@ def send_message(*args, **kwargs):
390390
now = datetime.datetime.now(tz=AJU_TZ)
391391

392392
# obtém o livro do dia, a resposta formatada e quanto tempo falta para acabar a oferta
393-
book, response, left = self.__get_book(now)
393+
try:
394+
book, response, left = self.__get_book(now)
395+
except:
396+
book, response, left = None, 'error', -1
397+
398+
# livro não obtido: considera pegar novamente o livro em alguns minutos
399+
if book is None:
400+
with self.state_access['lock']:
401+
state = self.get_state('daily_book', message.chat_id)
402+
last_time = state['last_time']
403+
my = state['__memory__']
404+
405+
# inicializa contador de tentativas se necessário
406+
if 'retry-counter' not in my:
407+
my['retry-counter'] = 0
408+
409+
# reinicializa contador se faz algum tempo desde o último envio
410+
elif last_time \
411+
and last_time - now >= datetime.timedelta(hours=1):
412+
my['retry-counter'] = 0
413+
414+
# reinicializa contador se faz algum tempo desde a última tentativa
415+
elif 'retry-when' in my and now < my['retry-when'] \
416+
and my['retry-when'] - now >= datetime.timedelta(hours=1):
417+
my['retry-counter'] = 0
418+
419+
# incrementa o contador desta tentativa
420+
if retry:
421+
my['retry-counter'] += 1
422+
423+
# condições básicas para talvez reagendar
424+
should_retry = not retry or 'retry-when' not in my or now > my['retry-when']
425+
426+
# flags para a mensagem ao usuário
427+
already_scheduled = not should_retry and reply
428+
429+
phrase = None
430+
431+
# agenda obtenção do livro em 5 minutos
432+
if should_retry:
433+
callback = lambda bot, job, msg=message: self.packtpub_free_learning(msg, now, reply, retry=True)
434+
self.updater.job_queue.run_once(callback, when=5*60)
435+
436+
phrase = "⏰ Eu não consegui pegar o livro agora, eu vou tentar de novo em alguns minutos. Aguarde!"
437+
438+
# avisa que já há um agendamento
439+
elif already_scheduled:
440+
phrase = "⏰ Eu não consegui pegar o livro agora, mas em poucos minutos, deve chegar. Aguarde!"
441+
442+
# forma a frase em caso de erro
443+
if response == 'error':
444+
phrase = "⛔ Houston, we have a problem..."
445+
if should_retry or already_scheduled:
446+
phrase += " estou trabalhando em tentar de novo. Aguarde!"
447+
448+
if phrase:
449+
send_message(message, phrase, parse_mode="Markdown")
450+
return
394451

395452
# adiciona à resposta uma frase de que a oferta está acabando
396453
if left >= 0:

0 commit comments

Comments
 (0)