Compare commits

...
7 Commits
Author SHA1 Message Date
brinza d3ed6e4006 Try to add markup 2024-07-31 00:44:19 +03:00
brinza a8f39d4630 Fix i18n persistence 2024-07-30 18:06:05 +03:00
brinza b3a1ea1309 Refactored and fix docker deploy 2024-07-30 18:02:46 +03:00
brinza c309d4975e Make run deleteWebhook even if polling assumed 2024-07-30 18:01:08 +03:00
brinza 4ac6be06cf Fix Dockerfile 2024-07-30 16:11:06 +03:00
brinza a1bd24d3fc Fix webhook 2024-07-30 16:10:38 +03:00
brinza 238d144b6d Add pymysql in requirements.txt 2024-07-30 13:58:13 +03:00
17 changed files with 192 additions and 71 deletions
+1
View File
@@ -3,5 +3,6 @@ __pycache__/
venv/ venv/
.venv/ .venv/
logs/ logs/
data/
*.env *.env
*.db *.db
+13 -13
View File
@@ -19,21 +19,21 @@ RUN --mount=type=cache,target=/root/.cache/pip \
--mount=type=bind,source=requirements.txt,target=requirements.txt \ --mount=type=bind,source=requirements.txt,target=requirements.txt \
pip install -r requirements.txt pip install -r requirements.txt
# copy i18n files # copy sources
COPY --chown=bot i18n.yaml i18n/i18n.yaml 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 # prepare environment
WORKDIR /app ENV I18N_PATH=/data/i18n.yaml
COPY --chown=bot mybot mybot ENV DB_URL=sqlite:////data/bot.db
COPY --chown=bot webapp webapp
# preapre environment RUN mkdir -p /data
ENV SS_TYPE=memory RUN chown bot:bot /data
ENV I18N_PATH=/i18n/i18n.yaml VOLUME /data
# set user
USER bot USER bot
WORKDIR /app
CMD ["python3", "-m", "mybot"] ENTRYPOINT ["./docker-entrypoint.sh"]
VOLUME i18n/
+17
View File
@@ -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
View File
@@ -19,8 +19,8 @@ if config.config_file_name is not None:
target_metadata = Base.metadata target_metadata = Base.metadata
# set sqlalchemy.url since it can not be set in alembic.ini file # set sqlalchemy.url since it can not be set in alembic.ini file
app_config = AppConfig() app_config = AppConfig.from_env()
config.set_main_option("sqlalchemy.url", app_config.DB_URL) config.set_main_option("sqlalchemy.url", app_config.database.url)
def run_migrations_offline() -> None: def run_migrations_offline() -> None:
+12 -3
View File
@@ -8,6 +8,8 @@ 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
def create_bot(config: Config, i18n: I18N, engine): 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, skip_pending=config.bot.skip_pending,
num_threads=config.bot.num_threads, num_threads=config.bot.num_threads,
use_class_middlewares=True, use_class_middlewares=True,
state_storage=state_storage) state_storage=state_storage,
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()
if config.use_webhook: if config.use_webhook:
bot.delete_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)
@@ -35,6 +39,11 @@ def main():
i18n = I18N(config.i18n) i18n = I18N(config.i18n)
engine = get_engine(config.database) engine = get_engine(config.database)
bot = create_bot(config, i18n, engine) bot = create_bot(config, i18n, engine)
if config.use_webhook:
app = create_app(bot, config)
return app
bot.infinity_polling( bot.infinity_polling(
timeout=config.bot.timeout, timeout=config.bot.timeout,
long_polling_timeout=config.bot.polling_timeout, long_polling_timeout=config.bot.polling_timeout,
+8 -2
View File
@@ -23,13 +23,19 @@ class BotConfig:
@dataclass @dataclass
class WebhookConfig: class WebhookConfig:
url: str domain: str
url_path: str
max_connections: int max_connections: int
drop_pending_updates: bool drop_pending_updates: bool
@property
def url(self):
return f"https://{self.domain}/{self.url_path}"
@classmethod @classmethod
def from_env(cls): 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)), int(os.getenv("WEBHOOK_MAX_CONNECTIONS", 40)),
bool(int(os.getenv("WEBHOOK_DROP_PENDING", True)))) bool(int(os.getenv("WEBHOOK_DROP_PENDING", True))))
+9 -3
View File
@@ -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")
+11
View File
@@ -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
+55
View File
@@ -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
+15
View File
@@ -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"))
)
+2 -2
View File
@@ -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))
+11 -3
View File
@@ -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
+35
View File
@@ -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
+1
View File
@@ -3,5 +3,6 @@ pyyaml
sqlalchemy sqlalchemy
alembic alembic
psycopg psycopg
pymysql
flask flask
gunicorn gunicorn
-27
View File
@@ -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
-16
View File
@@ -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)