Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .env.example
Original file line number Diff line number Diff line change
@@ -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
13 changes: 13 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -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!'

10 changes: 4 additions & 6 deletions commands/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
3 changes: 2 additions & 1 deletion commands/callback.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
)
2 changes: 1 addition & 1 deletion commands/coach.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
3 changes: 2 additions & 1 deletion commands/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
4 changes: 2 additions & 2 deletions commands/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
6 changes: 3 additions & 3 deletions commands/sticker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
3 changes: 1 addition & 2 deletions commands/weather.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
52 changes: 32 additions & 20 deletions core/telegram.py
Original file line number Diff line number Diff line change
@@ -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(
Expand All @@ -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()
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
24 changes: 4 additions & 20 deletions run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))