Compare commits

...
16 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
brinza db3e02356d Try to add webhook using flask 2024-07-30 03:56:00 +03:00
brinza e230d6f3dc Add webhook config 2024-07-30 02:59:58 +03:00
brinza f8c09d963e Fix circular imports 2024-07-30 02:45:20 +03:00
brinza cd5845c180 move pool_recycle and pool_pre_ping in config.py 2024-07-30 02:39:47 +03:00
brinza f62e05fd06 Add DatabaseMiddleware 2024-07-30 02:37:36 +03:00
brinza 3ec83e408c rename class in arguments.py 2024-07-30 02:24:00 +03:00
brinza d2c6b972e5 Removed bot module 2024-07-26 03:33:13 +03:00
brinza e09347a03f Add default for SS_TYPE 2024-07-26 03:04:33 +03:00
brinza fbe174e4fb Fix last line 2024-07-26 03:04:18 +03:00
20 changed files with 270 additions and 51 deletions
+1
View File
@@ -3,5 +3,6 @@ __pycache__/
venv/
.venv/
logs/
data/
*.env
*.db
+13 -11
View File
@@ -19,19 +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
VOLUME i18n/
# 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
# 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"]
ENTRYPOINT ["./docker-entrypoint.sh"]
+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
# 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:
+28 -6
View File
@@ -1,18 +1,35 @@
from telebot import TeleBot
from .config import Config, load_config
from .logger import create_logger
from .bot import get_bot
from .i18n import I18N
from .database import get_engine
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):
def create_bot(config: Config, i18n: I18N, engine):
state_storage = get_state_storage(config.states)
bot = get_bot(config.bot, state_storage)
setup_middlewares(bot, i18n)
bot = TeleBot(config.bot.token,
parse_mode=config.bot.parse_mode,
skip_pending=config.bot.skip_pending,
num_threads=config.bot.num_threads,
use_class_middlewares=True,
state_storage=state_storage,
threaded=False if config.use_webhook else True)
register_handlers(bot)
markup = setup_markup(bot, i18n)
setup_middlewares(bot, i18n, engine, markup)
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
@@ -20,8 +37,13 @@ def main():
config = load_config()
# logger = create_logger("mybot", config.log_level)
i18n = I18N(config.i18n)
# engine = get_engine(config.database)
bot = create_bot(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,
-15
View File
@@ -1,15 +0,0 @@
from telebot import TeleBot
from .handlers import register_handlers
from .config import BotConfig
def get_bot(config: BotConfig, state_storage):
bot = TeleBot(config.token,
parse_mode=config.parse_mode,
skip_pending=config.skip_pending,
num_threads=config.num_threads,
use_class_middlewares=True,
state_storage=state_storage)
register_handlers(bot)
return bot
+29 -2
View File
@@ -21,6 +21,25 @@ class BotConfig:
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
class I18NConfig:
path: str
@@ -44,7 +63,7 @@ class StateStorageConfig:
@classmethod
def from_env(cls):
return cls(os.getenv("SS_TYPE"),
return cls(os.getenv("SS_TYPE", "memory"),
os.getenv("SS_REDIS_HOST"),
int(os.getenv("SS_REDIS_PORT", 6379)),
int(os.getenv("SS_REDIS_DB", 0)),
@@ -54,10 +73,14 @@ class StateStorageConfig:
@dataclass
class DatabaseConfig:
url: str
pool_recycle: int
pool_pre_ping: bool
@classmethod
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
@@ -66,7 +89,9 @@ class Config:
i18n: I18NConfig
states: StateStorageConfig
database: DatabaseConfig
webhook: WebhookConfig
use_webhook: bool
log_level: str
owner_id: int
@@ -77,6 +102,8 @@ class Config:
i18n=I18NConfig.from_env(),
states=StateStorageConfig.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"),
owner_id=int(os.getenv("OWNER_ID", 1)),
)
+2 -2
View File
@@ -6,8 +6,8 @@ from ..config import DatabaseConfig
def get_engine(config: DatabaseConfig):
engine = create_engine(config.url,
pool_recycle=3600,
pool_pre_ping=True)
pool_recycle=config.pool_recycle,
pool_pre_ping=config.pool_pre_ping)
return engine
+4 -1
View File
@@ -8,5 +8,8 @@ class User (Base):
__tablename__ = "user"
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
def __init__(self, id: int, username: str):
super().__init__(id=id, username=username)
+9 -3
View File
@@ -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")
+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"))
)
+5 -3
View File
@@ -1,8 +1,10 @@
from telebot import TeleBot
from .arguments import ExtraArguments
from ..i18n import I18N
from .arguments import ArgumentsMiddleware
from .database import DatabaseMiddleware
def setup_middlewares(bot: TeleBot, i18n: I18N):
bot.setup_middleware(ExtraArguments(i18n))
def setup_middlewares(bot: TeleBot, i18n: I18N, engine, markup):
bot.setup_middleware(ArgumentsMiddleware(i18n, markup))
bot.setup_middleware(DatabaseMiddleware(engine))
+12 -4
View File
@@ -2,17 +2,25 @@ from telebot.handler_backends import BaseMiddleware
from telebot.types import Message, CallbackQuery
class ExtraArguments(BaseMiddleware):
def __init__(self, i18n):
class ArgumentsMiddleware (BaseMiddleware):
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
+29
View File
@@ -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()
-1
View File
@@ -15,4 +15,3 @@ def get_state_storage(config: StateStorageConfig):
# states will be defined here
+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
+3 -1
View File
@@ -1,6 +1,8 @@
pytelegrambotapi
environs
pyyaml
sqlalchemy
alembic
psycopg
pymysql
flask
gunicorn