Template
Compare commits
1
Commits
6e8238243a
..
markup
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d3ed6e4006 |
+4
-4
@@ -8,6 +8,7 @@ from .states import get_state_storage
|
|||||||
from .handlers import register_handlers
|
from .handlers import register_handlers
|
||||||
from .middlewares import setup_middlewares
|
from .middlewares import setup_middlewares
|
||||||
from .filters import add_custom_filters
|
from .filters import add_custom_filters
|
||||||
|
from .markup import setup_markup
|
||||||
from .webhook import create_app
|
from .webhook import create_app
|
||||||
|
|
||||||
|
|
||||||
@@ -21,15 +22,14 @@ def create_bot(config: Config, i18n: I18N, engine):
|
|||||||
state_storage=state_storage,
|
state_storage=state_storage,
|
||||||
threaded=False if config.use_webhook else True)
|
threaded=False if config.use_webhook else True)
|
||||||
register_handlers(bot)
|
register_handlers(bot)
|
||||||
setup_middlewares(bot, i18n, engine)
|
markup = setup_markup(bot, i18n)
|
||||||
|
setup_middlewares(bot, i18n, engine, markup)
|
||||||
add_custom_filters(bot, config)
|
add_custom_filters(bot, config)
|
||||||
bot.delete_webhook()
|
bot.delete_webhook()
|
||||||
if config.use_webhook:
|
if config.use_webhook:
|
||||||
bot.set_webhook(config.webhook.url,
|
bot.set_webhook(config.webhook.url,
|
||||||
drop_pending_updates=config.webhook.drop_pending_updates,
|
drop_pending_updates=config.webhook.drop_pending_updates,
|
||||||
max_connections=config.webhook.max_connections,
|
max_connections=config.webhook.max_connections)
|
||||||
secret_token=config.webhook.secret_token,
|
|
||||||
certificate=config.webhook.cert_path)
|
|
||||||
return bot
|
return bot
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+4
-20
@@ -1,7 +1,5 @@
|
|||||||
import os
|
import os
|
||||||
import secrets
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -25,35 +23,21 @@ class BotConfig:
|
|||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class WebhookConfig:
|
class WebhookConfig:
|
||||||
domain: Optional[str]
|
domain: str
|
||||||
url_path: str
|
url_path: str
|
||||||
max_connections: int
|
max_connections: int
|
||||||
drop_pending_updates: bool
|
drop_pending_updates: bool
|
||||||
|
|
||||||
# secret token
|
|
||||||
use_secret_token: bool
|
|
||||||
secret_token: Optional[str]
|
|
||||||
|
|
||||||
# self-signed certificate
|
|
||||||
cert_path: Optional[str]
|
|
||||||
|
|
||||||
def __post_init__(self):
|
|
||||||
if self.use_secret_token and not self.secret_token:
|
|
||||||
self.secret_token = secrets.token_hex()
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def url(self):
|
def url(self):
|
||||||
return f"https://{self.domain}{self.url_path}"
|
return f"https://{self.domain}/{self.url_path}"
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_env(cls):
|
def from_env(cls):
|
||||||
return cls(os.getenv("WEBHOOK_DOMAIN"),
|
return cls(os.getenv("WEBHOOK_DOMAIN"),
|
||||||
os.getenv("WEBHOOK_URL_PATH", "/"),
|
os.getenv("WEBHOOK_URL_PATH"),
|
||||||
int(os.getenv("WEBHOOK_MAX_CONNECTIONS", 40)),
|
int(os.getenv("WEBHOOK_MAX_CONNECTIONS", 40)),
|
||||||
bool(int(os.getenv("WEBHOOK_DROP_PENDING", True))),
|
bool(int(os.getenv("WEBHOOK_DROP_PENDING", True))))
|
||||||
bool(int(os.getenv("WEBHOOK_USE_SECRET_TOKEN", True))),
|
|
||||||
os.getenv("WEBHOOK_SECRET_TOKEN"),
|
|
||||||
os.getenv("WEBHOOK_CERT_PATH"))
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
from telebot import TeleBot
|
from telebot import TeleBot
|
||||||
from telebot.types import Message
|
from telebot.types import Message, CallbackQuery
|
||||||
|
|
||||||
|
|
||||||
def start(message: Message, bot: TeleBot, t, **kwargs):
|
def start(message: Message, bot: TeleBot, t, m, **kwargs):
|
||||||
bot.send_message(message.chat.id, t("start"))
|
bot.send_message(message.chat.id, t("start"), reply_markup=m("start"))
|
||||||
|
|
||||||
|
|
||||||
|
def start_call(call: CallbackQuery, bot: TeleBot, t, m, **kwargs):
|
||||||
|
bot.send_message(call.message.chat.id, t("start"), reply_markup=m("start"))
|
||||||
|
|
||||||
|
|
||||||
def help_(message, bot, t, **kwargs):
|
def help_(message, bot, t, **kwargs):
|
||||||
@@ -13,3 +17,5 @@ def help_(message, bot, t, **kwargs):
|
|||||||
def register_handlers(bot: TeleBot):
|
def register_handlers(bot: TeleBot):
|
||||||
bot.register_message_handler(start, commands=["start"], pass_bot=True)
|
bot.register_message_handler(start, commands=["start"], pass_bot=True)
|
||||||
bot.register_message_handler(help_, commands=["help"], pass_bot=True)
|
bot.register_message_handler(help_, commands=["help"], pass_bot=True)
|
||||||
|
|
||||||
|
bot.register_callback_query_handler(start_call, lambda call: call.data == "start")
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
from telebot import TeleBot
|
||||||
|
|
||||||
|
from ..i18n import I18N
|
||||||
|
from .base import MarkupManager
|
||||||
|
from .simple import SimpleMarkup
|
||||||
|
|
||||||
|
|
||||||
|
def setup_markup(bot: TeleBot, i18n: I18N):
|
||||||
|
markup_mg = MarkupManager(bot, i18n)
|
||||||
|
markup_mg.register_prototype(SimpleMarkup)
|
||||||
|
return markup_mg
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import abc
|
||||||
|
from typing import Optional, Type
|
||||||
|
|
||||||
|
from telebot import TeleBot
|
||||||
|
from telebot.types import CallbackQuery, InlineKeyboardMarkup
|
||||||
|
|
||||||
|
from ..i18n import I18N
|
||||||
|
|
||||||
|
|
||||||
|
class Markup (metaclass=abc.ABCMeta):
|
||||||
|
tag: str
|
||||||
|
|
||||||
|
def __init__(self, bot: TeleBot, i18n: I18N):
|
||||||
|
self.bot = bot
|
||||||
|
self.t = i18n
|
||||||
|
|
||||||
|
def __call__(self, *args, **kwargs):
|
||||||
|
return self.build(*args, **kwargs)
|
||||||
|
|
||||||
|
def check(self, call: CallbackQuery) -> bool:
|
||||||
|
return call.data == self.tag
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def build(self, *args, **kwargs) -> Optional[InlineKeyboardMarkup]:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class DummyMarkup (Markup):
|
||||||
|
tag = "__dummy"
|
||||||
|
|
||||||
|
def check(self, call: CallbackQuery) -> bool:
|
||||||
|
return True
|
||||||
|
|
||||||
|
def build(self, *args, **kwargs) -> Optional[InlineKeyboardMarkup]:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class MarkupManager:
|
||||||
|
def __init__(self, bot: TeleBot, i18n: I18N):
|
||||||
|
self.bot = bot
|
||||||
|
self.i18n = i18n
|
||||||
|
self._prototypes: list[Markup] = []
|
||||||
|
self._dummy = DummyMarkup(self.bot, self.i18n)
|
||||||
|
|
||||||
|
def register_prototype(self, markup_proto_class: Type[Markup]):
|
||||||
|
self._prototypes.append(markup_proto_class(self.bot, self.i18n))
|
||||||
|
|
||||||
|
def __call__(self, tag: str, *args, **kwargs):
|
||||||
|
return self.get(tag).build(*args, **kwargs)
|
||||||
|
|
||||||
|
def get(self, tag: str) -> Optional[Markup]:
|
||||||
|
for mp in self._prototypes:
|
||||||
|
if mp.tag == tag:
|
||||||
|
return mp
|
||||||
|
return None
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
|
||||||
|
|
||||||
|
from .base import Markup
|
||||||
|
|
||||||
|
|
||||||
|
class SimpleMarkup (Markup):
|
||||||
|
tag = "start"
|
||||||
|
|
||||||
|
def build(self, *args, **kwargs) -> Optional[InlineKeyboardMarkup]:
|
||||||
|
return (InlineKeyboardMarkup()
|
||||||
|
.add(InlineKeyboardButton("start", callback_data="start"))
|
||||||
|
.add(InlineKeyboardButton("help", callback_data="help"))
|
||||||
|
)
|
||||||
@@ -5,6 +5,6 @@ from .arguments import ArgumentsMiddleware
|
|||||||
from .database import DatabaseMiddleware
|
from .database import DatabaseMiddleware
|
||||||
|
|
||||||
|
|
||||||
def setup_middlewares(bot: TeleBot, i18n: I18N, engine):
|
def setup_middlewares(bot: TeleBot, i18n: I18N, engine, markup):
|
||||||
bot.setup_middleware(ArgumentsMiddleware(i18n))
|
bot.setup_middleware(ArgumentsMiddleware(i18n, markup))
|
||||||
bot.setup_middleware(DatabaseMiddleware(engine))
|
bot.setup_middleware(DatabaseMiddleware(engine))
|
||||||
|
|||||||
@@ -3,16 +3,24 @@ from telebot.types import Message, CallbackQuery
|
|||||||
|
|
||||||
|
|
||||||
class ArgumentsMiddleware (BaseMiddleware):
|
class ArgumentsMiddleware (BaseMiddleware):
|
||||||
def __init__(self, i18n):
|
def __init__(self, i18n, markup):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.i18n = i18n
|
self.i18n = i18n
|
||||||
|
self.markup = markup
|
||||||
self.update_types = ["message", "callback_query"]
|
self.update_types = ["message", "callback_query"]
|
||||||
|
|
||||||
def pre_process(self, obj, data: dict):
|
def pre_process(self, obj, data: dict):
|
||||||
if isinstance(obj, Message):
|
if isinstance(obj, Message):
|
||||||
data["t"] = self.i18n.customized_call(message=obj)
|
self.pre_process_message(obj, data)
|
||||||
elif isinstance(obj, CallbackQuery):
|
elif isinstance(obj, CallbackQuery):
|
||||||
data["t"] = self.i18n.customized_call(callback=obj)
|
self.pre_process_callback(obj, data)
|
||||||
|
data["m"] = self.markup
|
||||||
|
|
||||||
|
def pre_process_message(self, message: Message, data: dict):
|
||||||
|
data["t"] = self.i18n.customized_call(message=message)
|
||||||
|
|
||||||
|
def pre_process_callback(self, call: CallbackQuery, data: dict):
|
||||||
|
data["t"] = self.i18n.customized_call(callback=call)
|
||||||
|
|
||||||
def post_process(self, message, data: dict, exception: BaseException):
|
def post_process(self, message, data: dict, exception: BaseException):
|
||||||
pass
|
pass
|
||||||
|
|||||||
+12
-12
@@ -1,35 +1,35 @@
|
|||||||
from flask import Flask, request, abort, g
|
from flask import Flask, Blueprint, request, abort, g
|
||||||
from telebot import TeleBot
|
from telebot import TeleBot
|
||||||
from telebot.types import Update
|
from telebot.types import Update
|
||||||
|
|
||||||
from ..config import Config
|
from ..config import Config
|
||||||
|
|
||||||
|
|
||||||
|
bot_bp = Blueprint("bot", __name__)
|
||||||
|
|
||||||
|
|
||||||
|
@bot_bp.route("/", methods=["GET", "POST"])
|
||||||
def handle_updates():
|
def handle_updates():
|
||||||
if request.method == "GET":
|
if request.method == "GET":
|
||||||
abort(404) # safer to 404
|
|
||||||
if g.config.webhook.use_secret_token:
|
|
||||||
if request.headers.get("X-Telegram-Bot-Api-Secret-Token") != g.config.webhook.secret_token:
|
|
||||||
abort(404)
|
abort(404)
|
||||||
if request.headers.get("content-type") == "application/json":
|
if request.headers.get("content-type") == "application/json":
|
||||||
update = Update.de_json(request.get_json())
|
update = Update.de_json(request.get_json())
|
||||||
g.bot.process_new_updates([update])
|
g.bot.process_new_updates([update])
|
||||||
return ""
|
return ""
|
||||||
else:
|
else:
|
||||||
abort(404) # safer to 404
|
abort(403)
|
||||||
|
|
||||||
|
|
||||||
def inject_g(**kwargs):
|
def inject_g(bot: TeleBot, config: Config):
|
||||||
def inner():
|
def inner():
|
||||||
for k, v in kwargs.items():
|
g.bot = bot
|
||||||
setattr(g, k, v)
|
g.config = config
|
||||||
return inner
|
return inner
|
||||||
|
|
||||||
|
|
||||||
def create_app(bot: TeleBot, config: Config):
|
def create_app(bot: TeleBot, config: Config):
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
app.add_url_rule(config.webhook.url_path,
|
app.register_blueprint(bot_bp, url_prefix=f"{config.webhook.url_path}")
|
||||||
view_func=handle_updates,
|
app.before_request(inject_g(bot, config))
|
||||||
methods=["GET", "POST"])
|
|
||||||
app.before_request(inject_g(bot=bot, config=config))
|
|
||||||
return app
|
return app
|
||||||
|
|||||||
Reference in New Issue
Block a user