diff --git a/Procfile b/Procfile index fe26464..17df07a 100644 --- a/Procfile +++ b/Procfile @@ -1 +1,2 @@ -web: python run.py +web: flask run -h 0.0.0.0 -p $PORT +worker: python bot.py \ No newline at end of file diff --git a/app.py b/app.py index 7c60b7c..a65251a 100644 --- a/app.py +++ b/app.py @@ -8,6 +8,8 @@ @app.route('/') def hello(): - JerimumBot.send_message(chat_id='-281314498', text='Essa é uma mensagem de teste') + JerimumBot.send_message( + chat_id='-281314498', + text='Essa é uma mensagem de teste' + ) return 'Hello, World!' - diff --git a/bot.py b/bot.py index 24e43eb..60c0e2f 100644 --- a/bot.py +++ b/bot.py @@ -1,10 +1,35 @@ +import logging + +from decouple import config + from core import BotTelegramCore from commands import handlers +logging.basicConfig( + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + level=logging.INFO) + +logger = logging.getLogger(__name__) + + class JerimumBot(BotTelegramCore): """Bot Controller""" def config_handlers(self): for config_handler in handlers: config_handler(self) + + @classmethod + def instance(cls): + if super().instance() is None: + return cls(token=config('BOT_TOKEN', default='??')) + return super().instance() + + @classmethod + def run(cls): + super(cls, cls.instance()).run() + + +if __name__ == '__main__': + JerimumBot.run() diff --git a/core/telegram.py b/core/telegram.py index 9f5a5ab..9eb16fe 100644 --- a/core/telegram.py +++ b/core/telegram.py @@ -1,4 +1,3 @@ -from time import sleep from abc import ABC, abstractmethod import logging @@ -25,19 +24,21 @@ def __init__(self, token): self.token = token self.__updater = Updater(self.token) + self.__running = False self.config_handlers() @classmethod def send_message(cls, chat_id, text, parse_mode=None): instance = cls.instance() assert isinstance(instance, BotTelegramCore) - instance.__updater.bot.send_message(chat_id=chat_id, text=text, parse_mode=parse_mode) + instance.__updater.bot.send_message( + chat_id=chat_id, + text=text, + parse_mode=parse_mode + ) @classmethod def instance(cls): - while cls.__instance is None: - logging.info('Esperando bot ser inicializado...') - sleep(1) return cls.__instance @abstractmethod @@ -54,6 +55,10 @@ def add_error_handler(self, handler): def run(self): """Start the bot as a python script loop""" - self.__updater.start_polling() + if not self.__running: + self.__updater.start_polling() - logging.info('Bot está rodando como um script python!') + logging.info('Bot está rodando como um script python!') + self.__running = True + else: + logging.info('Bot já está rodando!') diff --git a/run.py b/run.py index c875029..d63eb33 100644 --- a/run.py +++ b/run.py @@ -1,5 +1,3 @@ -import logging - from decouple import config from app import app @@ -7,7 +5,6 @@ if __name__ == '__main__': - bot = JerimumBot(token=config('BOT_TOKEN', default='??')) + JerimumBot.run() - bot.run() app.run(host='0.0.0.0', port=config('PORT', default=5000, cast=int))