mirror of
				https://github.com/civsocit/olgram.git
				synced 2025-10-30 23:53:24 +00:00 
			
		
		
		
	Compare commits
	
		
			No commits in common. "1dd4d4d7fd114d3312ed5167ff4a268390b25676" and "a262d4e488e7f3270df91583c3e33fed5e8af567" have entirely different histories.
		
	
	
		
			1dd4d4d7fd
			...
			a262d4e488
		
	
		
|  | @ -1,7 +1,6 @@ | ||||||
| О проекте | О проекте | ||||||
| =================================== | =================================== | ||||||
| 
 | 
 | ||||||
| 
 |  | ||||||
| Зачем нужен Olgram | Зачем нужен Olgram | ||||||
| ------------ | ------------ | ||||||
| 
 | 
 | ||||||
|  |  | ||||||
|  | @ -4,23 +4,21 @@ | ||||||
| Донаты | Донаты | ||||||
| ---------------- | ---------------- | ||||||
| 
 | 
 | ||||||
| На аренду сервера для этого проекта | На рекламу проекта, аренду сервера и пиццу | ||||||
| 
 | 
 | ||||||
| Bitcoin: | Bitcoin: | ||||||
|     ``bc1qlq7cm5chc8flr3fy8ewk967aknq3dwmxtwn9hl`` |     ``bc1qlq7cm5chc8flr3fy8ewk967aknq3dwmxtwn9hl`` | ||||||
| 
 | 
 | ||||||
| Litecoin: | Monero: | ||||||
|     ``LTC1QXAJSVZ0LW44AA5NYTUCH8CP2G8X7A4CDASE4Y7`` |     ``886AQ8tCVcQKp21xsuSLkfDdTAdtCFH1jR58Tw9MsaxFXoZ7YRHXx1cQcUfUnDX6hySzPsQEVt6RWPn3sXH9QUmwCr3oVqB`` | ||||||
| 
 | 
 | ||||||
| Как убрать "Этот бот создан с помощью ..." | Dash: | ||||||
| ---------------- |     ``XqxetfWzr5n4Ms1TxMbdEEeHGe8CaMdmb6`` | ||||||
| Напишите нам на `@civsocit_feedback_bot <https://t.me/civsocit_feedback_bot>`_. |  | ||||||
| 
 | 
 | ||||||
| 
 | 
 | ||||||
| История изменений | История изменений | ||||||
| ---------------- | ---------------- | ||||||
| 
 | 
 | ||||||
| - `2024-01-12` Мультиязычность (стартовое сообщение и автоответчик) |  | ||||||
| - `2022-08-01` Защита от флуда | - `2022-08-01` Защита от флуда | ||||||
| - `2022-07-23` Автоответчик не пишет сообщение лишний раз | - `2022-07-23` Автоответчик не пишет сообщение лишний раз | ||||||
| - `2022-07-04` Поддержка двух ботов в одном чате | - `2022-07-04` Поддержка двух ботов в одном чате | ||||||
|  |  | ||||||
|  | @ -3,7 +3,7 @@ | ||||||
| # -- Project information | # -- Project information | ||||||
| 
 | 
 | ||||||
| project = 'Olgram' | project = 'Olgram' | ||||||
| copyright = '2024, Civsocit' | copyright = '2022, Civsocit' | ||||||
| author = 'civsocit' | author = 'civsocit' | ||||||
| 
 | 
 | ||||||
| release = '0.1' | release = '0.1' | ||||||
|  |  | ||||||
|  | @ -68,13 +68,6 @@ BotFather - это официальный бот Telegram, создающий д | ||||||
| 
 | 
 | ||||||
| Теперь просто отправьте новый текст приветствия. | Теперь просто отправьте новый текст приветствия. | ||||||
| 
 | 
 | ||||||
| .. note:: |  | ||||||
| 
 |  | ||||||
|    Чтобы настроить особый текст приветствия для, например, русскоязычных пользователей (т.е. тех пользователей, у |  | ||||||
|    которых в настройках Telegram выставлена русская локализация), нажмите кнопку "Руссикй 🇷🇺" и только потом отправьте |  | ||||||
|    текст приветствия. Чтобы отредактировать текст приветствия для всех остальных языков, нажмите "[все языки]". |  | ||||||
| 
 |  | ||||||
| 
 |  | ||||||
| Как привязать бота к групповому чату | Как привязать бота к групповому чату | ||||||
| ------------------------------------ | ------------------------------------ | ||||||
| 
 | 
 | ||||||
|  |  | ||||||
|  | @ -455,7 +455,7 @@ msgid "" | ||||||
| "отключено.\n" | "отключено.\n" | ||||||
| "\n" | "\n" | ||||||
| "    Текущий текст:\n" | "    Текущий текст:\n" | ||||||
| "    <pre>" | "    <pre>\n" | ||||||
| "    {1}\n" | "    {1}\n" | ||||||
| "    </pre>\n" | "    </pre>\n" | ||||||
| "    Отправьте сообщение, чтобы изменить текст.\n" | "    Отправьте сообщение, чтобы изменить текст.\n" | ||||||
|  |  | ||||||
|  | @ -407,7 +407,9 @@ msgid "" | ||||||
| "    команду /start\n" | "    команду /start\n" | ||||||
| "\n" | "\n" | ||||||
| "    Текущий текст:\n" | "    Текущий текст:\n" | ||||||
| "    <pre>{1}</pre>\n" | "    <pre>\n" | ||||||
|  | "    {1}\n" | ||||||
|  | "    </pre>\n" | ||||||
| "    Отправьте сообщение, чтобы изменить текст.\n" | "    Отправьте сообщение, чтобы изменить текст.\n" | ||||||
| "    " | "    " | ||||||
| msgstr "" | msgstr "" | ||||||
|  | @ -417,7 +419,9 @@ msgstr "" | ||||||
| "    команду /start\n" | "    команду /start\n" | ||||||
| "\n" | "\n" | ||||||
| "    Поточний текст:\n" | "    Поточний текст:\n" | ||||||
| "    <pre>{1}</pre>\n" | "    <pre>\n" | ||||||
|  | "    {1}\n" | ||||||
|  | "    </pre>\n" | ||||||
| "    Надішліть повідомлення, щоб змінити текст.\n" | "    Надішліть повідомлення, щоб змінити текст.\n" | ||||||
| "    \n" | "    \n" | ||||||
| "    " | "    " | ||||||
|  | @ -458,7 +462,9 @@ msgid "" | ||||||
| "отключено.\n" | "отключено.\n" | ||||||
| "\n" | "\n" | ||||||
| "    Текущий текст:\n" | "    Текущий текст:\n" | ||||||
| "    <pre>{1}</pre>\n" | "    <pre>\n" | ||||||
|  | "    {1}\n" | ||||||
|  | "    </pre>\n" | ||||||
| "    Отправьте сообщение, чтобы изменить текст.\n" | "    Отправьте сообщение, чтобы изменить текст.\n" | ||||||
| "    " | "    " | ||||||
| msgstr "" | msgstr "" | ||||||
|  |  | ||||||
|  | @ -306,7 +306,9 @@ msgid "" | ||||||
| "    команду /start\n" | "    команду /start\n" | ||||||
| "\n" | "\n" | ||||||
| "    Текущий текст:\n" | "    Текущий текст:\n" | ||||||
| "    <pre>{1}</pre>\n" | "    <pre>\n" | ||||||
|  | "    {1}\n" | ||||||
|  | "    </pre>\n" | ||||||
| "    Отправьте сообщение, чтобы изменить текст.\n" | "    Отправьте сообщение, чтобы изменить текст.\n" | ||||||
| "    " | "    " | ||||||
| msgstr "" | msgstr "" | ||||||
|  | @ -315,7 +317,9 @@ msgstr "" | ||||||
| "    /start\n" | "    /start\n" | ||||||
| "\n" | "\n" | ||||||
| "    目前的文本。\n" | "    目前的文本。\n" | ||||||
| "    <pre>{1}</pre>\n" | "    <pre>\n" | ||||||
|  | "    {1}\n" | ||||||
|  | "    </pre>\n" | ||||||
| "    发送消息,改变文本。\n" | "    发送消息,改变文本。\n" | ||||||
| "    " | "    " | ||||||
| 
 | 
 | ||||||
|  | @ -355,7 +359,9 @@ msgid "" | ||||||
| "отключено.\n" | "отключено.\n" | ||||||
| "\n" | "\n" | ||||||
| "    Текущий текст:\n" | "    Текущий текст:\n" | ||||||
| "    <pre>{1}</pre>\n" | "    <pre>\n" | ||||||
|  | "    {1}\n" | ||||||
|  | "    </pre>\n" | ||||||
| "    Отправьте сообщение, чтобы изменить текст.\n" | "    Отправьте сообщение, чтобы изменить текст.\n" | ||||||
| "    " | "    " | ||||||
| msgstr "" | msgstr "" | ||||||
|  | @ -364,7 +370,9 @@ msgstr "" | ||||||
| "默认情况下,它是禁用的。\n" | "默认情况下,它是禁用的。\n" | ||||||
| "\n" | "\n" | ||||||
| "    目前的文本。\n" | "    目前的文本。\n" | ||||||
| "    <pre>{1}</pre>。\n" | "    <pre>\n" | ||||||
|  | "    {1}\n" | ||||||
|  | "    </pre>。\n" | ||||||
| "    发送消息,改变文本。\n" | "    发送消息,改变文本。\n" | ||||||
| "    " | "    " | ||||||
| 
 | 
 | ||||||
|  |  | ||||||
|  | @ -4,7 +4,7 @@ | ||||||
| from aiogram import types | from aiogram import types | ||||||
| from aiogram.utils.exceptions import TelegramAPIError, Unauthorized | from aiogram.utils.exceptions import TelegramAPIError, Unauthorized | ||||||
| from aiogram import Bot as AioBot | from aiogram import Bot as AioBot | ||||||
| from olgram.models.models import Bot, BotStartMessage, BotSecondMessage | from olgram.models.models import Bot | ||||||
| from server.server import unregister_token | from server.server import unregister_token | ||||||
| from locales.locale import _ | from locales.locale import _ | ||||||
| 
 | 
 | ||||||
|  | @ -26,39 +26,27 @@ async def delete_bot(bot: Bot, call: types.CallbackQuery): | ||||||
|         pass |         pass | ||||||
| 
 | 
 | ||||||
| 
 | 
 | ||||||
| async def reset_bot_text(bot: Bot, call: types.CallbackQuery, state): | async def reset_bot_text(bot: Bot, call: types.CallbackQuery): | ||||||
|     """ |     """ | ||||||
|     Пользователь решил сбросить текст бота к default |     Пользователь решил сбросить текст бота к default | ||||||
|     :param bot: |     :param bot: | ||||||
|     :param call: |     :param call: | ||||||
|     :return: |     :return: | ||||||
|     """ |     """ | ||||||
|     async with state.proxy() as proxy: |     bot.start_text = bot._meta.fields_map['start_text'].default | ||||||
|         lang = proxy.get("lang", "none") |     await bot.save() | ||||||
|     if lang == "none": |  | ||||||
|         await BotStartMessage.filter(bot=bot).delete() |  | ||||||
|         bot.start_text = bot._meta.fields_map['start_text'].default |  | ||||||
|         await bot.save(update_fields=["start_text"]) |  | ||||||
|     else: |  | ||||||
|         await BotStartMessage.filter(bot=bot, locale=lang).delete() |  | ||||||
|     await call.answer(_("Текст сброшен")) |     await call.answer(_("Текст сброшен")) | ||||||
| 
 | 
 | ||||||
| 
 | 
 | ||||||
| async def reset_bot_second_text(bot: Bot, call: types.CallbackQuery, state): | async def reset_bot_second_text(bot: Bot, call: types.CallbackQuery): | ||||||
|     """ |     """ | ||||||
|     Пользователь решил сбросить second text бота |     Пользователь решил сбросить second text бота | ||||||
|     :param bot: |     :param bot: | ||||||
|     :param call: |     :param call: | ||||||
|     :return: |     :return: | ||||||
|     """ |     """ | ||||||
|     async with state.proxy() as proxy: |     bot.second_text = bot._meta.fields_map['second_text'].default | ||||||
|         lang = proxy.get("lang", "none") |     await bot.save() | ||||||
|     if lang == "none": |  | ||||||
|         await BotSecondMessage.filter(bot=bot).delete() |  | ||||||
|         bot.second_text = bot._meta.fields_map['second_text'].default |  | ||||||
|         await bot.save(update_fields=["second_text"]) |  | ||||||
|     else: |  | ||||||
|         await BotSecondMessage.filter(bot=bot, locale=lang).delete() |  | ||||||
|     await call.answer(_("Текст сброшен")) |     await call.answer(_("Текст сброшен")) | ||||||
| 
 | 
 | ||||||
| 
 | 
 | ||||||
|  |  | ||||||
|  | @ -37,4 +37,4 @@ async def info(message: types.Message, state: FSMContext): | ||||||
|                          _("Входящих сообщений у всех ботов: {0}\n").format(income_messages) + |                          _("Входящих сообщений у всех ботов: {0}\n").format(income_messages) + | ||||||
|                          _("Исходящих сообщений у всех ботов: {0}\n").format(outgoing_messages) + |                          _("Исходящих сообщений у всех ботов: {0}\n").format(outgoing_messages) + | ||||||
|                          _("Промо-кодов выдано: {0}\n").format(promo_count) + |                          _("Промо-кодов выдано: {0}\n").format(promo_count) + | ||||||
|                          _("Рекламную плашку выключили: {0}\n").format(olgram_text_disabled)) |                          _("Рекламную плашку выключили: {0}\n".format(olgram_text_disabled))) | ||||||
|  |  | ||||||
|  | @ -1,7 +1,7 @@ | ||||||
| from olgram.router import dp | from olgram.router import dp | ||||||
| 
 | 
 | ||||||
| from aiogram import types, Bot as AioBot | from aiogram import types, Bot as AioBot | ||||||
| from olgram.models.models import Bot, User, DefaultAnswer, BotStartMessage, BotSecondMessage | from olgram.models.models import Bot, User, DefaultAnswer | ||||||
| from aiogram.dispatcher import FSMContext | from aiogram.dispatcher import FSMContext | ||||||
| from aiogram.utils.callback_data import CallbackData | from aiogram.utils.callback_data import CallbackData | ||||||
| from textwrap import dedent | from textwrap import dedent | ||||||
|  | @ -202,26 +202,9 @@ async def send_bot_settings_menu(bot: Bot, call: types.CallbackQuery): | ||||||
|     await edit_or_create(call, text, reply_markup=keyboard, parse_mode="HTML") |     await edit_or_create(call, text, reply_markup=keyboard, parse_mode="HTML") | ||||||
| 
 | 
 | ||||||
| 
 | 
 | ||||||
| languages = { | async def send_bot_text_menu(bot: Bot, call: ty.Optional[types.CallbackQuery] = None, chat_id: ty.Optional[int] = None): | ||||||
|     "en": "English 🇺🇸", |  | ||||||
|     "ru": "Русский 🇷🇺", |  | ||||||
|     "uk": "Український 🇺🇦", |  | ||||||
|     "tr": "Türkçe 🇹🇷", |  | ||||||
|     "hy": "հայերեն 🇦🇲", |  | ||||||
|     "ka": "ქართული ენა 🇬🇪" |  | ||||||
| } |  | ||||||
| 
 |  | ||||||
| 
 |  | ||||||
| async def send_bot_text_menu(bot: Bot, call: ty.Optional[types.CallbackQuery] = None, chat_id: ty.Optional[int] = None, |  | ||||||
|                              state=None): |  | ||||||
|     if call: |     if call: | ||||||
|         await call.answer() |         await call.answer() | ||||||
| 
 |  | ||||||
|     async with state.proxy() as proxy: |  | ||||||
|         lang = proxy.get("lang", "none") |  | ||||||
| 
 |  | ||||||
|     prepared_languages = {ln.locale: ln.text for ln in await bot.start_texts} |  | ||||||
| 
 |  | ||||||
|     keyboard = types.InlineKeyboardMarkup(row_width=2) |     keyboard = types.InlineKeyboardMarkup(row_width=2) | ||||||
|     keyboard.insert( |     keyboard.insert( | ||||||
|         types.InlineKeyboardButton(text=_("<< Завершить редактирование"), |         types.InlineKeyboardButton(text=_("<< Завершить редактирование"), | ||||||
|  | @ -232,40 +215,23 @@ async def send_bot_text_menu(bot: Bot, call: ty.Optional[types.CallbackQuery] = | ||||||
|                                    callback_data=menu_callback.new(level=3, bot_id=bot.id, operation="next_text", |                                    callback_data=menu_callback.new(level=3, bot_id=bot.id, operation="next_text", | ||||||
|                                                                    chat=empty)) |                                                                    chat=empty)) | ||||||
|     ) |     ) | ||||||
|     keyboard.row( |     keyboard.insert( | ||||||
|         types.InlineKeyboardButton(text=_("Сбросить текст"), |         types.InlineKeyboardButton(text=_("Сбросить текст"), | ||||||
|                                    callback_data=menu_callback.new(level=3, bot_id=bot.id, operation="reset_text", |                                    callback_data=menu_callback.new(level=3, bot_id=bot.id, operation="reset_text", | ||||||
|                                                                    chat=empty)) |                                                                    chat=empty)) | ||||||
|     ) |     ) | ||||||
|     keyboard.add( |  | ||||||
|         types.InlineKeyboardButton(text=("🟢 " if lang == "none" else "") + _("[все языки]"), |  | ||||||
|                                    callback_data=menu_callback.new(level=3, bot_id=bot.id, |  | ||||||
|                                                                    operation="slang_none", chat=empty)) |  | ||||||
|     ) |  | ||||||
|     for code, name in languages.items(): |  | ||||||
|         prefix = "" |  | ||||||
|         if code == lang: |  | ||||||
|             prefix = "🟢 " |  | ||||||
|         elif code in prepared_languages: |  | ||||||
|             prefix = "✔️ " |  | ||||||
|         keyboard.insert( |  | ||||||
|             types.InlineKeyboardButton(text=prefix + name, |  | ||||||
|                                        callback_data=menu_callback.new(level=3, bot_id=bot.id, |  | ||||||
|                                                                        operation=f"slang_{code}", |  | ||||||
|                                                                        chat=empty)) |  | ||||||
|         ) |  | ||||||
| 
 | 
 | ||||||
|     text = dedent(_(""" |     text = dedent(_(""" | ||||||
|     Сейчас вы редактируете текст, который отправляется после того, как пользователь отправит вашему боту @{0} |     Сейчас вы редактируете текст, который отправляется после того, как пользователь отправит вашему боту @{0} | ||||||
|     команду /start |     команду /start | ||||||
| 
 | 
 | ||||||
|     Текущий текст{2}: |     Текущий текст: | ||||||
|     <pre>{1}</pre> |     <pre> | ||||||
|  |     {1} | ||||||
|  |     </pre> | ||||||
|     Отправьте сообщение, чтобы изменить текст. |     Отправьте сообщение, чтобы изменить текст. | ||||||
|     """)) |     """)) | ||||||
|     text = text.format(bot.name, |     text = text.format(bot.name, bot.start_text) | ||||||
|                        prepared_languages.get(lang, bot.start_text), |  | ||||||
|                        _(" (для языка {0})").format(languages[lang]) if lang != "none" else "") |  | ||||||
|     if call: |     if call: | ||||||
|         await edit_or_create(call, text, keyboard, parse_mode="HTML") |         await edit_or_create(call, text, keyboard, parse_mode="HTML") | ||||||
|     else: |     else: | ||||||
|  | @ -298,15 +264,9 @@ async def send_bot_statistic_menu(bot: Bot, call: ty.Optional[types.CallbackQuer | ||||||
| 
 | 
 | ||||||
| 
 | 
 | ||||||
| async def send_bot_second_text_menu(bot: Bot, call: ty.Optional[types.CallbackQuery] = None, | async def send_bot_second_text_menu(bot: Bot, call: ty.Optional[types.CallbackQuery] = None, | ||||||
|                                     chat_id: ty.Optional[int] = None, state=None): |                                     chat_id: ty.Optional[int] = None): | ||||||
|     if call: |     if call: | ||||||
|         await call.answer() |         await call.answer() | ||||||
| 
 |  | ||||||
|     async with state.proxy() as proxy: |  | ||||||
|         lang = proxy.get("lang", "none") |  | ||||||
| 
 |  | ||||||
|     prepared_languages = {ln.locale: ln.text for ln in await bot.second_texts} |  | ||||||
| 
 |  | ||||||
|     keyboard = types.InlineKeyboardMarkup(row_width=2) |     keyboard = types.InlineKeyboardMarkup(row_width=2) | ||||||
|     keyboard.insert( |     keyboard.insert( | ||||||
|         types.InlineKeyboardButton(text=_("<< Завершить редактирование"), |         types.InlineKeyboardButton(text=_("<< Завершить редактирование"), | ||||||
|  | @ -327,35 +287,18 @@ async def send_bot_second_text_menu(bot: Bot, call: ty.Optional[types.CallbackQu | ||||||
|                                    callback_data=menu_callback.new(level=3, bot_id=bot.id, |                                    callback_data=menu_callback.new(level=3, bot_id=bot.id, | ||||||
|                                                                    operation="reset_second_text", chat=empty)) |                                                                    operation="reset_second_text", chat=empty)) | ||||||
|     ) |     ) | ||||||
|     keyboard.add( |  | ||||||
|         types.InlineKeyboardButton(text=("🟢 " if lang == "none" else "") + _("[все языки]"), |  | ||||||
|                                    callback_data=menu_callback.new(level=3, bot_id=bot.id, |  | ||||||
|                                                                    operation="alang_none", chat=empty)) |  | ||||||
|     ) |  | ||||||
|     for code, name in languages.items(): |  | ||||||
|         prefix = "" |  | ||||||
|         if code == lang: |  | ||||||
|             prefix = "🟢 " |  | ||||||
|         elif code in prepared_languages: |  | ||||||
|             prefix = "✔️ " |  | ||||||
|         keyboard.insert( |  | ||||||
|             types.InlineKeyboardButton(text=prefix + name, |  | ||||||
|                                        callback_data=menu_callback.new(level=3, bot_id=bot.id, |  | ||||||
|                                                                        operation=f"alang_{code}", |  | ||||||
|                                                                        chat=empty)) |  | ||||||
|         ) |  | ||||||
| 
 | 
 | ||||||
|     text = dedent(_(""" |     text = dedent(_(""" | ||||||
|     Сейчас вы редактируете текст автоответчика. Это сообщение отправляется в ответ на все входящие сообщения @{0} \ |     Сейчас вы редактируете текст автоответчика. Это сообщение отправляется в ответ на все входящие сообщения @{0} \ | ||||||
| автоматически. По умолчанию оно отключено. | автоматически. По умолчанию оно отключено. | ||||||
| 
 | 
 | ||||||
|     Текущий текст{2}: |     Текущий текст: | ||||||
|     <pre>{1}</pre> |     <pre> | ||||||
|  |     {1} | ||||||
|  |     </pre> | ||||||
|     Отправьте сообщение, чтобы изменить текст. |     Отправьте сообщение, чтобы изменить текст. | ||||||
|     """)) |     """)) | ||||||
|     text = text.format(bot.name, |     text = text.format(bot.name, bot.second_text if bot.second_text else _("(отключено)")) | ||||||
|                        prepared_languages.get(lang, bot.second_text or _("отключено")), |  | ||||||
|                        _(" (для языка {0})").format(languages[lang]) if lang != "none" else "") |  | ||||||
|     if call: |     if call: | ||||||
|         await edit_or_create(call, text, keyboard, parse_mode="HTML") |         await edit_or_create(call, text, keyboard, parse_mode="HTML") | ||||||
|     else: |     else: | ||||||
|  | @ -403,43 +346,20 @@ async def send_bot_templates_menu(bot: Bot, call: ty.Optional[types.CallbackQuer | ||||||
| async def start_text_received(message: types.Message, state: FSMContext): | async def start_text_received(message: types.Message, state: FSMContext): | ||||||
|     async with state.proxy() as proxy: |     async with state.proxy() as proxy: | ||||||
|         bot_id = proxy.get("bot_id") |         bot_id = proxy.get("bot_id") | ||||||
|         lang = proxy.get("lang", "none") |  | ||||||
| 
 |  | ||||||
|     bot = await Bot.get_or_none(pk=bot_id) |     bot = await Bot.get_or_none(pk=bot_id) | ||||||
|     if lang == "none": |     bot.start_text = message.html_text | ||||||
|         bot.start_text = message.html_text |     await bot.save() | ||||||
|         await bot.save(update_fields=["start_text"]) |     await send_bot_text_menu(bot, chat_id=message.chat.id) | ||||||
|     else: |  | ||||||
|         obj, created = await BotStartMessage.get_or_create(bot=bot, |  | ||||||
|                                                            locale=lang, |  | ||||||
|                                                            defaults={"text": message.html_text}) |  | ||||||
|         if not created: |  | ||||||
|             obj.text = message.html_text |  | ||||||
|             await obj.save(update_fields=["text"]) |  | ||||||
|     await send_bot_text_menu(bot, chat_id=message.chat.id, state=state) |  | ||||||
| 
 | 
 | ||||||
| 
 | 
 | ||||||
| @dp.message_handler(state="wait_second_text", content_types="text", regexp="^[^/].+")  # Not command | @dp.message_handler(state="wait_second_text", content_types="text", regexp="^[^/].+")  # Not command | ||||||
| async def second_text_received(message: types.Message, state: FSMContext): | async def second_text_received(message: types.Message, state: FSMContext): | ||||||
|     async with state.proxy() as proxy: |     async with state.proxy() as proxy: | ||||||
|         bot_id = proxy.get("bot_id") |         bot_id = proxy.get("bot_id") | ||||||
|         lang = proxy.get("lang", "none") |  | ||||||
| 
 |  | ||||||
|     bot = await Bot.get_or_none(pk=bot_id) |     bot = await Bot.get_or_none(pk=bot_id) | ||||||
|     if lang == "none": |     bot.second_text = message.html_text | ||||||
|         bot.second_text = message.html_text |     await bot.save() | ||||||
|         await bot.save(update_fields=["second_text"]) |     await send_bot_second_text_menu(bot, chat_id=message.chat.id) | ||||||
|     else: |  | ||||||
|         obj, created = await BotSecondMessage.get_or_create(bot=bot, |  | ||||||
|                                                             locale=lang, |  | ||||||
|                                                             defaults={"text": message.html_text}) |  | ||||||
|         if not created: |  | ||||||
|             obj.text = message.html_text |  | ||||||
|             await obj.save(update_fields=["text"]) |  | ||||||
|         if not bot.second_text: |  | ||||||
|             bot.second_text = message.html_text |  | ||||||
|             await bot.save(update_fields=["second_text"]) |  | ||||||
|     await send_bot_second_text_menu(bot, chat_id=message.chat.id, state=state) |  | ||||||
| 
 | 
 | ||||||
| 
 | 
 | ||||||
| @dp.message_handler(state="wait_template", content_types="text", regexp="^[^/](.+)?")  # Not command | @dp.message_handler(state="wait_template", content_types="text", regexp="^[^/](.+)?")  # Not command | ||||||
|  | @ -507,7 +427,7 @@ async def callback(call: types.CallbackQuery, callback_data: dict, state: FSMCon | ||||||
|             await state.set_state("wait_start_text") |             await state.set_state("wait_start_text") | ||||||
|             async with state.proxy() as proxy: |             async with state.proxy() as proxy: | ||||||
|                 proxy["bot_id"] = bot.id |                 proxy["bot_id"] = bot.id | ||||||
|             return await send_bot_text_menu(bot, call, state=state) |             return await send_bot_text_menu(bot, call) | ||||||
| 
 | 
 | ||||||
|     if level == "3": |     if level == "3": | ||||||
|         if operation == "delete_yes": |         if operation == "delete_yes": | ||||||
|  | @ -527,28 +447,16 @@ async def callback(call: types.CallbackQuery, callback_data: dict, state: FSMCon | ||||||
|             await bot_actions.olgram_text(bot, call) |             await bot_actions.olgram_text(bot, call) | ||||||
|             return await send_bot_settings_menu(bot, call) |             return await send_bot_settings_menu(bot, call) | ||||||
|         if operation == "reset_text": |         if operation == "reset_text": | ||||||
|             await bot_actions.reset_bot_text(bot, call, state) |             await bot_actions.reset_bot_text(bot, call) | ||||||
|             return await send_bot_text_menu(bot, call, state=state) |             return await send_bot_text_menu(bot, call) | ||||||
|         if operation.startswith("slang_"): |  | ||||||
|             async with state.proxy() as proxy: |  | ||||||
|                 lang = operation.replace("slang_", "") |  | ||||||
|                 if lang == "none" or lang in languages: |  | ||||||
|                     proxy["lang"] = lang |  | ||||||
|             return await send_bot_text_menu(bot, call, state=state) |  | ||||||
|         if operation == "next_text": |         if operation == "next_text": | ||||||
|             await state.set_state("wait_second_text") |             await state.set_state("wait_second_text") | ||||||
|             async with state.proxy() as proxy: |             async with state.proxy() as proxy: | ||||||
|                 proxy["bot_id"] = bot.id |                 proxy["bot_id"] = bot.id | ||||||
|             return await send_bot_second_text_menu(bot, call, state=state) |             return await send_bot_second_text_menu(bot, call) | ||||||
|         if operation.startswith("alang_"): |  | ||||||
|             async with state.proxy() as proxy: |  | ||||||
|                 lang = operation.replace("alang_", "") |  | ||||||
|                 if lang == "none" or lang in languages: |  | ||||||
|                     proxy["lang"] = lang |  | ||||||
|             return await send_bot_second_text_menu(bot, call, state=state) |  | ||||||
|         if operation == "reset_second_text": |         if operation == "reset_second_text": | ||||||
|             await bot_actions.reset_bot_second_text(bot, call, state) |             await bot_actions.reset_bot_second_text(bot, call) | ||||||
|             return await send_bot_second_text_menu(bot, call, state=state) |             return await send_bot_second_text_menu(bot, call) | ||||||
|         if operation == "templates": |         if operation == "templates": | ||||||
|             await state.set_state("wait_template") |             await state.set_state("wait_template") | ||||||
|             async with state.proxy() as proxy: |             async with state.proxy() as proxy: | ||||||
|  |  | ||||||
|  | @ -1,9 +0,0 @@ | ||||||
| -- upgrade -- |  | ||||||
| CREATE TABLE IF NOT EXISTS "bot_start_message" ( |  | ||||||
|     "id" SERIAL NOT NULL PRIMARY KEY, |  | ||||||
|     "locale" VARCHAR(5) NOT NULL, |  | ||||||
|     "bot_id" INT NOT NULL REFERENCES "bot" ("id") ON DELETE CASCADE, |  | ||||||
|     CONSTRAINT "uid_bot_start_m_bot_id_871cd1" UNIQUE ("bot_id", "locale") |  | ||||||
| ); |  | ||||||
| -- downgrade -- |  | ||||||
| DROP TABLE IF EXISTS "bot_start_message"; |  | ||||||
|  | @ -1,4 +0,0 @@ | ||||||
| -- upgrade -- |  | ||||||
| ALTER TABLE "bot_start_message" ADD "text" TEXT NOT NULL; |  | ||||||
| -- downgrade -- |  | ||||||
| ALTER TABLE "bot_start_message" DROP COLUMN "text"; |  | ||||||
|  | @ -1,10 +0,0 @@ | ||||||
| -- upgrade -- |  | ||||||
| CREATE TABLE IF NOT EXISTS "bot_second_message" ( |  | ||||||
|     "id" SERIAL NOT NULL PRIMARY KEY, |  | ||||||
|     "locale" VARCHAR(5) NOT NULL, |  | ||||||
|     "text" TEXT NOT NULL, |  | ||||||
|     "bot_id" INT NOT NULL REFERENCES "bot" ("id") ON DELETE CASCADE, |  | ||||||
|     CONSTRAINT "uid_bot_second__bot_id_432892" UNIQUE ("bot_id", "locale") |  | ||||||
| ); |  | ||||||
| -- downgrade -- |  | ||||||
| DROP TABLE IF EXISTS "bot_second_message"; |  | ||||||
|  | @ -70,28 +70,6 @@ class Bot(Model): | ||||||
|         table = 'bot' |         table = 'bot' | ||||||
| 
 | 
 | ||||||
| 
 | 
 | ||||||
| class BotStartMessage(Model): |  | ||||||
|     id = fields.IntField(pk=True) |  | ||||||
|     bot = fields.ForeignKeyField("models.Bot", related_name="start_texts", on_delete=fields.CASCADE) |  | ||||||
|     locale = fields.CharField(max_length=5) |  | ||||||
|     text = fields.TextField() |  | ||||||
| 
 |  | ||||||
|     class Meta: |  | ||||||
|         unique_together = ("bot", "locale") |  | ||||||
|         table = 'bot_start_message' |  | ||||||
| 
 |  | ||||||
| 
 |  | ||||||
| class BotSecondMessage(Model): |  | ||||||
|     id = fields.IntField(pk=True) |  | ||||||
|     bot = fields.ForeignKeyField("models.Bot", related_name="second_texts", on_delete=fields.CASCADE) |  | ||||||
|     locale = fields.CharField(max_length=5) |  | ||||||
|     text = fields.TextField() |  | ||||||
| 
 |  | ||||||
|     class Meta: |  | ||||||
|         unique_together = ("bot", "locale") |  | ||||||
|         table = 'bot_second_message' |  | ||||||
| 
 |  | ||||||
| 
 |  | ||||||
| class User(Model): | class User(Model): | ||||||
|     id = fields.IntField(pk=True) |     id = fields.IntField(pk=True) | ||||||
|     telegram_id = fields.BigIntField(index=True, unique=True) |     telegram_id = fields.BigIntField(index=True, unique=True) | ||||||
|  |  | ||||||
|  | @ -41,7 +41,7 @@ class OlgramSettings(AbstractSettings): | ||||||
| 
 | 
 | ||||||
|     @classmethod |     @classmethod | ||||||
|     def version(cls): |     def version(cls): | ||||||
|         return "0.6.1" |         return "0.5.0" | ||||||
| 
 | 
 | ||||||
|     @classmethod |     @classmethod | ||||||
|     @lru_cache |     @lru_cache | ||||||
|  |  | ||||||
|  | @ -11,7 +11,7 @@ from tortoise.expressions import F | ||||||
| import logging | import logging | ||||||
| import typing as ty | import typing as ty | ||||||
| from olgram.settings import ServerSettings | from olgram.settings import ServerSettings | ||||||
| from olgram.models.models import Bot, GroupChat, BannedUser, BotStartMessage, BotSecondMessage | from olgram.models.models import Bot, GroupChat, BannedUser | ||||||
| from locales.locale import _, translators | from locales.locale import _, translators | ||||||
| from server.inlines import inline_handler | from server.inlines import inline_handler | ||||||
| 
 | 
 | ||||||
|  | @ -78,29 +78,26 @@ async def send_user_message(message: types.Message, super_chat_id: int, bot): | ||||||
|         if message.from_user.username: |         if message.from_user.username: | ||||||
|             user_info += " | @" + message.from_user.username |             user_info += " | @" + message.from_user.username | ||||||
|         user_info += f" | #ID{message.from_user.id}" |         user_info += f" | #ID{message.from_user.id}" | ||||||
|         if message.from_user.locale: |  | ||||||
|             user_info += f" | lang: {message.from_user.locale}" |  | ||||||
|         if message.forward_sender_name: |  | ||||||
|             user_info += f" | fwd: {message.forward_sender_name}" |  | ||||||
| 
 | 
 | ||||||
|         # Добавлять информацию в конец текста |         # Добавлять информацию в конец текста | ||||||
|         if message.content_type == types.ContentType.TEXT \ |         if message.content_type == types.ContentType.TEXT and len(message.text) + len(user_info) < 4093:  # noqa:E721 | ||||||
|                 and len(message.text) + len(user_info) < 4093:  # noqa:E721 |  | ||||||
|             new_message = await message.bot.send_message(super_chat_id, message.text + "\n\n" + user_info) |             new_message = await message.bot.send_message(super_chat_id, message.text + "\n\n" + user_info) | ||||||
|         else:  # Не добавлять информацию в конец текста, информация отдельным сообщением |         else:  # Не добавлять информацию в конец текста, информация отдельным сообщением | ||||||
|             new_message = await message.bot.send_message(super_chat_id, text=user_info) |             new_message = await message.bot.send_message(super_chat_id, text=user_info) | ||||||
|             new_message_2 = await message.copy_to(super_chat_id, reply_to_message_id=new_message.message_id) |             new_message_2 = await message.copy_to(super_chat_id, reply_to_message_id=new_message.message_id) | ||||||
|             await _redis.set(_message_unique_id(bot.pk, new_message_2.message_id), message.chat.id, |             await _redis.set(_message_unique_id(bot.pk, new_message_2.message_id), message.chat.id, | ||||||
|                              pexpire=ServerSettings.redis_timeout_ms()) |                              pexpire=ServerSettings.redis_timeout_ms()) | ||||||
|  |         await _redis.set(_message_unique_id(bot.pk, new_message.message_id), message.chat.id, | ||||||
|  |                          pexpire=ServerSettings.redis_timeout_ms()) | ||||||
|  |         return new_message | ||||||
|     else: |     else: | ||||||
|         try: |         try: | ||||||
|             new_message = await message.forward(super_chat_id) |             new_message = await message.forward(super_chat_id) | ||||||
|         except exceptions.MessageCantBeForwarded: |         except exceptions.MessageCantBeForwarded: | ||||||
|             new_message = await message.copy_to(super_chat_id) |             new_message = await message.copy_to(super_chat_id) | ||||||
| 
 |         await _redis.set(_message_unique_id(bot.pk, new_message.message_id), message.chat.id, | ||||||
|     await _redis.set(_message_unique_id(bot.pk, new_message.message_id), message.chat.id, |                          pexpire=ServerSettings.redis_timeout_ms()) | ||||||
|                      pexpire=ServerSettings.redis_timeout_ms()) |         return new_message | ||||||
|     return new_message |  | ||||||
| 
 | 
 | ||||||
| 
 | 
 | ||||||
| async def send_to_superchat(is_super_group: bool, message: types.Message, super_chat_id: int, bot): | async def send_to_superchat(is_super_group: bool, message: types.Message, super_chat_id: int, bot): | ||||||
|  | @ -161,9 +158,7 @@ async def handle_user_message(message: types.Message, super_chat_id: int, bot): | ||||||
|         send_auto = not await _redis.get(_last_message_uid(bot.pk, message.chat.id)) |         send_auto = not await _redis.get(_last_message_uid(bot.pk, message.chat.id)) | ||||||
|         await _redis.setex(_last_message_uid(bot.pk, message.chat.id), 60 * 60 * 3, 1) |         await _redis.setex(_last_message_uid(bot.pk, message.chat.id), 60 * 60 * 3, 1) | ||||||
|         if send_auto: |         if send_auto: | ||||||
|             text_obj = await BotSecondMessage.get_or_none(bot=bot, locale=str(message.from_user.locale)) |             return SendMessage(chat_id=message.chat.id, text=bot.second_text, parse_mode="HTML") | ||||||
|             return SendMessage(chat_id=message.chat.id, text=text_obj.text if text_obj else bot.second_text, |  | ||||||
|                                parse_mode="HTML") |  | ||||||
| 
 | 
 | ||||||
| 
 | 
 | ||||||
| async def handle_operator_message(message: types.Message, super_chat_id: int, bot): | async def handle_operator_message(message: types.Message, super_chat_id: int, bot): | ||||||
|  | @ -223,8 +218,7 @@ async def message_handler(message: types.Message, *args, **kwargs): | ||||||
| 
 | 
 | ||||||
|     if message.text and message.text == "/start": |     if message.text and message.text == "/start": | ||||||
|         # На команду start нужно ответить, не пересылая сообщение никуда |         # На команду start нужно ответить, не пересылая сообщение никуда | ||||||
|         text_obj = await BotStartMessage.get_or_none(bot=bot, locale=str(message.from_user.locale)) |         text = bot.start_text | ||||||
|         text = text_obj.text if text_obj else bot.start_text |  | ||||||
|         if bot.enable_olgram_text: |         if bot.enable_olgram_text: | ||||||
|             text += _(ServerSettings.append_text()) |             text += _(ServerSettings.append_text()) | ||||||
|         return SendMessage(chat_id=message.chat.id, text=text, parse_mode="HTML") |         return SendMessage(chat_id=message.chat.id, text=text, parse_mode="HTML") | ||||||
|  |  | ||||||
		Loading…
	
		Reference in New Issue
	
	Block a user