diff --git a/.env.example b/.env.example index 7caa989..44f3306 100644 --- a/.env.example +++ b/.env.example @@ -1,4 +1,3 @@ export BOT_TOKEN=meu_token_123 export OPENWEATHERMAP_TOKEN=meu_token_123 -export MODE=cmd -export SERVER_URL=https://jerimumhsbot.herokuapp.com +export PORT=5000 diff --git a/app.py b/app.py new file mode 100644 index 0000000..7c60b7c --- /dev/null +++ b/app.py @@ -0,0 +1,13 @@ +from flask import Flask + +from bot import JerimumBot + + +app = Flask(__name__) + + +@app.route('/') +def hello(): + JerimumBot.send_message(chat_id='-281314498', text='Essa é uma mensagem de teste') + return 'Hello, World!' + diff --git a/commands/base.py b/commands/base.py index 18f31df..7b2608b 100644 --- a/commands/base.py +++ b/commands/base.py @@ -35,15 +35,13 @@ def rules(bot, update): def config_handlers(instance: BotTelegramCore): logging.info('Configurando comandos base do bot...') - dp = instance.updater.dispatcher + instance.add_handler(CommandHandler("regras", rules)) + instance.add_handler(CommandHandler("descricao", description)) - dp.add_handler(CommandHandler("regras", rules)) - dp.add_handler(CommandHandler("descricao", description)) - - dp.add_handler( + instance.add_handler( CommandHandler("start", lambda bot, update: update.message.reply_text(START))) - dp.add_handler( + instance.add_handler( CommandHandler("ajuda", lambda bot, update: update.message.reply_text(HELP))) diff --git a/commands/callback.py b/commands/callback.py index baeae7e..b2819ef 100644 --- a/commands/callback.py +++ b/commands/callback.py @@ -30,6 +30,7 @@ def handle_callback(bot, update): def config_handlers(instance: BotTelegramCore): logging.info('Configurando callback handler do bot...') - instance.updater.dispatcher.add_handler( + + instance.add_handler( CallbackQueryHandler(handle_callback) ) diff --git a/commands/coach.py b/commands/coach.py index a54bde6..2ed674e 100644 --- a/commands/coach.py +++ b/commands/coach.py @@ -57,5 +57,5 @@ def coach(bot, update, args): def config_handlers(instance: BotTelegramCore): logging.info('Configurando comandos de coach quantico do bot...') - instance.updater.dispatcher.add_handler( + instance.add_handler( CommandHandler("coach", coach, pass_args=True)) diff --git a/commands/error.py b/commands/error.py index 62f2743..d10162a 100644 --- a/commands/error.py +++ b/commands/error.py @@ -23,4 +23,5 @@ def error(bot, update, err): def config_handlers(instance: BotTelegramCore): logging.info('Configurando error handler do bot...') - instance.updater.dispatcher.add_error_handler(error) + + instance.add_error_handler(error) diff --git a/commands/message.py b/commands/message.py index f3cfdf1..76da7dd 100644 --- a/commands/message.py +++ b/commands/message.py @@ -63,10 +63,10 @@ def welcome(bot, update): def config_handlers(instance: BotTelegramCore): logging.info('Configurando message handlers do bot...') - instance.updater.dispatcher.add_handler(MessageHandler( + instance.add_handler(MessageHandler( Filters.status_update.new_chat_members, welcome)) - instance.updater.dispatcher.add_handler(MessageHandler( + instance.add_handler(MessageHandler( Filters.status_update.left_chat_member, lambda bot, update: update.message.reply_text( BYE.format( diff --git a/commands/sticker.py b/commands/sticker.py index 2b2466e..485054a 100644 --- a/commands/sticker.py +++ b/commands/sticker.py @@ -15,17 +15,17 @@ def config_handlers(instance: BotTelegramCore): logging.info('Configurando comandos de sticker do bot...') - instance.updater.dispatcher.add_handler( + instance.add_handler( CommandHandler("xinga", lambda bot, update: bot.send_sticker( sticker="CAADAQADCgEAAmOWFQq4zU4TMS08AwI", chat_id=update.message.chat_id))) - instance.updater.dispatcher.add_handler( + instance.add_handler( CommandHandler("aberta", lambda bot, update: bot.send_sticker( sticker="CAADAQADXwADHaeSHfBrZMzXjtwlFgQ", chat_id=update.message.chat_id))) - instance.updater.dispatcher.add_handler( + instance.add_handler( CommandHandler("fechada", lambda bot, update: bot.send_sticker( sticker="CAADAQADYAADHaeSHb7fujge5DRfFgQ", chat_id=update.message.chat_id))) diff --git a/commands/weather.py b/commands/weather.py index 41b4bb1..a24603f 100644 --- a/commands/weather.py +++ b/commands/weather.py @@ -46,5 +46,4 @@ def weather(bot, update, args): def config_handlers(instance: BotTelegramCore): logging.info('Psicografando satelites climaticos...') - instance.updater.dispatcher.\ - add_handler(CommandHandler("clima", weather, pass_args=True)) + instance.add_handler(CommandHandler("clima", weather, pass_args=True)) diff --git a/core/telegram.py b/core/telegram.py index 4667587..9f5a5ab 100644 --- a/core/telegram.py +++ b/core/telegram.py @@ -1,7 +1,8 @@ +from time import sleep from abc import ABC, abstractmethod import logging -from telegram.ext import Updater +from telegram.ext import Updater, Handler logging.basicConfig( @@ -12,36 +13,47 @@ class BotTelegramCore(ABC): - def __init__(self, token, port, server_url): + __instance = None + + def __new__(cls, *args, **kwargs): + if not cls.__instance: + cls.__instance = super().__new__(cls) + return cls.__instance + + def __init__(self, token): logging.info('Inicializando o bot...') self.token = token - self.port = port - self.server_url = server_url - self.updater = Updater(self.token) + self.__updater = Updater(self.token) 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) + + @classmethod + def instance(cls): + while cls.__instance is None: + logging.info('Esperando bot ser inicializado...') + sleep(1) + return cls.__instance + @abstractmethod def config_handlers(self): raise NotImplementedError('Cannot call config_handler from BotCore') - def run_web(self): - """Start the bot as a webhook server""" - - self.updater.start_webhook( - listen="0.0.0.0", - port=self.port, - url_path=self.token - ) - - self.updater.bot.set_webhook(f"{self.server_url}/{self.token}") + def add_handler(self, handler: Handler): + if not isinstance(handler, Handler): + raise ValueError("Handler deve ser do tipo Handler!") + self.__updater.dispatcher.add_handler(handler) - logging.info('Bot está rodando como um webserver!') - self.updater.idle() + def add_error_handler(self, handler): + self.__updater.dispatcher.add_error_handler(handler) - def run_cmd(self): + def run(self): """Start the bot as a python script loop""" - self.updater.start_polling() + self.__updater.start_polling() logging.info('Bot está rodando como um script python!') - self.updater.idle() diff --git a/requirements.txt b/requirements.txt index bbab698..4f0d788 100644 --- a/requirements.txt +++ b/requirements.txt @@ -15,3 +15,4 @@ python-telegram-bot==10.0.2 requests==2.22.0 soupsieve==1.9.4 urllib3==1.25.6 +flask==1.1.1 \ No newline at end of file diff --git a/run.py b/run.py index 2f2d522..c875029 100644 --- a/run.py +++ b/run.py @@ -2,28 +2,12 @@ from decouple import config +from app import app from bot import JerimumBot if __name__ == '__main__': - instance = JerimumBot( - token=config('BOT_TOKEN', default='??'), - port=config('PORT', default=8443, cast=int), - server_url=config('SERVER_URL', default='??') - ) + bot = JerimumBot(token=config('BOT_TOKEN', default='??')) - try: - mode = config('MODE', default='cmd') - if mode == 'cmd': - instance.run_cmd() - elif mode == 'web': - instance.run_web() - else: - raise Exception('O modo passado não foi reconhecido') - - except Exception as e: - logging.error(f'Modo: {config("MODE", default="cmd")}') - logging.error(f'token: {instance.token}') - logging.error(f'Port: {instance.port}') - logging.error(f'heroku app name: {instance.server_url}') - raise e + bot.run() + app.run(host='0.0.0.0', port=config('PORT', default=5000, cast=int))