Template
Compare commits
7
Commits
db3e02356d
..
markup
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d3ed6e4006 | ||
|
|
a8f39d4630 | ||
|
|
b3a1ea1309 | ||
|
|
c309d4975e | ||
|
|
4ac6be06cf | ||
|
|
a1bd24d3fc | ||
|
|
238d144b6d |
@@ -3,5 +3,6 @@ __pycache__/
|
||||
venv/
|
||||
.venv/
|
||||
logs/
|
||||
data/
|
||||
*.env
|
||||
*.db
|
||||
|
||||
+13
-13
@@ -19,21 +19,21 @@ RUN --mount=type=cache,target=/root/.cache/pip \
|
||||
--mount=type=bind,source=requirements.txt,target=requirements.txt \
|
||||
pip install -r requirements.txt
|
||||
|
||||
# copy i18n files
|
||||
COPY --chown=bot i18n.yaml i18n/i18n.yaml
|
||||
# copy sources
|
||||
COPY --chown=bot --chmod=774 docker-entrypoint.sh /app/
|
||||
COPY --chown=bot migrations /app/migrations
|
||||
COPY --chown=bot mybot /app/mybot
|
||||
COPY --chown=bot i18n.yaml /app/
|
||||
|
||||
# copy default configs
|
||||
WORKDIR /app
|
||||
COPY --chown=bot mybot mybot
|
||||
COPY --chown=bot webapp webapp
|
||||
# prepare environment
|
||||
ENV I18N_PATH=/data/i18n.yaml
|
||||
ENV DB_URL=sqlite:////data/bot.db
|
||||
|
||||
# preapre environment
|
||||
ENV SS_TYPE=memory
|
||||
ENV I18N_PATH=/i18n/i18n.yaml
|
||||
RUN mkdir -p /data
|
||||
RUN chown bot:bot /data
|
||||
VOLUME /data
|
||||
|
||||
# set user
|
||||
USER bot
|
||||
WORKDIR /app
|
||||
|
||||
CMD ["python3", "-m", "mybot"]
|
||||
|
||||
VOLUME i18n/
|
||||
ENTRYPOINT ["./docker-entrypoint.sh"]
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
#!/bin/sh
|
||||
|
||||
if [ ! -f ${I18N_PATH} ]; then
|
||||
cp i18n.yaml ${I18N_PATH}
|
||||
fi
|
||||
|
||||
alembic -c migrations/alembic.ini upgrade head
|
||||
|
||||
if [ $# -eq 0 ]; then
|
||||
if [ -z "${USE_WEBHOOK}" ]; then
|
||||
exec python3 -m mybot
|
||||
else
|
||||
exec gunicorn -b 0.0.0.0:8080 "mybot:main()"
|
||||
fi
|
||||
else
|
||||
exec $1
|
||||
fi
|
||||
+2
-2
@@ -19,8 +19,8 @@ if config.config_file_name is not None:
|
||||
target_metadata = Base.metadata
|
||||
|
||||
# set sqlalchemy.url since it can not be set in alembic.ini file
|
||||
app_config = AppConfig()
|
||||
config.set_main_option("sqlalchemy.url", app_config.DB_URL)
|
||||
app_config = AppConfig.from_env()
|
||||
config.set_main_option("sqlalchemy.url", app_config.database.url)
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
|
||||
+12
-3
@@ -8,6 +8,8 @@ from .states import get_state_storage
|
||||
from .handlers import register_handlers
|
||||
from .middlewares import setup_middlewares
|
||||
from .filters import add_custom_filters
|
||||
from .markup import setup_markup
|
||||
from .webhook import create_app
|
||||
|
||||
|
||||
def create_bot(config: Config, i18n: I18N, engine):
|
||||
@@ -17,12 +19,14 @@ def create_bot(config: Config, i18n: I18N, engine):
|
||||
skip_pending=config.bot.skip_pending,
|
||||
num_threads=config.bot.num_threads,
|
||||
use_class_middlewares=True,
|
||||
state_storage=state_storage)
|
||||
state_storage=state_storage,
|
||||
threaded=False if config.use_webhook else True)
|
||||
register_handlers(bot)
|
||||
setup_middlewares(bot, i18n, engine)
|
||||
markup = setup_markup(bot, i18n)
|
||||
setup_middlewares(bot, i18n, engine, markup)
|
||||
add_custom_filters(bot, config)
|
||||
bot.delete_webhook()
|
||||
if config.use_webhook:
|
||||
bot.delete_webhook()
|
||||
bot.set_webhook(config.webhook.url,
|
||||
drop_pending_updates=config.webhook.drop_pending_updates,
|
||||
max_connections=config.webhook.max_connections)
|
||||
@@ -35,6 +39,11 @@ def main():
|
||||
i18n = I18N(config.i18n)
|
||||
engine = get_engine(config.database)
|
||||
bot = create_bot(config, i18n, engine)
|
||||
|
||||
if config.use_webhook:
|
||||
app = create_app(bot, config)
|
||||
return app
|
||||
|
||||
bot.infinity_polling(
|
||||
timeout=config.bot.timeout,
|
||||
long_polling_timeout=config.bot.polling_timeout,
|
||||
|
||||
+8
-2
@@ -23,13 +23,19 @@ class BotConfig:
|
||||
|
||||
@dataclass
|
||||
class WebhookConfig:
|
||||
url: str
|
||||
domain: str
|
||||
url_path: str
|
||||
max_connections: int
|
||||
drop_pending_updates: bool
|
||||
|
||||
@property
|
||||
def url(self):
|
||||
return f"https://{self.domain}/{self.url_path}"
|
||||
|
||||
@classmethod
|
||||
def from_env(cls):
|
||||
return cls(os.getenv("WEBHOOK_URL"),
|
||||
return cls(os.getenv("WEBHOOK_DOMAIN"),
|
||||
os.getenv("WEBHOOK_URL_PATH"),
|
||||
int(os.getenv("WEBHOOK_MAX_CONNECTIONS", 40)),
|
||||
bool(int(os.getenv("WEBHOOK_DROP_PENDING", True))))
|
||||
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
from telebot import TeleBot
|
||||
from telebot.types import Message
|
||||
from telebot.types import Message, CallbackQuery
|
||||
|
||||
|
||||
def start(message: Message, bot: TeleBot, t, **kwargs):
|
||||
bot.send_message(message.chat.id, t("start"))
|
||||
def start(message: Message, bot: TeleBot, t, m, **kwargs):
|
||||
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):
|
||||
@@ -13,3 +17,5 @@ def help_(message, bot, t, **kwargs):
|
||||
def register_handlers(bot: TeleBot):
|
||||
bot.register_message_handler(start, commands=["start"], 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
|
||||
|
||||
|
||||
def setup_middlewares(bot: TeleBot, i18n: I18N, engine):
|
||||
bot.setup_middleware(ArgumentsMiddleware(i18n))
|
||||
def setup_middlewares(bot: TeleBot, i18n: I18N, engine, markup):
|
||||
bot.setup_middleware(ArgumentsMiddleware(i18n, markup))
|
||||
bot.setup_middleware(DatabaseMiddleware(engine))
|
||||
|
||||
@@ -3,16 +3,24 @@ from telebot.types import Message, CallbackQuery
|
||||
|
||||
|
||||
class ArgumentsMiddleware (BaseMiddleware):
|
||||
def __init__(self, i18n):
|
||||
def __init__(self, i18n, markup):
|
||||
super().__init__()
|
||||
self.i18n = i18n
|
||||
self.markup = markup
|
||||
self.update_types = ["message", "callback_query"]
|
||||
|
||||
def pre_process(self, obj, data: dict):
|
||||
if isinstance(obj, Message):
|
||||
data["t"] = self.i18n.customized_call(message=obj)
|
||||
self.pre_process_message(obj, data)
|
||||
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):
|
||||
pass
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
from flask import Flask, Blueprint, request, abort, g
|
||||
from telebot import TeleBot
|
||||
from telebot.types import Update
|
||||
|
||||
from ..config import Config
|
||||
|
||||
|
||||
bot_bp = Blueprint("bot", __name__)
|
||||
|
||||
|
||||
@bot_bp.route("/", methods=["GET", "POST"])
|
||||
def handle_updates():
|
||||
if request.method == "GET":
|
||||
abort(404)
|
||||
if request.headers.get("content-type") == "application/json":
|
||||
update = Update.de_json(request.get_json())
|
||||
g.bot.process_new_updates([update])
|
||||
return ""
|
||||
else:
|
||||
abort(403)
|
||||
|
||||
|
||||
def inject_g(bot: TeleBot, config: Config):
|
||||
def inner():
|
||||
g.bot = bot
|
||||
g.config = config
|
||||
return inner
|
||||
|
||||
|
||||
def create_app(bot: TeleBot, config: Config):
|
||||
app = Flask(__name__)
|
||||
app.register_blueprint(bot_bp, url_prefix=f"{config.webhook.url_path}")
|
||||
app.before_request(inject_g(bot, config))
|
||||
|
||||
return app
|
||||
@@ -3,5 +3,6 @@ pyyaml
|
||||
sqlalchemy
|
||||
alembic
|
||||
psycopg
|
||||
pymysql
|
||||
flask
|
||||
gunicorn
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
from flask import Flask, g
|
||||
from telebot import TeleBot
|
||||
|
||||
from mybot import create_bot
|
||||
from mybot.config import load_config
|
||||
from mybot.database import get_engine
|
||||
from mybot.i18n import I18N
|
||||
|
||||
from .bot import bp as bot_bp
|
||||
|
||||
|
||||
def inject_bot(bot: TeleBot):
|
||||
def inner():
|
||||
g.bot = bot
|
||||
return inner
|
||||
|
||||
|
||||
def create_app():
|
||||
config = load_config()
|
||||
i18n = I18N(config.i18n)
|
||||
engine = get_engine(config.database)
|
||||
bot = create_bot(config, i18n, engine)
|
||||
|
||||
app = Flask(__name__)
|
||||
app.register_blueprint(bot_bp, url_prefix=f"/{config.bot.token}")
|
||||
app.before_request(inject_bot(bot))
|
||||
return app
|
||||
@@ -1,16 +0,0 @@
|
||||
from flask import Blueprint, request, abort, g, Response
|
||||
from telebot.types import Update
|
||||
|
||||
|
||||
bp = Blueprint("bot", __name__)
|
||||
|
||||
|
||||
@bp.route("/", methods=["POST"])
|
||||
def handle_updates():
|
||||
if request.headers.get("content-type") == "application/json":
|
||||
json_string = request.get_data().decode("utf-8")
|
||||
update = Update.de_json(json_string)
|
||||
g.bot.process_new_updates([update])
|
||||
return Response("", 200)
|
||||
else:
|
||||
abort(403)
|
||||
Reference in New Issue
Block a user