Template
Compare commits
13
Commits
d2c6b972e5
...
markup
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d3ed6e4006 | ||
|
|
a8f39d4630 | ||
|
|
b3a1ea1309 | ||
|
|
c309d4975e | ||
|
|
4ac6be06cf | ||
|
|
a1bd24d3fc | ||
|
|
238d144b6d | ||
|
|
db3e02356d | ||
|
|
e230d6f3dc | ||
|
|
f8c09d963e | ||
|
|
cd5845c180 | ||
|
|
f62e05fd06 | ||
|
|
3ec83e408c |
@@ -3,5 +3,6 @@ __pycache__/
|
|||||||
venv/
|
venv/
|
||||||
.venv/
|
.venv/
|
||||||
logs/
|
logs/
|
||||||
|
data/
|
||||||
*.env
|
*.env
|
||||||
*.db
|
*.db
|
||||||
|
|||||||
+13
-11
@@ -19,19 +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/
|
||||||
VOLUME i18n/
|
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
|
||||||
|
|
||||||
# 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"]
|
||||||
|
|||||||
@@ -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
|
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:
|
||||||
|
|||||||
+16
-2
@@ -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,10 +19,17 @@ 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)
|
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:
|
||||||
|
bot.set_webhook(config.webhook.url,
|
||||||
|
drop_pending_updates=config.webhook.drop_pending_updates,
|
||||||
|
max_connections=config.webhook.max_connections)
|
||||||
return bot
|
return bot
|
||||||
|
|
||||||
|
|
||||||
@@ -30,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,
|
||||||
|
|||||||
+28
-1
@@ -21,6 +21,25 @@ class BotConfig:
|
|||||||
os.getenv("BOT_PARSE_MODE", "html"))
|
os.getenv("BOT_PARSE_MODE", "html"))
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class WebhookConfig:
|
||||||
|
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_DOMAIN"),
|
||||||
|
os.getenv("WEBHOOK_URL_PATH"),
|
||||||
|
int(os.getenv("WEBHOOK_MAX_CONNECTIONS", 40)),
|
||||||
|
bool(int(os.getenv("WEBHOOK_DROP_PENDING", True))))
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class I18NConfig:
|
class I18NConfig:
|
||||||
path: str
|
path: str
|
||||||
@@ -54,10 +73,14 @@ class StateStorageConfig:
|
|||||||
@dataclass
|
@dataclass
|
||||||
class DatabaseConfig:
|
class DatabaseConfig:
|
||||||
url: str
|
url: str
|
||||||
|
pool_recycle: int
|
||||||
|
pool_pre_ping: bool
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_env(cls):
|
def from_env(cls):
|
||||||
return cls(os.getenv("DATABASE_URL", "sqlite:///bot.db"))
|
return cls(os.getenv("DB_URL", "sqlite:///bot.db"),
|
||||||
|
int(os.getenv("DB_POOL_RECYCLE", 3600)),
|
||||||
|
bool(int(os.getenv("DB_POOL_PRE_PING", True))))
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -66,7 +89,9 @@ class Config:
|
|||||||
i18n: I18NConfig
|
i18n: I18NConfig
|
||||||
states: StateStorageConfig
|
states: StateStorageConfig
|
||||||
database: DatabaseConfig
|
database: DatabaseConfig
|
||||||
|
webhook: WebhookConfig
|
||||||
|
|
||||||
|
use_webhook: bool
|
||||||
log_level: str
|
log_level: str
|
||||||
owner_id: int
|
owner_id: int
|
||||||
|
|
||||||
@@ -77,6 +102,8 @@ class Config:
|
|||||||
i18n=I18NConfig.from_env(),
|
i18n=I18NConfig.from_env(),
|
||||||
states=StateStorageConfig.from_env(),
|
states=StateStorageConfig.from_env(),
|
||||||
database=DatabaseConfig.from_env(),
|
database=DatabaseConfig.from_env(),
|
||||||
|
webhook=WebhookConfig.from_env(),
|
||||||
|
use_webhook=bool(int(os.getenv("USE_WEBHOOK", False))),
|
||||||
log_level=os.getenv("LOG_LEVEL", "INFO"),
|
log_level=os.getenv("LOG_LEVEL", "INFO"),
|
||||||
owner_id=int(os.getenv("OWNER_ID", 1)),
|
owner_id=int(os.getenv("OWNER_ID", 1)),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ from ..config import DatabaseConfig
|
|||||||
|
|
||||||
def get_engine(config: DatabaseConfig):
|
def get_engine(config: DatabaseConfig):
|
||||||
engine = create_engine(config.url,
|
engine = create_engine(config.url,
|
||||||
pool_recycle=3600,
|
pool_recycle=config.pool_recycle,
|
||||||
pool_pre_ping=True)
|
pool_pre_ping=config.pool_pre_ping)
|
||||||
return engine
|
return engine
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -8,5 +8,8 @@ class User (Base):
|
|||||||
__tablename__ = "user"
|
__tablename__ = "user"
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(BIGINT, primary_key=True, unique=True, autoincrement=False)
|
id: Mapped[int] = mapped_column(BIGINT, primary_key=True, unique=True, autoincrement=False)
|
||||||
username: Mapped[int] = mapped_column(String(32), unique=True, nullable=True)
|
username: Mapped[str] = mapped_column(String(32), unique=True, nullable=True)
|
||||||
# additional fields go here
|
# additional fields go here
|
||||||
|
|
||||||
|
def __init__(self, id: int, username: str):
|
||||||
|
super().__init__(id=id, username=username)
|
||||||
|
|||||||
@@ -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"))
|
||||||
|
)
|
||||||
@@ -1,8 +1,10 @@
|
|||||||
from telebot import TeleBot
|
from telebot import TeleBot
|
||||||
|
|
||||||
from .arguments import ExtraArguments
|
|
||||||
from ..i18n import I18N
|
from ..i18n import I18N
|
||||||
|
from .arguments import ArgumentsMiddleware
|
||||||
|
from .database import DatabaseMiddleware
|
||||||
|
|
||||||
|
|
||||||
def setup_middlewares(bot: TeleBot, i18n: I18N):
|
def setup_middlewares(bot: TeleBot, i18n: I18N, engine, markup):
|
||||||
bot.setup_middleware(ExtraArguments(i18n))
|
bot.setup_middleware(ArgumentsMiddleware(i18n, markup))
|
||||||
|
bot.setup_middleware(DatabaseMiddleware(engine))
|
||||||
|
|||||||
@@ -2,17 +2,25 @@ from telebot.handler_backends import BaseMiddleware
|
|||||||
from telebot.types import Message, CallbackQuery
|
from telebot.types import Message, CallbackQuery
|
||||||
|
|
||||||
|
|
||||||
class ExtraArguments(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
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
from telebot.handler_backends import BaseMiddleware
|
||||||
|
from telebot.types import Message, CallbackQuery
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from ..database.models import User
|
||||||
|
|
||||||
|
|
||||||
|
class DatabaseMiddleware (BaseMiddleware):
|
||||||
|
def __init__(self, engine):
|
||||||
|
super().__init__()
|
||||||
|
self.engine = engine
|
||||||
|
self.update_types = ["message", "callback_query"]
|
||||||
|
|
||||||
|
def pre_process(self, obj: [Message, CallbackQuery], data: dict):
|
||||||
|
session = Session(self.engine)
|
||||||
|
user = session.get(User, obj.from_user.id)
|
||||||
|
if user is None:
|
||||||
|
user = User(id=obj.from_user.id, username=obj.from_user.username)
|
||||||
|
session.add(user)
|
||||||
|
session.commit()
|
||||||
|
data["db"] = session
|
||||||
|
data["user"] = user
|
||||||
|
|
||||||
|
def post_process(self, message, data: dict, exception: BaseException):
|
||||||
|
if "db" in data:
|
||||||
|
session: Session = data["db"]
|
||||||
|
session.rollback()
|
||||||
|
session.close()
|
||||||
@@ -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
-1
@@ -1,6 +1,8 @@
|
|||||||
pytelegrambotapi
|
pytelegrambotapi
|
||||||
environs
|
|
||||||
pyyaml
|
pyyaml
|
||||||
sqlalchemy
|
sqlalchemy
|
||||||
alembic
|
alembic
|
||||||
psycopg
|
psycopg
|
||||||
|
pymysql
|
||||||
|
flask
|
||||||
|
gunicorn
|
||||||
|
|||||||
Reference in New Issue
Block a user