Removed other source code
This commit is contained in:
parent
4d3b9513f0
commit
347c666a78
30 changed files with 0 additions and 2084 deletions
|
@ -1,25 +0,0 @@
|
|||
import logging
|
||||
|
||||
from aiogram import Dispatcher
|
||||
|
||||
from bozenka.instances.telegram.handlers.chat_admin import register_admin_cmd
|
||||
from bozenka.instances.telegram.handlers.queries import register_queries
|
||||
from bozenka.instances.telegram.handlers.dev import register_dev_cmd
|
||||
from bozenka.instances.telegram.handlers.main import register_main_cmd
|
||||
from bozenka.instances.telegram.handlers.chat_user import register_user_cmd
|
||||
from bozenka.instances.telegram.utils.middleware import register_middlewares
|
||||
|
||||
|
||||
def register_handlers(dp: Dispatcher) -> None:
|
||||
"""
|
||||
Registers all handlers
|
||||
:param dp:
|
||||
:return:
|
||||
"""
|
||||
logging.log(msg="Starting registering all handlers", level=logging.INFO)
|
||||
register_dev_cmd(dp)
|
||||
register_user_cmd(dp)
|
||||
register_admin_cmd(dp)
|
||||
register_main_cmd(dp)
|
||||
register_queries(dp)
|
||||
register_middlewares(dp)
|
|
@ -1,72 +0,0 @@
|
|||
|
||||
|
||||
import logging
|
||||
|
||||
from aiogram import Router, F
|
||||
from aiogram.filters import Command
|
||||
|
||||
from bozenka.instances.telegram.handlers.chat_admin.help import *
|
||||
from bozenka.instances.telegram.handlers.chat_admin.mutes import mute, unmute
|
||||
from bozenka.instances.telegram.handlers.chat_admin.pins import pin, unpin, unpin_all
|
||||
from bozenka.instances.telegram.handlers.chat_admin.topics import *
|
||||
from bozenka.instances.telegram.handlers.chat_admin.bans import ban_command, unban_command
|
||||
from bozenka.instances.telegram.utils.filters import *
|
||||
|
||||
|
||||
def register_admin_cmd(router: Router) -> None:
|
||||
"""
|
||||
Registers all commands related to administrators in group.
|
||||
All commands there require access to some group perms.
|
||||
:param router:
|
||||
:return:
|
||||
"""
|
||||
logging.log(msg="Registering administrator commands", level=logging.INFO)
|
||||
|
||||
# Ban / Unban commands handler
|
||||
router.message.register(ban_command, Command(commands="ban"),
|
||||
IsAdminFilter(True), F.reply_to_message.text)
|
||||
router.message.register(unban_command, Command(commands="unban"),
|
||||
IsAdminFilter(True), F.reply_to_message.text)
|
||||
|
||||
# Mute / Unmute commands handler
|
||||
router.message.register(mute, Command(commands=["mute", "re"]), UserHasPermissions(["can_restrict_members"]),
|
||||
BotHasPermissions(["can_restrict_members"]))
|
||||
router.message.register(unmute, Command(commands=["unmute"]), UserHasPermissions(["can_restrict_members"]),
|
||||
BotHasPermissions(["can_restrict_members"]))
|
||||
|
||||
# Pin / Unpin / Unpinall commands handler
|
||||
router.message.register(pin, Command(commands="pin"), UserHasPermissions(["can_pin_messages"]),
|
||||
BotHasPermissions(["can_pin_messages"]), F.reply_to_message.text)
|
||||
router.message.register(unpin, Command(commands="unpin"), UserHasPermissions(["can_pin_messages"]),
|
||||
BotHasPermissions(["can_pin_messages"]), F.reply_to_message.text)
|
||||
router.message.register(unpin_all, Command(commands="unpin_all"), IsAdminFilter(True),
|
||||
BotHasPermissions(["can_pin_messages"]), F.reply_to_message.text)
|
||||
|
||||
# Topic managment handlers
|
||||
router.message.register(reopen_topic, Command(commands=["reopen_topic", "open_topic", "open"]),
|
||||
UserHasPermissions(["can_manage_topics"]),
|
||||
BotHasPermissions(["can_manage_topics"]), F.chat.is_forum)
|
||||
router.message.register(close_topic, Command(commands=["close_topic", "close"]),
|
||||
UserHasPermissions(["can_manage_topics"]),
|
||||
BotHasPermissions(["can_manage_topics"]), F.chat.is_forum)
|
||||
router.message.register(close_general_topic, Command(commands=["close_general"]),
|
||||
UserHasPermissions(["can_manage_topics"]),
|
||||
BotHasPermissions(["can_manage_topics"]), F.chat.is_forum)
|
||||
router.message.register(reopen_general_topic, Command(commands=["reopen_general", "open_general"]),
|
||||
UserHasPermissions(["can_manage_topics"]),
|
||||
BotHasPermissions(["can_manage_topics"]), F.chat.is_forum)
|
||||
router.message.register(hide_general_topic, Command(commands=["hide_general"]),
|
||||
UserHasPermissions(["can_manage_topics"]),
|
||||
BotHasPermissions(["can_manage_topics"]), F.chat.is_forum)
|
||||
router.message.register(unhide_general_topic, Command(commands=["unhide_general", "show_general"]),
|
||||
UserHasPermissions(["can_manage_topics"]),
|
||||
BotHasPermissions(["can_manage_topics"]), F.chat.is_forum)
|
||||
|
||||
# Helpig handlers
|
||||
router.message.register(help_ban, Command(commands=["ban"]))
|
||||
router.message.register(help_unban, Command(commands=["unban"]))
|
||||
router.message.register(help_mute, Command(commands=["mute"]))
|
||||
router.message.register(help_unmute, Command(commands=["mute"]))
|
||||
router.message.register(help_pin, Command(commands=["pin"]))
|
||||
router.message.register(help_unpin, Command(commands=["unpin"]))
|
||||
|
|
@ -1,114 +0,0 @@
|
|||
from aiogram.filters import CommandObject
|
||||
from aiogram.types import Message
|
||||
from aiogram.enums import ChatMemberStatus
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
|
||||
from bozenka.database.tables.telegram import get_chat_config_value
|
||||
from bozenka.instances.telegram.utils.keyboards import ban_keyboard, delete_keyboard
|
||||
|
||||
from bozenka.instances.telegram.utils.simpler import SolutionSimpler, ru_cmds, list_of_features
|
||||
|
||||
|
||||
async def ban_command(msg: Message, command: CommandObject, session_maker: async_sessionmaker) -> None:
|
||||
"""
|
||||
/ban command function, supports time and reasons.
|
||||
:param msg: Message telegram object
|
||||
:param command: Object of telegram command
|
||||
:param session_maker: Session maker object of SqlAlchemy
|
||||
:return: Nothing
|
||||
"""
|
||||
banned_user = await msg.chat.get_member(msg.reply_to_message.from_user.id)
|
||||
send_to_dm = await get_chat_config_value(chat_id=msg.chat.id, session=session_maker, setting=list_of_features["Admin"][4])
|
||||
send_notification = await get_chat_config_value(chat_id=msg.chat.id, session=session_maker, setting=list_of_features["Admin"][5])
|
||||
|
||||
where_send = {
|
||||
True: msg.from_user.id,
|
||||
False: msg.chat.id
|
||||
}
|
||||
|
||||
if banned_user.status == ChatMemberStatus.KICKED:
|
||||
await msg.bot.send_message(chat_id=where_send[send_to_dm],
|
||||
text="Ошибка ❌\n"
|
||||
"Этот пользователь уже удален из группы",
|
||||
reply_markup=delete_keyboard(msg.from_user.id))
|
||||
await msg.answer()
|
||||
return
|
||||
|
||||
config = await SolutionSimpler.ban_user(msg, command, session_maker)
|
||||
if config["reason"] and config["ban_time"]:
|
||||
await msg.answer("Удача ✅\n"
|
||||
f"Пользователь {msg.reply_to_message.from_user.mention_html()} был заблокирован пользователем {msg.from_user.mention_html()}.\n"
|
||||
f"По причине {config['reason']}, до даты {config['ban_time']}",
|
||||
reply_markup=ban_keyboard(msg.from_user.id, msg.reply_to_message.from_user.id))
|
||||
elif config["reason"]:
|
||||
await msg.answer(
|
||||
"Удача ✅\n"
|
||||
f"Пользователь {msg.reply_to_message.from_user.mention_html()} был заблокирован пользователем {msg.reply_to_message.from_user.mention_html()}.\n"
|
||||
f"По причине {config['reason']}.",
|
||||
reply_markup=ban_keyboard(admin_id=msg.from_user.id, ban_id=msg.reply_to_message.from_user.id)
|
||||
)
|
||||
elif config["ban_time"]:
|
||||
await msg.answer(
|
||||
"Удача ✅\n"
|
||||
f"Пользователь {msg.reply_to_message.from_user.mention_html()} был заблокирован пользователем {msg.from_user.mention_html()}, до даты {config['ban_time']}",
|
||||
reply_markup=ban_keyboard(admin_id=msg.from_user.id, ban_id=msg.reply_to_message.from_user.id)
|
||||
)
|
||||
else:
|
||||
await msg.answer(
|
||||
"Удача ✅\n"
|
||||
f"Пользователь {msg.reply_to_message.from_user.mention_html()} был заблокирован пользователем {msg.from_user.mention_html()}.",
|
||||
reply_markup=ban_keyboard(msg.from_user.id, msg.reply_to_message.from_user.id)
|
||||
)
|
||||
|
||||
|
||||
async def unban_command(msg: Message, command: CommandObject, session_maker: async_sessionmaker) -> None:
|
||||
"""
|
||||
/unban command function
|
||||
:param msg: Message telegram object
|
||||
:param command: Object of telegram command
|
||||
:param session_maker: Session maker object of SqlAlchemy
|
||||
"""
|
||||
await SolutionSimpler.unban_user(msg, session_maker)
|
||||
unbanned_user = await msg.chat.get_member(msg.reply_to_message.from_user.id)
|
||||
if unbanned_user.is_member and unbanned_user.status != ChatMemberStatus.KICKED:
|
||||
await msg.answer(
|
||||
"Ошибка ❌\n"
|
||||
"Этот пользователь не находится в бане.",
|
||||
reply_markup=delete_keyboard(admin_id=msg.from_user.id)
|
||||
)
|
||||
elif not command.text:
|
||||
await msg.answer(
|
||||
"Удача ✅\n"
|
||||
f"Пользователь {msg.reply_to_message.from_user.mention_html()} был разблокирован пользователем {msg.from_user.mention_html()}.\n",
|
||||
reply_markup=ban_keyboard(admin_id=msg.from_user.id, ban_id=msg.reply_to_message.from_user.id)
|
||||
)
|
||||
else:
|
||||
await msg.answer(
|
||||
"Удача ✅\n"
|
||||
f"Пользователь {msg.reply_to_message.from_user.mention_html()} был разблокирован пользователем {msg.from_user.mention_html()}.\n"
|
||||
f"По причине {CommandObject.text}.",
|
||||
reply_markup=ban_keyboard(admin_id=msg.from_user.id, ban_id=msg.reply_to_message.from_user.id)
|
||||
)
|
||||
|
||||
|
||||
async def status_command(msg: Message, session_maker: async_sessionmaker) -> None:
|
||||
"""
|
||||
/status command function
|
||||
Checks is user banned and muted
|
||||
:param msg: Message telegram object
|
||||
:param session_maker: Session maker object of SqlAlchemy
|
||||
:return:
|
||||
"""
|
||||
config = await SolutionSimpler.get_status(msg, session_maker)
|
||||
msg_text = ""
|
||||
if config["is_banned"]:
|
||||
msg_text += "Находится в бане"
|
||||
if config["ban_reason"]:
|
||||
msg_text += f"по причине <code>{config['ban_reason']}</code>"
|
||||
msg_text += "🔨\n"
|
||||
if config["is_muted"]:
|
||||
msg_text += "Находится в муте"
|
||||
if config["mute_reason"]:
|
||||
msg_text += f"по причине <code>{config['mute_reason']}</code>"
|
||||
msg_text += "🤐\n"
|
||||
await msg.answer(msg_text, reply_markup=delete_keyboard(msg.from_user.id))
|
|
@ -1,76 +0,0 @@
|
|||
from aiogram.types import Message
|
||||
|
||||
from bozenka.instances.telegram.utils.keyboards import delete_keyboard
|
||||
|
||||
|
||||
async def help_ban(msg: Message) -> None:
|
||||
"""
|
||||
Shows help message for /ban
|
||||
:param msg: Message telegram object
|
||||
:return: Nothing
|
||||
"""
|
||||
await msg.answer("Использование:\n"
|
||||
"<pre>/ban [время блокировки] [причина блокировки]</pre>\n"
|
||||
"Ответьте на сообщение, чтобы заблокировать пользователя",
|
||||
reply_markup=delete_keyboard(msg.from_user.id))
|
||||
|
||||
|
||||
async def help_unban(msg: Message) -> None:
|
||||
"""
|
||||
Shows help message for /unban
|
||||
:param msg: Message telegram object
|
||||
:return: Nothing
|
||||
"""
|
||||
await msg.answer("Использование:\n"
|
||||
"<pre>/unban</pre>\n"
|
||||
"Ответьте на сообщение, чтобы разблокировать пользователя",
|
||||
reply_markup=delete_keyboard(msg.from_user.id))
|
||||
|
||||
|
||||
async def help_mute(msg: Message) -> None:
|
||||
"""
|
||||
Shows help message for /mute
|
||||
:param msg: Message telegram object
|
||||
:return: Nothing
|
||||
"""
|
||||
await msg.answer("Использование:\n"
|
||||
"<pre>/mute [время мута] [причина мута]</pre>\n"
|
||||
"Ответьте на сообщение, чтобы замутить пользователя",
|
||||
reply_markup=delete_keyboard(msg.from_user.id))
|
||||
|
||||
|
||||
async def help_unmute(msg: Message) -> None:
|
||||
"""
|
||||
Shows help message for /unmute
|
||||
:param msg: Message telegram object
|
||||
:return: Nothing
|
||||
"""
|
||||
await msg.answer("Использование:\n"
|
||||
"<pre>/unmute</pre>\n"
|
||||
"Ответьте на сообщение, чтобы замутить пользователя",
|
||||
reply_markup=delete_keyboard(msg.from_user.id))
|
||||
|
||||
|
||||
async def help_pin(msg: Message) -> None:
|
||||
"""
|
||||
Shows help message for /mute
|
||||
:param msg: Message telegram object
|
||||
:return: Nothing
|
||||
"""
|
||||
await msg.answer("Использование:\n"
|
||||
"<pre>/pin</pre>\n"
|
||||
"Ответьте на сообщение, чтобы закрепить сообщение",
|
||||
reply_markup=delete_keyboard(msg.from_user.id))
|
||||
|
||||
|
||||
async def help_unpin(msg: Message) -> None:
|
||||
"""
|
||||
Shows help message for /mute
|
||||
:param msg: Message telegram object
|
||||
:return: Nothing
|
||||
"""
|
||||
await msg.answer("Использование:\n"
|
||||
"<pre>/unpin</pre>\n"
|
||||
"Ответьте на сообщение, чтобы открепить сообщение",
|
||||
reply_markup=delete_keyboard(msg.from_user.id))
|
||||
|
|
@ -1,59 +0,0 @@
|
|||
from aiogram.filters import CommandObject
|
||||
from aiogram.types import Message as Message
|
||||
from aiogram.enums import ChatMemberStatus
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
from bozenka.instances.telegram.utils.keyboards import mute_keyboard, unmute_keyboard
|
||||
from bozenka.instances.telegram.utils.simpler import SolutionSimpler
|
||||
|
||||
|
||||
async def mute(msg: Message, command: CommandObject, session_maker: async_sessionmaker) -> None:
|
||||
"""
|
||||
Handler of command /mute
|
||||
Restricts member from using chat
|
||||
:param msg: Message telegram object
|
||||
:param command: Object of telegram command
|
||||
:param session_maker: Session maker object of SqlAlchemy
|
||||
:return: Nothing
|
||||
"""
|
||||
restricting = await msg.chat.get_member(msg.reply_to_message.from_user.id)
|
||||
if restricting.status == ChatMemberStatus.LEFT or restricting.status == ChatMemberStatus.KICKED:
|
||||
return
|
||||
config = await SolutionSimpler.mute_user(msg, command, session_maker)
|
||||
if config["mute_time"] and config["reason"] != "":
|
||||
await msg.answer("Удача ✅\n"
|
||||
f"{msg.from_user.mention_html('Этот пользователь')} запретил писать "
|
||||
f"сообщения {msg.reply_to_message.from_user.mention_html('этому пользователю')}.\n"
|
||||
f"По причине {config['reason']}, до даты {config['mute_time']}",
|
||||
reply_markup=mute_keyboard(msg.from_user.id, restricting.user.id))
|
||||
elif config["reason"] != "":
|
||||
await msg.answer("Удача ✅\n"
|
||||
f"{msg.from_user.mention_html('Этот пользователь')} запретил писать "
|
||||
f"сообщения {msg.reply_to_message.from_user.mention_html('этому пользователю')}.\n"
|
||||
f"По причине {config['reason']}",
|
||||
reply_markup=mute_keyboard(msg.from_user.id, restricting.user.id))
|
||||
elif config["mute_time"]:
|
||||
await msg.answer("Удача ✅\n"
|
||||
f"{msg.from_user.mention_html('Этот пользователь')} запретил писать "
|
||||
f"сообщения {msg.reply_to_message.from_user.mention_html('этому пользователю')}.\n"
|
||||
f"До даты {config['mute_time']}",
|
||||
reply_markup=mute_keyboard(msg.from_user.id, restricting.user.id))
|
||||
else:
|
||||
await msg.answer("Удача ✅\n"
|
||||
f"{msg.from_user.mention_html('Этот пользователь')} запретил писать "
|
||||
f"сообщения пользователю {msg.reply_to_message.from_user.mention_html()}.\n",
|
||||
reply_markup=mute_keyboard(msg.from_user.id, restricting.user.id))
|
||||
|
||||
|
||||
async def unmute(msg: Message, session_maker: async_sessionmaker) -> None:
|
||||
"""
|
||||
Handler of command /unmute
|
||||
Gives access member to send messages into chat
|
||||
:param msg: Message telegram object
|
||||
:param session_maker: Session maker object of SqlAlchemy
|
||||
:return: Nothing
|
||||
"""
|
||||
await SolutionSimpler.unmute_user(msg, session_maker)
|
||||
await msg.answer("Удача ✅"
|
||||
f"{msg.from_user.mention_html('Этот пользователь')} разрешил писать\n"
|
||||
f"сообщения {msg.reply_to_message.from_user.mention_html('этому пользователю')}",
|
||||
reply_markup=unmute_keyboard(msg.from_user.id, msg.reply_to_message.from_user.id))
|
|
@ -1,40 +0,0 @@
|
|||
from aiogram.types import Message as Message
|
||||
from bozenka.instances.telegram.utils.keyboards import unpin_msg_keyboard, pin_msg_keyboard, delete_keyboard
|
||||
from bozenka.instances.telegram.utils.simpler import SolutionSimpler
|
||||
|
||||
|
||||
async def pin(msg: Message) -> None:
|
||||
"""
|
||||
/pin command function, pins replied command
|
||||
:param msg: Message telegram object
|
||||
:return: Nothing
|
||||
"""
|
||||
await SolutionSimpler.pin_msg(msg)
|
||||
await msg.answer("Удача ✅\n"
|
||||
"Сообщение было закреплено 📌",
|
||||
reply_markup=pin_msg_keyboard(msg_id=msg.reply_to_message.message_id, user_id=msg.from_user.id))
|
||||
|
||||
|
||||
async def unpin(msg: Message) -> None:
|
||||
"""
|
||||
/unpin command function, unpins replied command
|
||||
:param msg: Message telegram object
|
||||
:return: Nothing
|
||||
"""
|
||||
await SolutionSimpler.unpin_msg(msg)
|
||||
await msg.answer("Удача ✅\n"
|
||||
"Сообщение было откреплено 📌",
|
||||
reply_markup=unpin_msg_keyboard(msg_id=msg.reply_to_message.message_id, user_id=msg.from_user.id))
|
||||
|
||||
|
||||
async def unpin_all(msg: Message) -> None:
|
||||
"""
|
||||
/unpin_all command function, unpins all messages in chat
|
||||
:param msg: Message telegram object
|
||||
:return: Nothing
|
||||
"""
|
||||
await SolutionSimpler.unpin_all_messages(msg)
|
||||
await msg.answer("Удача ✅\n"
|
||||
"Все сообщения были откреплены 📌",
|
||||
reply_markup=delete_keyboard(admin_id=msg.from_user.id))
|
||||
|
|
@ -1,93 +0,0 @@
|
|||
from aiogram import Bot
|
||||
from aiogram.filters import CommandObject
|
||||
from aiogram.types import Message as Message
|
||||
from bozenka.instances.telegram.utils.keyboards import delete_keyboard, close_thread_keyboard, open_thread_keyboard
|
||||
from bozenka.instances.telegram.utils.simpler import SolutionSimpler
|
||||
|
||||
|
||||
async def close_topic(msg: Message, bot: Bot) -> None:
|
||||
"""
|
||||
/close command function. Closing thread
|
||||
:param msg: Message telegram object
|
||||
:param bot: Object of telegram bot
|
||||
:return: Nothing
|
||||
"""
|
||||
config = await SolutionSimpler.close_topic(msg=msg)
|
||||
await msg.answer(config[0],
|
||||
reply_markup=close_thread_keyboard(user_id=msg.from_user.id)
|
||||
if config[1] else delete_keyboard(msg.from_user.id))
|
||||
|
||||
|
||||
async def reopen_topic(msg: Message, bot: Bot) -> None:
|
||||
"""
|
||||
/open command function. Opens thread
|
||||
:param msg: Message telegram object
|
||||
:param bot: Object of telegram bot
|
||||
:return: Nothing
|
||||
"""
|
||||
config = await SolutionSimpler.open_topic(msg=msg)
|
||||
await msg.answer(config[0],
|
||||
reply_markup=open_thread_keyboard(user_id=msg.from_user.id)
|
||||
if config[1] else delete_keyboard(msg.from_user.id))
|
||||
|
||||
|
||||
async def close_general_topic(msg: Message, bot: Bot) -> None:
|
||||
"""
|
||||
/close_general command function. Closes general thread
|
||||
:param msg: Message telegram object
|
||||
:param bot: Object of telegram bot
|
||||
:return: Nothing
|
||||
"""
|
||||
config = await SolutionSimpler.close_general_topic(msg=msg)
|
||||
await msg.answer(config[0],
|
||||
reply_markup=close_thread_keyboard(user_id=msg.from_user.id)
|
||||
if config[1] else delete_keyboard(msg.from_user.id))
|
||||
|
||||
|
||||
async def reopen_general_topic(msg: Message, bot: Bot) -> None:
|
||||
"""
|
||||
/open_general command function. Opens general thread
|
||||
:param msg: Message telegram object
|
||||
:param bot: Object of telegram bot
|
||||
:return: Nothing
|
||||
"""
|
||||
config = await SolutionSimpler.open_general_topic(msg=msg)
|
||||
await msg.answer(config[0],
|
||||
reply_markup=open_thread_keyboard(user_id=msg.from_user.id)
|
||||
if config[1] else delete_keyboard(msg.from_user.id))
|
||||
|
||||
|
||||
async def hide_general_topic(msg: Message, bot: Bot) -> None:
|
||||
"""
|
||||
/hide_general command function. Hides general thread
|
||||
:param msg: Message telegram object
|
||||
:param bot: Object of telegram bot
|
||||
:return: Nothing
|
||||
"""
|
||||
config = await SolutionSimpler.hide_general_topic(msg=msg)
|
||||
await msg.answer(config[0],
|
||||
reply_markup=delete_keyboard(msg.from_user.id))
|
||||
|
||||
|
||||
async def unhide_general_topic(msg: Message, bot: Bot) -> None:
|
||||
"""
|
||||
/show_general command function. Shows back general thread.
|
||||
:param msg: Message telegram object
|
||||
:param bot: Object of telegram bot
|
||||
:return: Nothing
|
||||
"""
|
||||
config = await SolutionSimpler.show_general_topic(msg=msg)
|
||||
await msg.answer(config[0],
|
||||
reply_markup=delete_keyboard(msg.from_user.id))
|
||||
|
||||
|
||||
async def rename_topic(msg: Message, bot: Bot, command: CommandObject) -> None:
|
||||
"""
|
||||
/rename command function. Rename thread to a new name
|
||||
:param msg: Message telegram object
|
||||
:param bot: Object of telegram bot
|
||||
:param command: Object of telegram command
|
||||
:return: Nothing
|
||||
"""
|
||||
await msg.general_forum_topic_unhidden
|
||||
await bot.edit_forum_topic(name=command.text, chat_id=msg.chat.id, message_thread_id=msg.message_thread_id)
|
|
@ -1,29 +0,0 @@
|
|||
|
||||
import logging
|
||||
|
||||
from aiogram.enums import ContentType
|
||||
from aiogram.filters import Command
|
||||
from aiogram import Router, F
|
||||
|
||||
from bozenka.instances.telegram.handlers.chat_user.about import about
|
||||
from bozenka.instances.telegram.handlers.chat_user.invite import invite
|
||||
from bozenka.instances.telegram.handlers.chat_user.info import chat_info
|
||||
from bozenka.instances.telegram.handlers.chat_user.welcome import *
|
||||
|
||||
|
||||
def register_user_cmd(router: Router) -> None:
|
||||
"""
|
||||
Registers all commands related to users, and can be used by them.
|
||||
Some of them require access to some perms for bot.
|
||||
:param router:
|
||||
:return:
|
||||
"""
|
||||
logging.log(msg="Registering user commands", level=logging.INFO)
|
||||
|
||||
router.message.register(invite, Command(commands=["invite"]))
|
||||
router.message.register(about, Command(commands=["about"]))
|
||||
|
||||
router.message.register(leave, F.content_type == ContentType.LEFT_CHAT_MEMBER)
|
||||
router.message.register(join, F.content_type == ContentType.NEW_CHAT_MEMBERS)
|
||||
|
||||
router.message.register(chat_info, Command(commands=["info"]))
|
|
@ -1,19 +0,0 @@
|
|||
import logging
|
||||
|
||||
from aiogram.types import Message as Message
|
||||
from bozenka.instances.telegram.utils.keyboards import about_keyboard
|
||||
|
||||
|
||||
async def about(msg: Message):
|
||||
"""
|
||||
Sending information about bot by command `/about`
|
||||
Will be deleted by its use
|
||||
:param msg:
|
||||
:return:
|
||||
"""
|
||||
logging.log(msg=f"Sending about information for user_id={msg.from_user.id}",
|
||||
level=logging.INFO)
|
||||
await msg.answer("Кто я? 👁"
|
||||
"\nЯ - многозадачный бот, разрабатываемый Bozo Developement и всё ещё нахожусь в разработке"
|
||||
"\n(Ссылочки на нас внизу короче)☺️",
|
||||
reply_markup=about_keyboard.as_markup())
|
|
@ -1,32 +0,0 @@
|
|||
import logging
|
||||
|
||||
from aiogram.types import Message
|
||||
from bozenka.instances.telegram.utils.simpler import ru_cmds
|
||||
from bozenka.instances.telegram.utils.keyboards import delete_keyboard
|
||||
|
||||
|
||||
async def chat_info(msg: Message):
|
||||
"""
|
||||
Shows information about chat by command `/info`
|
||||
:param msg:
|
||||
:return:
|
||||
"""
|
||||
logging.log(msg=f"Sending information about chat user_id={msg.from_user.id}",
|
||||
level=logging.INFO)
|
||||
chat = await msg.bot.get_chat(msg.chat.id)
|
||||
# Related texts
|
||||
texts = {
|
||||
"chat_types": {"group": "группой", "supergroup": "cупер группой"},
|
||||
"forum_type": {True: "форумом,", False: ", не является форумом,", None: ", не является форумом,"},
|
||||
"required_invite": {True: "требуется одобрение заявки на вступление", False: "заявка не требуется.",
|
||||
None: "заявка не требуется."},
|
||||
"hidden_members": {True: "присуствуют", False: "отсуствуют", None: "отсуствуют"},
|
||||
"isprotected": {True: "пересылать сообщения из группы можно.", False: "пересылать сообщения из группы нельзя.",
|
||||
None: "пересылать сообщения из группы можно."},
|
||||
}
|
||||
|
||||
await msg.answer(f"{chat.title}\n"
|
||||
f"{chat.description}\n\n"
|
||||
f"Является {texts['chat_types'][chat.type]} {texts['forum_type'][chat.is_forum]} {texts['required_invite'][chat.join_by_request]}\n"
|
||||
f"Скрытые пользователи {texts['hidden_members'][chat.has_hidden_members]}, {texts['isprotected'][chat.has_protected_content]}",
|
||||
reply_markup=delete_keyboard(admin_id=msg.from_user.id))
|
|
@ -1,22 +0,0 @@
|
|||
import logging
|
||||
|
||||
from aiogram.types import Message
|
||||
from bozenka.instances.telegram.utils.keyboards import invite_keyboard
|
||||
from bozenka.instances.telegram.utils.simpler import ru_cmds
|
||||
|
||||
|
||||
async def invite(msg: Message):
|
||||
"""
|
||||
Generating invite to group by /invite command
|
||||
:param msg:
|
||||
:return:
|
||||
"""
|
||||
logging.log(msg=f"Generating invite for user_id={msg.from_user.id}",
|
||||
level=logging.INFO)
|
||||
link = await msg.chat.create_invite_link()
|
||||
print(link.invite_link[0])
|
||||
await msg.answer(
|
||||
ru_cmds["invite_generation"].replace("user", msg.from_user.mention_html(ru_cmds["sir"])),
|
||||
reply_markup=invite_keyboard(link=str(link.invite_link), admin_id=msg.from_user.id, chat_name=msg.chat.full_name)
|
||||
)
|
||||
|
|
@ -1,50 +0,0 @@
|
|||
import logging
|
||||
|
||||
from aiogram import Bot
|
||||
from aiogram.types import Message as Message
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
|
||||
from bozenka.instances.telegram.utils.simpler import SolutionSimpler
|
||||
|
||||
|
||||
async def join(msg: Message, session_maker: async_sessionmaker):
|
||||
"""
|
||||
Send welcome message, after adding new member to chat.
|
||||
Also works on adding bot to chat and sending welcome message.
|
||||
:param msg:
|
||||
:param session_maker:
|
||||
:return:
|
||||
"""
|
||||
for new in msg.new_chat_members:
|
||||
if new.id != msg.bot.id:
|
||||
logging.log(msg=f"Saing welcome for user_id={new.id}, chat_id={msg.chat.id}",
|
||||
level=logging.INFO)
|
||||
await msg.answer(
|
||||
f"Пользователь {new.mention_html()} переехал в конфу, благодаря {msg.from_user.mention_html()}👋",
|
||||
)
|
||||
await msg.delete()
|
||||
else:
|
||||
logging.log(msg=f"Saing welcome to administrators for chat_id={msg.chat.id}",
|
||||
level=logging.INFO)
|
||||
await msg.answer("Здраствуйте администраторы чата 👋\n"
|
||||
"Я - <b>бозенька</b>, мультифункциональный бот, разрабатываемый Bozo Developement\n"
|
||||
"Выдайте мне <b>полные права администратора</b> для моей полной работы.\n"
|
||||
"Чтобы настроить функционал, используйте /setup или кнопку под сообщением", )
|
||||
await SolutionSimpler.auto_settings(msg=msg, session=session_maker)
|
||||
|
||||
|
||||
async def leave(msg: Message, bot: Bot):
|
||||
"""
|
||||
Sens goodbye message, after deleting member from chat
|
||||
:param msg:
|
||||
:param bot:
|
||||
:return:
|
||||
"""
|
||||
await msg.delete()
|
||||
if msg.from_user.id == bot.id:
|
||||
return
|
||||
logging.log(msg=f"Saing goodbye for user_id={msg.left_chat_member.id}, chat_id={msg.chat.id}",
|
||||
level=logging.INFO)
|
||||
await msg.answer(
|
||||
f"Пользователь {msg.left_chat_member.mention_html()} съехал с конфы, благодаря {msg.from_user.mention_html()}👋"
|
||||
)
|
|
@ -1,31 +0,0 @@
|
|||
import logging
|
||||
|
||||
from aiogram.filters import Command
|
||||
|
||||
from bozenka.instances.telegram.handlers.dev.hello import hi, testing
|
||||
from bozenka.instances.telegram.handlers.dev.text_generation import *
|
||||
from bozenka.instances.telegram.handlers.dev.image_generation import *
|
||||
|
||||
from bozenka.instances.telegram.utils.simpler import AnsweringGPT4Free, AnsweringGpt4All, GeneratingImages
|
||||
from aiogram import Router
|
||||
|
||||
|
||||
def register_dev_cmd(router: Router) -> None:
|
||||
"""
|
||||
Registering testing commands in development or planned in future and need much time to realise it.
|
||||
Don't need any special perms in group.
|
||||
:param router:
|
||||
:return:
|
||||
"""
|
||||
logging.log(msg="Registering developer commands", level=logging.INFO)
|
||||
router.message.register(hi, Command(commands=["hi", "welcome", "sup", "wassup", "hello", "priv",
|
||||
"privet", "хай", "прив", "привет", "ку"]))
|
||||
router.message.register(start_dialog_cmd, Command(commands=["conversation"]))
|
||||
router.message.register(g4f_generate_answer, AnsweringGPT4Free.ready_to_answer, ~Command(commands=["cancel"]))
|
||||
router.message.register(already_answering, AnsweringGpt4All.answering, ~Command(commands=["cancel"]))
|
||||
router.message.register(already_answering, AnsweringGPT4Free.answering, ~Command(commands=["cancel"]))
|
||||
router.message.register(g4a_generate_answer, AnsweringGpt4All.ready_to_answer, ~Command(commands=["cancel"]))
|
||||
router.message.register(kadinsky_generating_images, GeneratingImages.ready_to_generate, ~Command(commands=["cancel"]))
|
||||
router.message.register(start_imagine_cmd, Command(commands=["imagine"]))
|
||||
router.message.register(cancel_answering, Command(commands=["cancel"]))
|
||||
router.message.register(testing, Command(commands=["testingtest"]))
|
|
@ -1,28 +0,0 @@
|
|||
from aiogram import Bot
|
||||
from aiogram.filters import CommandObject
|
||||
from aiogram.types import Message as Message, User, Chat
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
|
||||
from bozenka.instances.telegram.utils.keyboards import delete_keyboard
|
||||
|
||||
|
||||
async def hi(msg: Message):
|
||||
"""
|
||||
Test command, sending welcome message.
|
||||
Made for testing bot working status.
|
||||
:param msg:
|
||||
:return:
|
||||
"""
|
||||
await msg.answer(
|
||||
f"Привет, {msg.from_user.mention_html('')} 👋",
|
||||
reply_markup=delete_keyboard(msg.from_user.id)
|
||||
)
|
||||
|
||||
|
||||
async def testing(msg: Message, session_maker: async_sessionmaker, command: CommandObject, user: User, target: User, chat: Chat, bot: Bot):
|
||||
print(user.full_name)
|
||||
print(target.full_name)
|
||||
print(msg)
|
||||
print(command.args)
|
||||
print(command.mention)
|
||||
print(command.command)
|
|
@ -1,95 +0,0 @@
|
|||
import logging
|
||||
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from aiogram.types import Message as Message, FSInputFile
|
||||
|
||||
from bozenka.generative.kadinsky import kadinsky_gen
|
||||
from bozenka.instances.telegram.utils.keyboards import delete_keyboard, image_generation_keyboard, \
|
||||
image_response_keyboard
|
||||
from bozenka.instances.telegram.utils.simpler import GeneratingImages
|
||||
|
||||
|
||||
async def already_generating(msg: Message, state: FSMContext):
|
||||
"""
|
||||
Giving response, if generating image for user right now,
|
||||
but user still asks something
|
||||
:param msg: Message telegram object
|
||||
:param state: FSM state of bot
|
||||
:return:
|
||||
"""
|
||||
await msg.answer(
|
||||
"Подождите пожалуйста, мы уже генерируем изображение для вас, подождите, когда мы ответим на ваш передыдущий вопрос",
|
||||
reply_markup=delete_keyboard(admin_id=msg.from_user.id))
|
||||
|
||||
|
||||
async def start_imagine_cmd(msg: Message, state: FSMContext):
|
||||
"""
|
||||
/iamgine command handler, start menu
|
||||
:param msg: Message telegram object
|
||||
:param state: FSM state of bot
|
||||
:return:
|
||||
"""
|
||||
if await state.get_state():
|
||||
return
|
||||
await msg.answer("Пожалуста, выберите сервис / модель для генерации изображений",
|
||||
reply_markup=image_generation_keyboard(user_id=msg.from_user.id))
|
||||
|
||||
|
||||
async def kadinsky_generating_images(msg: Message, state: FSMContext):
|
||||
"""
|
||||
Message handler for kandinsky to generate image by text from message
|
||||
:param msg: Message telegram object
|
||||
:param state: FSM state of bot
|
||||
:return:
|
||||
"""
|
||||
await state.set_state(GeneratingImages.generating)
|
||||
message = await msg.answer("Пожалуйста подождите, мы генерируем изображение ⏰\n"
|
||||
"Если что-то пойдет не так, мы вам сообщим 👌")
|
||||
data = await state.get_data()
|
||||
|
||||
try:
|
||||
|
||||
model_id = kadinsky_gen.get_model()
|
||||
width, height = data["set_size"].split("x")
|
||||
generating = kadinsky_gen.generate(model=model_id,
|
||||
prompt=msg.text,
|
||||
width=int(width),
|
||||
height=int(height))
|
||||
result = kadinsky_gen.check_generation(request_id=generating)
|
||||
|
||||
if result:
|
||||
path = kadinsky_gen.save_image(result[0], f"telegram_{msg.from_user.id}")
|
||||
photo = FSInputFile(path)
|
||||
await msg.answer_photo(photo=photo,
|
||||
caption=msg.text,
|
||||
reply_markup=image_response_keyboard(user_id=msg.from_user.id))
|
||||
await message.delete()
|
||||
else:
|
||||
await message.edit_text("Простите, произошла ошибка 😔\n"
|
||||
"Убедитесь, что севрера kadinsky работают и ваш промт не является неподобающим и неприемлимым\n"
|
||||
"Если это продолжается, пожалуйста используйте /cancel",
|
||||
reply_markup=image_response_keyboard(user_id=msg.from_user.id))
|
||||
|
||||
except Exception as ex:
|
||||
logging.log(msg=f"Get an exception for generating answer={ex}",
|
||||
level=logging.ERROR)
|
||||
finally:
|
||||
logging.log(msg=f"Generated image for user_id={msg.from_user.id} with promt",
|
||||
level=logging.INFO)
|
||||
await state.set_state(GeneratingImages.ready_to_generate)
|
||||
|
||||
|
||||
async def cancefl_answering(msg: Message, state: FSMContext):
|
||||
"""
|
||||
Canceling generating images for user
|
||||
Works on command /cancel
|
||||
:param msg: Message telegram object
|
||||
:param state: FSM state of bot
|
||||
:return:
|
||||
"""
|
||||
current = await state.get_state()
|
||||
if current is None:
|
||||
return
|
||||
await state.clear()
|
||||
await msg.answer("Удача ✅\n"
|
||||
"Диалог отменён!", reply_markup=delete_keyboard(admin_id=msg.from_user.id))
|
|
@ -1,156 +0,0 @@
|
|||
import logging
|
||||
import os.path
|
||||
|
||||
import g4f
|
||||
from gpt4all import GPT4All
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from aiogram.types import Message as Message
|
||||
|
||||
from bozenka.generative.gpt4all import check, model_path
|
||||
from bozenka.instances.telegram.utils.keyboards import gpt_categories_keyboard, delete_keyboard, text_response_keyboard
|
||||
from bozenka.instances.telegram.utils.simpler import AnsweringGpt4All, \
|
||||
AnsweringGPT4Free
|
||||
from bozenka.generative.gpt4free import generate_gpt4free_providers
|
||||
|
||||
|
||||
async def already_answering(msg: Message, state: FSMContext):
|
||||
"""
|
||||
Giving response, if answering user now,
|
||||
but he still asks something
|
||||
:param msg: Message telegram object
|
||||
:param state: FSM state of bot
|
||||
:return:
|
||||
"""
|
||||
await msg.answer("Подождите пожалуйста, мы уже генерируем ответ для вас, подождите, когда мы ответим на ваш передыдущий вопрос",
|
||||
reply_markup=delete_keyboard(admin_id=msg.from_user.id))
|
||||
|
||||
|
||||
async def start_dialog_cmd(msg: Message, state: FSMContext):
|
||||
"""
|
||||
/conversation command handler, start
|
||||
:param msg: Message telegram object
|
||||
:param state: FSM state of bot
|
||||
:return:
|
||||
"""
|
||||
if await state.get_state():
|
||||
return
|
||||
await msg.answer("Пожалуста, выберите сервис для ИИ.",
|
||||
reply_markup=gpt_categories_keyboard
|
||||
(user_id=msg.from_user.id))
|
||||
|
||||
|
||||
async def cancel_answering(msg: Message, state: FSMContext):
|
||||
"""
|
||||
Canceling dialog with generative model
|
||||
Works on command /cancel
|
||||
:param msg: Message telegram object
|
||||
:param state: FSM state of bot
|
||||
:return:
|
||||
"""
|
||||
current = await state.get_state()
|
||||
if current is None:
|
||||
return
|
||||
await state.clear()
|
||||
await msg.answer("Удача ✅\n"
|
||||
"Диалог отменён!", reply_markup=delete_keyboard(admin_id=msg.from_user.id))
|
||||
|
||||
|
||||
async def g4a_generate_answer(msg: Message, state: FSMContext):
|
||||
"""
|
||||
Generating answer if Gpt4All has been selected
|
||||
:param msg: Message telegram object
|
||||
:param state: FSM state of bot
|
||||
:return:
|
||||
"""
|
||||
await state.set_state(AnsweringGpt4All.answering)
|
||||
|
||||
models = GPT4All.list_models()
|
||||
info = await state.get_data()
|
||||
answer = ""
|
||||
|
||||
main_msg = await msg.answer("Пожалуйста подождите, мы генерируем вам ответ ⏰\n"
|
||||
"Если что-то пойдет не так, мы вам сообщим 👌",
|
||||
reply_markup=text_response_keyboard(user_id=msg.from_user.id))
|
||||
|
||||
if not check(models[info["set_model"]]["filename"]):
|
||||
main_msg = await main_msg.edit_text(main_msg.text + "\nПодождите пожалуста, мы скачиваем модель...",
|
||||
reply_markup=main_msg.reply_markup)
|
||||
|
||||
try:
|
||||
# Setting Gpt4All model
|
||||
model = GPT4All(model_name=models[info['set_model']]['filename'],
|
||||
model_path=model_path,
|
||||
allow_download=True)
|
||||
# Setting our chat session if exist
|
||||
model.current_chat_session = [] if not info.get("ready_to_answer") else info["ready_to_answer"]
|
||||
# Generating answer
|
||||
with model.chat_session():
|
||||
answer = model.generate(msg.text)
|
||||
await state.update_data(ready_to_answer=model.current_chat_session)
|
||||
|
||||
except Exception as S:
|
||||
answer = "Простите, произошла ошибка 😔\nЕсли это продолжается, пожалуйста используйте /cancel"
|
||||
logging.log(msg=f"Get an exception for generating answer={S}",
|
||||
level=logging.ERROR)
|
||||
finally:
|
||||
await main_msg.edit_text(answer, reply_markup=text_response_keyboard(user_id=msg.from_user.id))
|
||||
|
||||
await state.set_state(AnsweringGpt4All.ready_to_answer)
|
||||
|
||||
|
||||
async def g4f_generate_answer(msg: Message, state: FSMContext):
|
||||
"""
|
||||
Generating answer if GPT4Free model and provider has been selected
|
||||
:param msg: Message telegram object
|
||||
:param state: FSM state of bot
|
||||
:return:
|
||||
"""
|
||||
await state.set_state(AnsweringGPT4Free.answering)
|
||||
|
||||
info = await state.get_data()
|
||||
|
||||
providers = generate_gpt4free_providers()
|
||||
reply = await msg.reply("Пожалуйста подождите, мы генерируем ответ от провайдера ⏰\n"
|
||||
"Если что-то пойдет не так, мы вам сообщим 👌")
|
||||
|
||||
current_messages = []
|
||||
if info.get("ready_to_answer"):
|
||||
for message in info["ready_to_answer"]:
|
||||
current_messages.append(message)
|
||||
|
||||
if not info.get("set_provider"):
|
||||
info["set_provider"] = None
|
||||
|
||||
current_messages.append({"role": "user", "content": msg.text})
|
||||
|
||||
response = ""
|
||||
try:
|
||||
response = await g4f.ChatCompletion.create_async(
|
||||
model=info["set_model"],
|
||||
messages=current_messages,
|
||||
provider=None if info["set_provider"] is None else providers[info["set_provider"]],
|
||||
stream=False
|
||||
)
|
||||
|
||||
except NameError or SyntaxError:
|
||||
try:
|
||||
response = g4f.ChatCompletion.create(
|
||||
model=info["set_model"],
|
||||
messages=current_messages,
|
||||
provider=None if info["set_provider"] is None else providers[info["set_provider"]],
|
||||
stream=False
|
||||
)
|
||||
except Exception as S:
|
||||
response = "Простите, произошла ошибка 😔\nЕсли это продолжается, пожалуйста используйте /cancel"
|
||||
logging.log(msg=f"Get an exception for generating answer={S}",
|
||||
level=logging.ERROR)
|
||||
except Exception as S:
|
||||
response = "Простите, произошла ошибка 😔\nЕсли это продолжается, пожалуйста используйте /cancel"
|
||||
logging.log(msg=f"Get an exception for generating answer={S}",
|
||||
level=logging.ERROR)
|
||||
finally:
|
||||
await reply.edit_text(text=response, reply_markup=text_response_keyboard(user_id=msg.from_user.id))
|
||||
current_messages.append({"role": "assistant", "content": response})
|
||||
await state.update_data(ready_to_answer=current_messages)
|
||||
await state.set_state(AnsweringGPT4Free.ready_to_answer)
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
|
||||
import logging
|
||||
|
||||
from aiogram import Router, F
|
||||
from aiogram.enums import ContentType
|
||||
from aiogram.filters import Command, CommandStart
|
||||
|
||||
from bozenka.instances.telegram.handlers.main.setup import *
|
||||
from bozenka.instances.telegram.handlers.main.start import *
|
||||
|
||||
|
||||
def register_main_cmd(router: Router) -> None:
|
||||
"""
|
||||
Registers all commands related to basic commands or main commands in bot.
|
||||
Don't require any special perms for bot in group.
|
||||
:param router:
|
||||
:return:
|
||||
"""
|
||||
logging.log(msg="Registering main related commands", level=logging.INFO)
|
||||
|
||||
# Start command handler
|
||||
"""
|
||||
router.message.register(start_cmd, Command(commands=["start"]), F.chat.type == ChatType.PRIVATE)
|
||||
"""
|
||||
|
||||
router.message.register(start_cmd, *[Command(commands=["start"]), F.chat.type == ChatType.PRIVATE])
|
||||
|
||||
# Registering command /setup
|
||||
router.message.register(setup_cmd, Command(commands=["setup"]), ~(F.chat.type == ChatType.PRIVATE))
|
||||
|
||||
# After adding to chat handler
|
||||
router.message.register(group_adding_handler, F.content_type == ContentType.SUPERGROUP_CHAT_CREATED)
|
||||
router.message.register(group_adding_handler, F.content_type == ContentType.GROUP_CHAT_CREATED)
|
|
@ -1,31 +0,0 @@
|
|||
from aiogram.types import Message as Message
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
|
||||
from bozenka.instances.telegram.utils.simpler import SolutionSimpler
|
||||
from bozenka.instances.telegram.utils.keyboards import setup_keyboard
|
||||
|
||||
|
||||
async def setup_cmd(msg: Message):
|
||||
"""
|
||||
/setup handler
|
||||
:param msg:
|
||||
:param session:
|
||||
:return:
|
||||
"""
|
||||
await msg.answer("Привет владелец чата 👋\n"
|
||||
"Чтобы меня настроить, используй меню под данным сообщением",
|
||||
reply_markup=setup_keyboard())
|
||||
|
||||
|
||||
async def group_adding_handler(msg: Message, session_maker: async_sessionmaker):
|
||||
"""
|
||||
Send message after adding bozenka into group chat
|
||||
:param msg:
|
||||
:param session_maker:
|
||||
:return:
|
||||
"""
|
||||
await SolutionSimpler.auto_settings(msg=msg, session=session_maker)
|
||||
await msg.answer("Здраствуйте администраторы чата 👋\n"
|
||||
"Я - <b>бозенька</b>, мультифункциональный бот, разрабатываемый Bozo Developement\n"
|
||||
"Выдайте мне <b>полные права администратора</b> для моей полной работы, если не выдали."
|
||||
"Чтобы настроить функционал, используйте /setup или кнопку под сообщением")
|
|
@ -1,36 +0,0 @@
|
|||
from aiogram.enums import ChatType
|
||||
from aiogram.types import Message as Message
|
||||
from aiogram.utils.keyboard import InlineKeyboardBuilder
|
||||
|
||||
from bozenka.instances.telegram.utils.keyboards import help_keyboard, start_keyboard
|
||||
|
||||
|
||||
async def start_cmd(msg: Message) -> None:
|
||||
"""
|
||||
/start command function handler
|
||||
Shows menu and basic information about bozenka
|
||||
:param msg: Message telegram object
|
||||
:return: Nothing
|
||||
"""
|
||||
await msg.answer(
|
||||
"""
|
||||
Привет 👋
|
||||
Я - бозенька, бот с открытым исходным кодом, который поможет тебе в различных задачах.
|
||||
|
||||
Вот что ты можешь сделать с помощью меню:
|
||||
• Добавить в чат: добавляет меня в групповой чат, чтобы я мог выполнять свои функции внутри него.
|
||||
• Функционал: показывает список доступных функций и команд, которые я могу выполнить.
|
||||
• О разработчиках: предоставляет информацию о команде разработчиков, которые создали и поддерживают этого бота.
|
||||
• О запущенном экземпляре: выводит информацию о текущей версии и состоянии запущенного экземпляра бота.
|
||||
• Начать диалог с ИИ: позволяет начать диалог с искусственным интеллектом, который может отвечать на вопросы и предоставлять информацию.
|
||||
• Генерация изображений: позволяет сгенерировать изображения на основе заданных параметров и промта
|
||||
|
||||
Вот нужные ссылки обо мне:
|
||||
• <a href='https://t.me/bozodevelopment'>Канал с новостями об разработке</a>
|
||||
• <a href='https://github.com/kittyneverdies/bozenka/'>Исходный код на Github</a>
|
||||
|
||||
Чтобы воспользоваться какой-либо функцией, просто нажми на соответствующую кнопку ниже.
|
||||
Если у тебя возникнут вопросы или проблемы, не стесняйся обратиться к команде разработчиков или написать в обсуждении телеграм канала.
|
||||
Удачного использования!
|
||||
""",
|
||||
reply_markup=start_keyboard(), disable_web_page_preview=True)
|
|
@ -1,128 +0,0 @@
|
|||
from aiogram import Router, F
|
||||
|
||||
from bozenka.instances.telegram.handlers.queries.image_generation import inline_image_size, inline_image_ready
|
||||
from bozenka.instances.telegram.handlers.queries.mute import *
|
||||
from bozenka.instances.telegram.handlers.queries.start import *
|
||||
from bozenka.instances.telegram.utils.callbacks_factory import *
|
||||
from bozenka.instances.telegram.handlers.queries.ban import *
|
||||
from bozenka.instances.telegram.handlers.queries.pins import *
|
||||
from bozenka.instances.telegram.handlers.queries.threads import *
|
||||
from bozenka.instances.telegram.handlers.queries.delete import *
|
||||
from bozenka.instances.telegram.handlers.queries.revoke import *
|
||||
from bozenka.instances.telegram.handlers.queries.text_generation import *
|
||||
from bozenka.instances.telegram.handlers.queries.setup import *
|
||||
|
||||
|
||||
def register_queries(router: Router) -> None:
|
||||
"""
|
||||
Register all callback queries.
|
||||
:param router:
|
||||
:return:
|
||||
"""
|
||||
logging.log(msg="Registering callback queries", level=logging.INFO)
|
||||
|
||||
# Moderation
|
||||
# Ban / Unban buttons reactions
|
||||
router.callback_query.register(inline_ban, BanData.filter())
|
||||
router.callback_query.register(inline_unban, UnbanData.filter())
|
||||
|
||||
# Mute / Un,ute buttons reactions
|
||||
router.callback_query.register(inline_mute, MuteData.filter())
|
||||
router.callback_query.register(inline_unmute, UnmuteData.filter())
|
||||
|
||||
# Revoke telegram invite link button
|
||||
router.callback_query.register(inline_revoke, RevokeCallbackData.filter())
|
||||
# Delete button message reaction
|
||||
router.callback_query.register(inline_delete, DeleteMenu.filter())
|
||||
|
||||
# Threads (Close/Open)
|
||||
router.callback_query.register(inline_close_thread, CloseThread.filter())
|
||||
router.callback_query.register(inline_open_thread, OpenThread.filter())
|
||||
|
||||
# Pins (Pin/Unpin)
|
||||
router.callback_query.register(inline_pin_msg, PinMsg.filter())
|
||||
router.callback_query.register(inline_unpin_msg, UnpinMsg.filter())
|
||||
|
||||
# GPT Related queries
|
||||
|
||||
# Back to gpt categories
|
||||
router.callback_query.register(inline_start_gpt, GptBackMenu.filter(F.back_to == "category"))
|
||||
|
||||
# Gpt4Free menus (Providers/Models)
|
||||
router.callback_query.register(inline_g4f_categories, GptCategory.filter(F.category == "Gpt4Free"))
|
||||
router.callback_query.register(inline_g4f_categories, GptBackMenu.filter(F.back_to == "g4fcategory"))
|
||||
|
||||
router.callback_query.register(inline_g4f_provider_models, Gpt4FreeProvider.filter())
|
||||
|
||||
router.callback_query.register(inline_g4f_models, Gpt4FreeCategory.filter(F.category == "models"))
|
||||
router.callback_query.register(inline_g4f_providers, Gpt4FreeCategory.filter(F.category == "providers"))
|
||||
|
||||
router.callback_query.register(inline_g4f_model_select, Gpt4FreeModel.filter())
|
||||
router.callback_query.register(inline_g4f_next_models, Gpt4FreeModelPage.filter())
|
||||
|
||||
# Get back to menu state
|
||||
router.callback_query.register(inline_g4f_providers_back, GptBackMenu.filter(F.back_to == "providers"))
|
||||
|
||||
# Generates next pages (Providers/Models)
|
||||
router.callback_query.register(inline_next_g4f_models, Gpt4FreeProvsModelPage.filter(), flags={"rate_limit": {"rate": 5}})
|
||||
router.callback_query.register(inline_next_g4f_providers, Gpt4FreeProviderPage.filter(),
|
||||
flags={"rate_limit": {"rate": 5}})
|
||||
|
||||
# Help information (for page button under menu)
|
||||
router.callback_query.register(inline_return_pages, F.data == "gotpages")
|
||||
router.callback_query.register(inline_g4f_ready, Gpt4freeResult.filter())
|
||||
|
||||
# Image generation menu
|
||||
# Size setting
|
||||
router.callback_query.register(inline_image_size, ImageGenerationCategory.filter())
|
||||
|
||||
# Ready status
|
||||
router.callback_query.register(inline_image_ready, ImageGeneration.filter())
|
||||
|
||||
# Gpt4All menus
|
||||
# Gpt4All model menu
|
||||
router.callback_query.register(inline_g4a, GptCategory.filter(F.category == "Gpt4All"))
|
||||
|
||||
# Gpt4All back
|
||||
router.callback_query.register(inline_g4a_back, GptBackMenu.filter(F.back_to == "g4amodels"))
|
||||
|
||||
# Gpt4All selected model menu
|
||||
router.callback_query.register(inline_g4a_model, Gpt4AllModel.filter())
|
||||
router.callback_query.register(inline_g4a_select_model, Gpt4AllSelect.filter())
|
||||
|
||||
# Stop dialog button under gpt message answer
|
||||
router.callback_query.register(inline_stop_dialog, GptStop.filter())
|
||||
|
||||
# /setup command related queries
|
||||
# List of features based on category
|
||||
router.callback_query.register(inline_setup_category, SetupCategory.filter())
|
||||
|
||||
# Menu of feature to enable or disable
|
||||
router.callback_query.register(inline_edit_feature, SetupFeature.filter())
|
||||
router.callback_query.register(inline_feature_edited, SetupAction.filter(F.action == "enable"))
|
||||
router.callback_query.register(inline_feature_edited, SetupAction.filter(F.action == "disable"))
|
||||
|
||||
# Back from feature to category
|
||||
router.callback_query.register(inline_setup_category_back, SetupAction.filter(F.action == "back"))
|
||||
|
||||
# /start command related queries
|
||||
# Help of features based on category
|
||||
router.callback_query.register(inline_help_features, HelpCategory.filter())
|
||||
router.callback_query.register(inline_back_help_categories, HelpBack.filter(F.back_to == "category"))
|
||||
router.callback_query.register(inline_back_help_features, HelpBackCategory.filter())
|
||||
|
||||
# Menu to back
|
||||
router.callback_query.register(inline_help_feature, HelpFeature.filter())
|
||||
|
||||
# Back to /start
|
||||
router.callback_query.register(inline_start, F.data == "back")
|
||||
|
||||
# Categories of menu
|
||||
router.callback_query.register(inline_about_developers, F.data == "aboutdevs")
|
||||
router.callback_query.register(inline_add_to_chat, F.data == "addtochat")
|
||||
router.callback_query.register(inline_start_chatbot, F.data == "dialogai")
|
||||
router.callback_query.register(inline_help, F.data == "functional")
|
||||
router.callback_query.register(inline_about_instance, F.data == "aboutbot")
|
||||
|
||||
|
||||
|
|
@ -1,67 +0,0 @@
|
|||
import logging
|
||||
|
||||
from aiogram import types
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
|
||||
from bozenka.instances.telegram.utils.callbacks_factory import BanData, UnbanData
|
||||
from aiogram.enums import ChatMemberStatus
|
||||
|
||||
from bozenka.instances.telegram.utils.keyboards import ban_keyboard, unban_keyboard
|
||||
from bozenka.instances.telegram.utils.simpler import SolutionSimpler
|
||||
|
||||
|
||||
async def inline_ban(call: types.CallbackQuery, callback_data: BanData, session_maker: async_sessionmaker) -> None:
|
||||
"""
|
||||
Query, what bannes users after callback
|
||||
:param call: CallBackQuery telegram object
|
||||
:param callback_data: BanData object
|
||||
:param session_maker: AsyncSessionmaker object
|
||||
:return:
|
||||
"""
|
||||
clicked_user = await call.message.chat.get_member(call.from_user.id)
|
||||
banned_user = await call.message.chat.get_member(int(callback_data.user_id_ban))
|
||||
|
||||
if call.from_user.id != callback_data.user_id_clicked \
|
||||
and clicked_user.status not in [ChatMemberStatus.ADMINISTRATOR, ChatMemberStatus.CREATOR]:
|
||||
return
|
||||
await SolutionSimpler.inline_ban_user(call=call, data=callback_data, session=session_maker)
|
||||
|
||||
if not banned_user.is_member and banned_user.status == ChatMemberStatus.KICKED:
|
||||
await call.answer("Уже заблокирован ✅")
|
||||
else:
|
||||
await call.answer("Успешно заблокирован ✅")
|
||||
|
||||
await call.message.edit_text(
|
||||
"Удача ✅\n"
|
||||
f"{banned_user.user.mention_html('Этот пользователь')} был заблокирован {call.from_user.mention_html('этим пользователем')}.",
|
||||
reply_markup=ban_keyboard(admin_id=call.from_user.id, ban_id=banned_user.user.id)
|
||||
)
|
||||
logging.log(msg=f"Banned user @{banned_user.user.full_name} user_id=f{banned_user.user.id}", level=logging.INFO)
|
||||
|
||||
|
||||
async def inline_unban(call: types.CallbackQuery, callback_data: UnbanData, session_maker: async_sessionmaker) -> None:
|
||||
"""
|
||||
Query, what unbannes users after callback
|
||||
:param call: CallBackQuery telegram object
|
||||
:param callback_data: UnbanData object
|
||||
:param session_maker: AsyncSessionmaker object
|
||||
:return:
|
||||
"""
|
||||
clicked_user = await call.message.chat.get_member(call.from_user.id)
|
||||
unbanned_user = await call.message.chat.get_member(int(callback_data.user_id_unban))
|
||||
if call.from_user.id != callback_data.user_id_clicked \
|
||||
and clicked_user.status not in [ChatMemberStatus.ADMINISTRATOR, ChatMemberStatus.CREATOR]:
|
||||
return
|
||||
|
||||
await SolutionSimpler.inline_unban_user(call=call, data=callback_data, session=session_maker)
|
||||
|
||||
if unbanned_user.is_member and unbanned_user.status != ChatMemberStatus.KICKED:
|
||||
await call.answer("Уже разблокирован ✅")
|
||||
else:
|
||||
await call.answer("Успешно разблокирован ✅")
|
||||
await call.message.edit_text(
|
||||
"Удача ✅\n"
|
||||
f"{unbanned_user.user.mention_html('Этот пользователь')} был разблокирован {call.from_user.mention_html('этим пользователем')}.",
|
||||
reply_markup=unban_keyboard(admin_id=call.from_user.id, ban_id=unbanned_user.user.id)
|
||||
)
|
||||
logging.log(msg=f"Unbanned user @{unbanned_user.user.full_name} user_id=f{unbanned_user.user.id}", level=logging.INFO)
|
|
@ -1,21 +0,0 @@
|
|||
import logging
|
||||
|
||||
from aiogram import types
|
||||
|
||||
from bozenka.instances.telegram.utils.callbacks_factory import DeleteMenu
|
||||
from aiogram.enums import ChatMemberStatus
|
||||
|
||||
|
||||
async def inline_delete(call: types.CallbackQuery, callback_data: DeleteMenu) -> None:
|
||||
"""
|
||||
Deletes messsage, after special callback
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
user_clicked = await call.message.chat.get_member(call.from_user.id)
|
||||
if call.from_user.id == callback_data.user_id_clicked or user_clicked.status == ChatMemberStatus.ADMINISTRATOR:
|
||||
await call.answer("Хорошо ✅")
|
||||
logging.log(msg=f"Deleted message with message_id={call.message.message_id}",
|
||||
level=logging.INFO)
|
||||
await call.message.delete()
|
|
@ -1,60 +0,0 @@
|
|||
import logging
|
||||
|
||||
from aiogram import types
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from gpt4all import GPT4All
|
||||
|
||||
from bozenka.instances.telegram.utils.simpler.fsm_states import *
|
||||
|
||||
# Callbacks for GPT
|
||||
from bozenka.instances.telegram.utils.callbacks_factory import (
|
||||
ImageGeneration,
|
||||
ImageGenerationCategory
|
||||
)
|
||||
# Keyboards for messages
|
||||
from bozenka.instances.telegram.utils.keyboards import (
|
||||
gpt4free_models_by_provider_keyboard,
|
||||
gpt4free_providers_keyboard,
|
||||
delete_keyboard, gpt_categories_keyboard, generate_gpt4all_page, gpt4all_model_menu, image_resolution_keyboard
|
||||
)
|
||||
# Simpler utlilities
|
||||
from bozenka.instances.telegram.utils.simpler import (
|
||||
AnsweringGPT4Free,
|
||||
AnsweringGpt4All,
|
||||
)
|
||||
|
||||
|
||||
async def inline_image_size(call: types.CallbackQuery, callback_data: ImageGenerationCategory, state: FSMContext) -> None:
|
||||
"""
|
||||
Query, what shows menu for image size to generate in
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:param state:
|
||||
:return:
|
||||
"""
|
||||
if call.from_user.id != callback_data.user_id:
|
||||
return
|
||||
|
||||
await state.update_data(set_category=callback_data.category)
|
||||
await state.set_state(GeneratingImages.set_size)
|
||||
await call.message.edit_text("Пожалуста, выберите размер изображения 🖼",
|
||||
reply_markup=image_resolution_keyboard(user_id=call.from_user.id,
|
||||
category=callback_data.category))
|
||||
|
||||
|
||||
async def inline_image_ready(call: types.CallbackQuery, callback_data: ImageGeneration, state: FSMContext) -> None:
|
||||
"""
|
||||
Query, what shows menu for image size to generate in
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:param state:
|
||||
:return:
|
||||
"""
|
||||
if call.from_user.id != callback_data.user_id:
|
||||
return
|
||||
await state.update_data(set_size=callback_data.size)
|
||||
await state.set_state(GeneratingImages.ready_to_generate)
|
||||
await call.message.edit_text(f"Вы выбрали {callback_data.category} для генерации изображений в размере {callback_data.size}.\n"
|
||||
"Напишите /cancel для отмены",
|
||||
reply_markup=delete_keyboard(admin_id=call.from_user.id))
|
||||
|
|
@ -1,67 +0,0 @@
|
|||
import logging
|
||||
|
||||
from aiogram import types
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
|
||||
from bozenka.instances.telegram.utils.callbacks_factory import UnmuteData, MuteData
|
||||
from aiogram.enums import ChatMemberStatus
|
||||
|
||||
from bozenka.instances.telegram.utils.keyboards import ban_keyboard, unban_keyboard, mute_keyboard, unmute_keyboard
|
||||
from bozenka.instances.telegram.utils.simpler import SolutionSimpler
|
||||
|
||||
|
||||
async def inline_mute(call: types.CallbackQuery, callback_data: MuteData, session_maker: async_sessionmaker) -> None:
|
||||
"""
|
||||
Query, what mutes users after callback
|
||||
:param call: CallBackQuery telegram object
|
||||
:param callback_data: BanData object
|
||||
:param session_maker: AsyncSessionmaker object
|
||||
:return:
|
||||
"""
|
||||
clicked_user = await call.message.chat.get_member(call.from_user.id)
|
||||
muted_user = await call.message.chat.get_member(int(callback_data.user_id_mute))
|
||||
|
||||
if call.from_user.id != callback_data.user_id_clicked \
|
||||
and clicked_user.status not in [ChatMemberStatus.ADMINISTRATOR, ChatMemberStatus.CREATOR]:
|
||||
return
|
||||
await SolutionSimpler.inline_mute_user(call=call, data=callback_data, session=session_maker)
|
||||
|
||||
if not muted_user.can_send_messages and muted_user.status == ChatMemberStatus.RESTRICTED:
|
||||
await call.answer("Уже замучен ✅")
|
||||
else:
|
||||
await call.answer("Успешно замучен ✅")
|
||||
|
||||
await call.message.edit_text(
|
||||
"Удача ✅\n"
|
||||
f"{muted_user.user.mention_html('Этот пользователь')} был замучен {call.from_user.mention_html('этим пользователем')}.",
|
||||
reply_markup=mute_keyboard(admin_id=call.from_user.id, mute_id=callback_data.user_id_mute)
|
||||
)
|
||||
logging.log(msg=f"Banned user @{muted_user.user.full_name} user_id=f{muted_user.user.id}", level=logging.INFO)
|
||||
|
||||
|
||||
async def inline_unmute(call: types.CallbackQuery, callback_data: UnmuteData, session_maker: async_sessionmaker) -> None:
|
||||
"""
|
||||
Query, what unbannes users after callback
|
||||
:param call: CallBackQuery telegram object
|
||||
:param callback_data: UnbanData object
|
||||
:param session_maker: AsyncSessionmaker object
|
||||
:return:
|
||||
"""
|
||||
clicked_user = await call.message.chat.get_member(call.from_user.id)
|
||||
unmuted_user = await call.message.chat.get_member(int(callback_data.user_id_unmute))
|
||||
if call.from_user.id != callback_data.user_id_clicked \
|
||||
and clicked_user.status not in [ChatMemberStatus.ADMINISTRATOR, ChatMemberStatus.CREATOR]:
|
||||
return
|
||||
|
||||
await SolutionSimpler.inline_unmute_user(call=call, data=callback_data, session=session_maker)
|
||||
|
||||
if unmuted_user.can_send_messages or unmuted_user.status == ChatMemberStatus.RESTRICTED:
|
||||
await call.answer("Уже размучен ✅")
|
||||
else:
|
||||
await call.answer("Успешно размучен ✅")
|
||||
await call.message.edit_text(
|
||||
"Удача ✅\n"
|
||||
f"{unmuted_user.user.mention_html('Этот пользователь')} был размучен {call.from_user.mention_html('этим пользователем')}.",
|
||||
reply_markup=unmute_keyboard(admin_id=call.from_user.id, unmute_id=unmuted_user.user.id)
|
||||
)
|
||||
logging.log(msg=f"Unbanned user @{unmuted_user.user.full_name} user_id=f{unmuted_user.user.id}", level=logging.INFO)
|
|
@ -1,36 +0,0 @@
|
|||
from aiogram import types
|
||||
|
||||
from bozenka.instances.telegram.utils.callbacks_factory import PinMsg, UnpinMsg
|
||||
from bozenka.instances.telegram.utils.keyboards import unpin_msg_keyboard, pin_msg_keyboard
|
||||
|
||||
|
||||
async def inline_pin_msg(call: types.CallbackQuery, callback_data: PinMsg) -> None:
|
||||
"""
|
||||
Query, what pins message
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
if callback_data.user_id == call.from_user.id:
|
||||
return
|
||||
|
||||
await call.message.chat.pin_message(message_id=callback_data.msg_id)
|
||||
await call.message.edit_text("Удача ✅\n"
|
||||
"Сообщение было закреплено 📌",
|
||||
reply_markup=pin_msg_keyboard(user_id=call.from_user.id, msg_id=callback_data.msg_id))
|
||||
|
||||
|
||||
async def inline_unpin_msg(call: types.CallbackQuery, callback_data: UnpinMsg) -> None:
|
||||
"""
|
||||
Query, what unpins message
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
if callback_data.user_id == call.from_user.id:
|
||||
return
|
||||
|
||||
await call.message.chat.pin_message(message_id=callback_data.msg_id)
|
||||
await call.message.edit_text("Удача ✅\n"
|
||||
"Сообщение было откреплено 📌",
|
||||
reply_markup=unpin_msg_keyboard(user_id=call.from_user.id, msg_id=callback_data.msg_id))
|
|
@ -1,24 +0,0 @@
|
|||
import logging
|
||||
|
||||
from aiogram import types
|
||||
|
||||
from bozenka.instances.telegram.utils.callbacks_factory import RevokeCallbackData
|
||||
from aiogram.enums import ChatMemberStatus
|
||||
|
||||
from bozenka.instances.telegram.utils.simpler import ru_cmds
|
||||
|
||||
|
||||
async def inline_revoke(call: types.CallbackQuery, callback_data: RevokeCallbackData):
|
||||
"""
|
||||
Revokes invite link
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
user_clicked = await call.message.chat.get_member(call.from_user.id)
|
||||
if callback_data.admin_id == call.from_user.id or user_clicked.status == ChatMemberStatus.ADMINISTRATOR or user_clicked.status == ChatMemberStatus.CREATOR:
|
||||
logging.log(msg=f"Revoking link for user_id={call.from_user.id}",
|
||||
level=logging.INFO)
|
||||
await call.message.chat.revoke_invite_link(invite_link="https://" + str(callback_data.link))
|
||||
await call.answer("Удача ✅")
|
||||
await call.message.delete()
|
|
@ -1,73 +0,0 @@
|
|||
from aiogram.types import CallbackQuery, Message
|
||||
from sqlalchemy import select, Update
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
|
||||
from bozenka.database.tables.telegram import TelegramChatSettings, get_chat_config_value
|
||||
from bozenka.instances.telegram.utils.callbacks_factory import SetupCategory, SetupFeature, SetupAction
|
||||
from bozenka.instances.telegram.utils.keyboards import setup_category_keyboard, setup_feature_keyboard
|
||||
from bozenka.instances.telegram.utils.simpler import list_of_features
|
||||
|
||||
|
||||
async def inline_setup_category(call: CallbackQuery, callback_data: SetupCategory):
|
||||
"""
|
||||
Query, what shows list of features to enable.
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
await call.message.edit_text("Выберите настройку, которую хотите изменить",
|
||||
reply_markup=setup_category_keyboard(category=callback_data.category_name))
|
||||
|
||||
|
||||
async def inline_setup_category_back(call: CallbackQuery, callback_data: SetupAction):
|
||||
"""
|
||||
Query, what shows list of features to enable.
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
await call.message.edit_text("Выберите настройку, которую хотите изменить",
|
||||
reply_markup=setup_category_keyboard(category=callback_data.category_name))
|
||||
|
||||
|
||||
async def inline_edit_feature(call: CallbackQuery, callback_data: SetupFeature, session_maker: async_sessionmaker):
|
||||
"""
|
||||
Query, what shows menu to enable / disable feature
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:param session_maker:
|
||||
:return:
|
||||
"""
|
||||
is_enabled = await get_chat_config_value(
|
||||
chat_id=call.message.chat.id,
|
||||
session=session_maker,
|
||||
setting=list_of_features[callback_data.feature_category][callback_data.feature_index]
|
||||
)
|
||||
|
||||
await call.message.edit_text(
|
||||
list_of_features[callback_data.feature_category][callback_data.feature_index].description,
|
||||
reply_markup=await setup_feature_keyboard(category=callback_data.feature_category,
|
||||
index=callback_data.feature_index,
|
||||
is_enabled=is_enabled))
|
||||
|
||||
|
||||
async def inline_feature_edited(call: CallbackQuery, callback_data: SetupAction, session_maker: async_sessionmaker):
|
||||
"""
|
||||
Query, what shows menu to enable / disable feature
|
||||
after editing
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:param session_maker:
|
||||
:return:
|
||||
"""
|
||||
async with session_maker() as session:
|
||||
async with session.begin():
|
||||
await session.execute(Update(TelegramChatSettings)
|
||||
.values({list_of_features[callback_data.category_name][callback_data.feature_index].settings_name:
|
||||
callback_data.action == "enable"})
|
||||
.where(TelegramChatSettings.chat_id == call.message.chat.id))
|
||||
await call.message.edit_text(
|
||||
list_of_features[callback_data.category_name][callback_data.feature_index].description,
|
||||
reply_markup=await setup_feature_keyboard(category=callback_data.category_name,
|
||||
index=callback_data.feature_index,
|
||||
is_enabled=callback_data.action == "enable"))
|
|
@ -1,168 +0,0 @@
|
|||
import git
|
||||
|
||||
from aiogram.types import *
|
||||
|
||||
from bozenka.instances.telegram.utils.callbacks_factory import *
|
||||
from bozenka.instances.telegram.utils.keyboards import *
|
||||
from bozenka.instances.telegram.utils.simpler import list_of_features
|
||||
from bozenka.instances.version import is_updated, build
|
||||
|
||||
|
||||
async def inline_start(call: CallbackQuery):
|
||||
"""
|
||||
Query, what shows back menu of /start
|
||||
:param call:
|
||||
:return:
|
||||
"""
|
||||
await call.message.edit_text(
|
||||
"""
|
||||
Привет 👋
|
||||
Я - бозенька, бот с открытым исходным кодом, который поможет тебе в различных задачах.
|
||||
|
||||
Вот что ты можешь сделать с помощью меню:
|
||||
• Добавить в чат: добавляет меня в групповой чат, чтобы я мог выполнять свои функции внутри него.
|
||||
• Функционал: показывает список доступных функций и команд, которые я могу выполнить.
|
||||
• О разработчиках: предоставляет информацию о команде разработчиков, которые создали и поддерживают этого бота.
|
||||
• О запущенном экземпляре: выводит информацию о текущей версии и состоянии запущенного экземпляра бота.
|
||||
• Начать диалог с ИИ: позволяет начать диалог с искусственным интеллектом, который может отвечать на вопросы и предоставлять информацию.
|
||||
• Генерация изображений: позволяет сгенерировать изображения на основе заданных параметров и промта
|
||||
|
||||
Вот нужные ссылки обо мне:
|
||||
• <a href='https://t.me/bozodevelopment'>Канал с новостями об разработке</a>
|
||||
• <a href='https://github.com/kittyneverdies/bozenka/'>Исходный код на Github</a>
|
||||
|
||||
Чтобы воспользоваться какой-либо функцией, просто нажми на соответствующую кнопку ниже.
|
||||
Если у тебя возникнут вопросы или проблемы, не стесняйся обратиться к команде разработчиков или написать в обсуждении телеграм канала.
|
||||
Удачного использования!
|
||||
""",
|
||||
reply_markup=start_keyboard(),
|
||||
disable_web_page_preview=True
|
||||
)
|
||||
|
||||
|
||||
async def inline_start_chatbot(call: CallbackQuery):
|
||||
"""
|
||||
Query, what shows list of Categories, avaible to use as chatbot
|
||||
:param call:
|
||||
:return:
|
||||
"""
|
||||
await call.message.edit_text("Пожалуста, выберите сервиc / библиотеку, через которую вы будете общаться",
|
||||
reply_markup=gpt_categories_keyboard
|
||||
(user_id=call.from_user.id))
|
||||
|
||||
|
||||
async def inline_help(call: CallbackQuery):
|
||||
"""
|
||||
Query, what shows information about bozenka and it's development
|
||||
:param call:
|
||||
:return:
|
||||
"""
|
||||
await call.message.edit_text("Выберите категорию, по которой нужна помощь:",
|
||||
reply_markup=help_keyboard())
|
||||
|
||||
|
||||
async def inline_about_developers(call: CallbackQuery):
|
||||
"""
|
||||
Query, what shows information about bozenka and it's development
|
||||
:param call:
|
||||
:return:
|
||||
"""
|
||||
kb = InlineKeyboardMarkup(inline_keyboard=[[
|
||||
InlineKeyboardButton(text="Вернуться 🔙", callback_data="back")
|
||||
]])
|
||||
await call.message.edit_text("""
|
||||
Бозенька - это мультифункциональный (в будущем кроссплатформенный) бот.\n
|
||||
Он умеет работать с групповыми чатами и готовыми нейронными сетями для генерации текста и изображений.
|
||||
Бозенька разрабатывается коммандой, которая состоит на данный момент из одного человека.\n
|
||||
Исходный код проекта\n
|
||||
Исходный код находится под лицензией GPL-3.0, исходный код проекта можно посмотреть всегда <a href="https://github.com/kittyneverdies/bozenka/">здесь</a>
|
||||
Канал с новостями разработки находится <a href="https://t.me/bozodevelopment">здесь</a>
|
||||
""", reply_markup=kb, disable_web_page_preview=True)
|
||||
|
||||
|
||||
async def inline_about_instance(call: CallbackQuery):
|
||||
"""
|
||||
Query, what shows information about runned instance
|
||||
:param call:
|
||||
:return:
|
||||
"""
|
||||
kb = InlineKeyboardMarkup(inline_keyboard=[[
|
||||
InlineKeyboardButton(text="Вернуться 🔙", callback_data="back")
|
||||
]])
|
||||
me = await call.message.bot.get_me()
|
||||
update_status = {False: "требуется обновление бота 🔼",
|
||||
True: "обновление не требуется, последняя версия ✅"}
|
||||
await call.message.edit_text(
|
||||
f"Информация об данном запущенном экземпляре бозеньки:\n"
|
||||
f"Аккаунт бота: {me.mention_html()}\n"
|
||||
f"Запущенная версия бота <code>{build}</code>\n",
|
||||
f"Нужно ли обновление: {update_status[is_updated]}",
|
||||
reply_markup=kb)
|
||||
|
||||
|
||||
async def inline_add_to_chat(call: CallbackQuery):
|
||||
"""
|
||||
Query, what shows a link to add bozenka into user chat
|
||||
:param call:
|
||||
:return:
|
||||
"""
|
||||
# Getting bot
|
||||
me = await call.message.bot.me()
|
||||
|
||||
# Generating special keyboard
|
||||
kb = InlineKeyboardBuilder()
|
||||
kb.button(text="Добавить в ваш груповой чат 🔌",
|
||||
url="https://t.me/"
|
||||
f"{me.username}?"
|
||||
"startgroup&"
|
||||
"admin=promote_members+delete_messages+restrict_members+invite_users+pin_messages+manage_video_chats")
|
||||
kb.row(InlineKeyboardButton(text="Вернуться 🔙", callback_data="back"))
|
||||
|
||||
# Answering
|
||||
await call.message.edit_text("Чтобы добавить бозеньку в ваш групповой чат, нажмите на кнопку под сообщением:",
|
||||
reply_markup=kb.as_markup())
|
||||
|
||||
|
||||
async def inline_help_features(call: CallbackQuery, callback_data: HelpCategory):
|
||||
"""
|
||||
Query, what shows list of features to get support.
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
await call.message.edit_text("Выберите функцию, по которой нужна помощь",
|
||||
reply_markup=help_category_keyboard(category=callback_data.category_name))
|
||||
|
||||
|
||||
async def inline_back_help_features(call: CallbackQuery, callback_data: HelpBackCategory):
|
||||
"""
|
||||
Query, what shows list of features to get support.
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
await call.message.edit_text("Выберите функцию, по которой нужна помощь",
|
||||
reply_markup=help_category_keyboard(category=callback_data.back_to_category))
|
||||
|
||||
|
||||
async def inline_back_help_categories(call: CallbackQuery, callback_data: HelpBack):
|
||||
"""
|
||||
Query, what shows list of features to get support back.
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
await call.message.edit_text("Выберите категорию, по которой нужна помощь:",
|
||||
reply_markup=help_keyboard())
|
||||
|
||||
|
||||
async def inline_help_feature(call: CallbackQuery, callback_data: HelpFeature):
|
||||
"""
|
||||
Query, what shows list of features to get support.
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
await call.message.edit_text(
|
||||
list_of_features[callback_data.feature_category][callback_data.feature_index].description,
|
||||
reply_markup=help_feature_keyboard(category=callback_data.feature_category))
|
|
@ -1,358 +0,0 @@
|
|||
import logging
|
||||
|
||||
from aiogram import types
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from gpt4all import GPT4All
|
||||
|
||||
from bozenka.instances.telegram.utils.simpler.fsm_states import *
|
||||
|
||||
# Callbacks for GPT
|
||||
from bozenka.instances.telegram.utils.callbacks_factory import (
|
||||
GptCategory,
|
||||
Gpt4FreeProvider,
|
||||
Gpt4freeResult,
|
||||
Gpt4FreeProviderPage,
|
||||
Gpt4FreeProvsModelPage, GptStop, GptBackMenu, Gpt4AllModel, Gpt4AllSelect, Gpt4FreeCategory, Gpt4FreeModelPage,
|
||||
Gpt4FreeModel
|
||||
)
|
||||
# Keyboards for messages
|
||||
from bozenka.instances.telegram.utils.keyboards import (
|
||||
gpt4free_models_by_provider_keyboard,
|
||||
gpt4free_providers_keyboard,
|
||||
delete_keyboard, gpt_categories_keyboard, generate_gpt4all_page, gpt4all_model_menu, gpt4free_categories_keyboard,
|
||||
gpt4free_models_keyboard
|
||||
)
|
||||
# Simpler utlilities
|
||||
from bozenka.instances.telegram.utils.simpler import (
|
||||
AnsweringGPT4Free,
|
||||
AnsweringGpt4All,
|
||||
)
|
||||
|
||||
|
||||
async def inline_start_gpt(call: types.CallbackQuery, callback_data: GptBackMenu, state: FSMContext) -> None:
|
||||
"""
|
||||
Query, what shows when clicking on button in /start menu
|
||||
:param call:
|
||||
:param state:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
if call.from_user.id != callback_data.user_id:
|
||||
return
|
||||
await call.message.edit_text("Пожалуста, выберите сервис для ИИ.",
|
||||
reply_markup=gpt_categories_keyboard(user_id=call.from_user.id))
|
||||
|
||||
|
||||
async def inline_g4f_providers(call: types.CallbackQuery, callback_data: Gpt4FreeCategory, state: FSMContext) -> None:
|
||||
"""
|
||||
Query, what creating providers selecting menu.
|
||||
:param state:
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
if call.from_user.id != callback_data.user_id:
|
||||
return
|
||||
|
||||
logging.log(msg=f"Selected gpt4free category by user_id={call.from_user.id}",
|
||||
level=logging.INFO)
|
||||
|
||||
await call.answer("Вы выбрали провайдеры 🤖")
|
||||
|
||||
await state.set_state(AnsweringGPT4Free.set_provider)
|
||||
await call.message.edit_text("Выберите пожалуйста одного из провайдеров 👨💻",
|
||||
reply_markup=gpt4free_providers_keyboard(user_id=call.from_user.id, page=0))
|
||||
|
||||
|
||||
async def inline_g4f_models(call: types.CallbackQuery, callback_data: GptCategory, state: FSMContext) -> None:
|
||||
"""
|
||||
Query, what creating models selecting menu
|
||||
:param state:
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
if call.from_user.id != callback_data.user_id:
|
||||
return
|
||||
|
||||
await state.set_state(AnsweringGPT4Free.set_model)
|
||||
|
||||
await call.answer("Вы выбрали модели 🤖")
|
||||
|
||||
await call.message.edit_text("Выберите модель, с которой будете общаться 🤖",
|
||||
reply_markup=gpt4free_models_keyboard(user_id=call.from_user.id, page=0))
|
||||
|
||||
|
||||
async def inline_g4f_model_select(call: types.CallbackQuery, callback_data: Gpt4FreeModel, state: FSMContext):
|
||||
"""
|
||||
Query, what ending model selecting
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:param state:
|
||||
:return:
|
||||
"""
|
||||
if call.from_user.id != callback_data.user_id:
|
||||
return
|
||||
|
||||
await state.update_data(set_model=callback_data.model)
|
||||
await state.set_state(AnsweringGPT4Free.ready_to_answer)
|
||||
|
||||
await call.answer("Вы можете начать общаться 🤖")
|
||||
|
||||
await call.message.edit_text("Удача ✅\n"
|
||||
"Вы теперь можете спокойно вести диалог 🤖\n"
|
||||
f"Вы выбрали модель <b>{callback_data.model}</b>👾\n"
|
||||
"Чтобы прекратить общение, используйте /cancel ", reply_markup=delete_keyboard(admin_id=call.from_user.id))
|
||||
|
||||
|
||||
async def inline_g4f_next_models(call: types.CallbackQuery, callback_data: Gpt4FreeModelPage, state: FSMContext) -> None:
|
||||
"""
|
||||
Query, what creating models selecting menu
|
||||
:param state:
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
if call.from_user.id != callback_data.user_id:
|
||||
return
|
||||
|
||||
await call.answer(f"Вы перелистнули на страницу {callback_data.page + 1}📄")
|
||||
|
||||
await call.message.edit_text("Выберите модель, с которой будете общаться 🤖",
|
||||
reply_markup=gpt4free_models_keyboard(user_id=call.from_user.id, page=callback_data.page))
|
||||
|
||||
|
||||
async def inline_g4f_categories(call: types.CallbackQuery, callback_data: GptCategory, state: FSMContext) -> None:
|
||||
"""
|
||||
Query, what creating providers selecting menu.
|
||||
:param state:
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
if call.from_user.id != callback_data.user_id:
|
||||
return
|
||||
|
||||
logging.log(msg=f"Selected gpt4free category by user_id={call.from_user.id}",
|
||||
level=logging.INFO)
|
||||
|
||||
await state.update_data(set_category=callback_data.category)
|
||||
await call.answer("Вы выбрали Gpt4Free 🤖")
|
||||
await call.message.edit_text("Выберите, по какому пункту мы будем вести диалог с нейронной сети 🤖",
|
||||
reply_markup=gpt4free_categories_keyboard(user_id=call.from_user.id))
|
||||
await call.answer("Выберите, по какому пункту мы будем вести диалог с нейронной сети 🤖")
|
||||
|
||||
|
||||
async def inline_g4f_providers_back(call: types.CallbackQuery, callback_data: GptBackMenu, state: FSMContext) -> None:
|
||||
"""
|
||||
Query, what creating providers selecting menu.
|
||||
:param state:
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
if call.from_user.id != callback_data.user_id:
|
||||
return
|
||||
|
||||
logging.log(msg=f"Back to providers menu by user_id={call.from_user.id}",
|
||||
level=logging.INFO)
|
||||
await state.set_state(AnsweringGPT4Free.set_provider)
|
||||
|
||||
await call.message.edit_text("Выберите пожалуйста одного из провайдеров 👨💻",
|
||||
reply_markup=gpt4free_providers_keyboard(page=0, user_id=callback_data.user_id))
|
||||
await call.answer("Выберите пожалуйста одного из провайдеров 👨💻")
|
||||
|
||||
|
||||
async def inline_g4f_provider_models(call: types.CallbackQuery, callback_data: Gpt4FreeProvider, state: FSMContext) -> None:
|
||||
"""
|
||||
Query, what creating models selecting menu.
|
||||
:param state:
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
if call.from_user.id != callback_data.user_id:
|
||||
return
|
||||
|
||||
logging.log(msg=f"Selected gpt4free provider {callback_data.provider} by user_id={call.from_user.id}",
|
||||
level=logging.INFO)
|
||||
|
||||
await state.update_data(set_provider=callback_data.provider)
|
||||
await state.set_state(AnsweringGPT4Free.set_model)
|
||||
|
||||
await call.message.edit_text("Выберите пожалуйста модель ИИ 👾", reply_markup=gpt4free_models_by_provider_keyboard(
|
||||
user_id=callback_data.user_id,
|
||||
provider=callback_data.provider,
|
||||
page=0
|
||||
))
|
||||
await call.answer("Выберите пожалуйста модель ИИ 👾")
|
||||
|
||||
|
||||
async def inline_g4f_ready(call: types.CallbackQuery, callback_data: Gpt4freeResult, state: FSMContext) -> None:
|
||||
"""
|
||||
Query, what says about getting ready to questions for ChatGPT from Gpt4Free.
|
||||
:param state:
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
if call.from_user.id != callback_data.user_id:
|
||||
return
|
||||
|
||||
logging.log(msg=f"Selected gpt4free model {callback_data.model} by user_id={call.from_user.id}",
|
||||
level=logging.INFO)
|
||||
|
||||
await state.update_data(set_model=callback_data.model)
|
||||
await state.set_state(AnsweringGPT4Free.ready_to_answer)
|
||||
|
||||
logging.log(msg=f"Loaded GPT answering status for user_id={call.from_user.id}",
|
||||
level=logging.INFO)
|
||||
|
||||
await call.message.edit_text("Удача ✅\n"
|
||||
"Вы теперь можете спокойно вести диалог 🤖\n"
|
||||
f"Вы выбрали модель <b>{callback_data.model}</b>👾, от провайдера <b>{callback_data.provider}</b>👨💻\n"
|
||||
"Чтобы прекратить общение, используйте /cancel ",
|
||||
reply_markup=delete_keyboard(admin_id=callback_data.user_id))
|
||||
await call.answer("Вы теперь можете спокойно вести диалог 🤖")
|
||||
|
||||
|
||||
async def inline_g4a(call: types.CallbackQuery, callback_data: GptCategory, state: FSMContext) -> None:
|
||||
"""
|
||||
Query, what shows list for gpt4all models
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:param state:
|
||||
:return:
|
||||
"""
|
||||
if callback_data.user_id != call.from_user.id:
|
||||
return
|
||||
await state.set_state(AnsweringGpt4All.set_model)
|
||||
await call.message.edit_text("Выберите пожалуйста модель ИИ 👾",
|
||||
reply_markup=generate_gpt4all_page(user_id=call.from_user.id))
|
||||
|
||||
|
||||
async def inline_g4a_back(call: types.CallbackQuery, callback_data: GptCategory, state: FSMContext) -> None:
|
||||
"""
|
||||
Query, what shows list for gpt4all models back
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:param state:
|
||||
:return:
|
||||
"""
|
||||
if callback_data.user_id != call.from_user.id:
|
||||
return
|
||||
await state.set_state(AnsweringGpt4All.set_model)
|
||||
await call.message.edit_text("Выберите пожалуйста модель ИИ 👾",
|
||||
reply_markup=generate_gpt4all_page(user_id=call.from_user.id))
|
||||
|
||||
|
||||
async def inline_g4a_model(call: types.CallbackQuery, callback_data: Gpt4AllModel, state: FSMContext) -> None:
|
||||
"""
|
||||
Query, what show information about clicked gpt4all model from list
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:param state:
|
||||
:return:
|
||||
"""
|
||||
if callback_data.user_id != call.from_user.id:
|
||||
return
|
||||
models = GPT4All.list_models()
|
||||
name = models[callback_data.index]['name']
|
||||
await call.message.edit_text(f"{name}\n"
|
||||
f"Обученно на основе {models[callback_data.index]['parameters']} строк 👨💻",
|
||||
reply_markup=gpt4all_model_menu(user_id=call.from_user.id, index=callback_data.index))
|
||||
|
||||
|
||||
async def inline_g4a_select_model(call: types.CallbackQuery, callback_data: Gpt4AllSelect, state: FSMContext) -> None:
|
||||
"""
|
||||
Query, what says about getting ready for question for Gpt4All model
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:param state:
|
||||
:return:
|
||||
"""
|
||||
if callback_data.user_id != call.from_user.id:
|
||||
return
|
||||
await state.update_data(set_model=callback_data.index)
|
||||
await state.set_state(AnsweringGpt4All.ready_to_answer)
|
||||
models = GPT4All.list_models()
|
||||
|
||||
await call.message.edit_text("Удача ✅\n"
|
||||
"Вы теперь можете спокойно вести диалог 🤖\n"
|
||||
f"Вы выбрали модель <b>{models[callback_data.index]['name']}</b>👾 от Gpt4All\n"
|
||||
"Чтобы прекратить общение, используйте /cancel ",
|
||||
reply_markup=delete_keyboard(admin_id=callback_data.user_id))
|
||||
|
||||
|
||||
async def inline_next_g4f_providers(call: types.CallbackQuery, callback_data: Gpt4FreeProviderPage,
|
||||
state: FSMContext) -> None:
|
||||
"""
|
||||
Query, what generates a next page of providers for user
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:param state:
|
||||
:return:
|
||||
"""
|
||||
if call.from_user.id != callback_data.user_id:
|
||||
return
|
||||
logging.log(msg=f"Changed page to {str(callback_data.page + 1)} user_id={call.from_user.id}",
|
||||
level=logging.INFO)
|
||||
await call.message.edit_text(call.message.text,
|
||||
reply_markup=gpt4free_providers_keyboard(user_id=callback_data.user_id,
|
||||
page=callback_data.page))
|
||||
await call.answer(f"Вы перелистнули на страницу {callback_data.page + 1}📄")
|
||||
|
||||
|
||||
async def inline_next_g4f_models(call: types.CallbackQuery, callback_data: Gpt4FreeProvsModelPage,
|
||||
state: FSMContext) -> None:
|
||||
"""
|
||||
Query, what generates a next page of models for user.
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:param state:
|
||||
:return:
|
||||
"""
|
||||
if call.from_user.id != callback_data.user_id:
|
||||
return
|
||||
logging.log(msg=f"Changed page to {str(callback_data.page + 1)} user_id={call.from_user.id}",
|
||||
level=logging.INFO)
|
||||
await call.message.edit_text(call.message.text,
|
||||
reply_markup=gpt4free_models_by_provider_keyboard(
|
||||
user_id=callback_data.user_id,
|
||||
provider=callback_data.provider,
|
||||
page=callback_data.page
|
||||
))
|
||||
await call.answer(f"Вы перелистали на страницу {callback_data.page + 1}📄")
|
||||
|
||||
|
||||
async def inline_return_pages(call: types.CallbackQuery) -> None:
|
||||
"""
|
||||
Query, made for helping purposes.
|
||||
Shows current page.
|
||||
:param call:
|
||||
:return:
|
||||
"""
|
||||
logging.log(msg=f"Showed helping info for user_id={call.from_user.id}",
|
||||
level=logging.INFO)
|
||||
await call.answer("Здесь расположается текущая странница 📃")
|
||||
|
||||
|
||||
async def inline_stop_dialog(call: types.CallbackQuery, callback_data: GptStop, state: FSMContext) -> None:
|
||||
"""
|
||||
Query, what stops dialog
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:param state:
|
||||
"""
|
||||
# Checking user_id of user
|
||||
if callback_data.user_id != call.from_user.id:
|
||||
return
|
||||
# Clearing state
|
||||
await state.clear()
|
||||
# Answering something
|
||||
await call.answer("Хорошо ✅")
|
||||
if await state.get_state() == AnsweringGPT4Free.ready_to_answer or await state.get_state() == AnsweringGpt4All.answering:
|
||||
await call.message.edit_text(text=call.message.text + "\n\nДиалог остановлен ✅\n",
|
||||
reply_markup=delete_keyboard(admin_id=call.from_user.id))
|
||||
else:
|
||||
await call.message.delete()
|
|
@ -1,41 +0,0 @@
|
|||
from aiogram import types
|
||||
|
||||
from bozenka.instances.telegram.utils.callbacks_factory import CloseThread, OpenThread
|
||||
from bozenka.instances.telegram.utils.keyboards import open_thread_keyboard, close_thread_keyboard, delete_keyboard
|
||||
from bozenka.instances.telegram.utils.simpler import SolutionSimpler
|
||||
|
||||
|
||||
async def inline_close_thread(call: types.CallbackQuery, callback_data: CloseThread) -> None:
|
||||
"""
|
||||
Query, what close thread
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
|
||||
if callback_data.user_id != call.from_user.id or not call.message.chat.is_forum:
|
||||
return
|
||||
config = await SolutionSimpler.close_topic(msg=call.message, call=call)
|
||||
await call.message.edit_text(
|
||||
config[0],
|
||||
reply_markup=close_thread_keyboard(user_id=call.from_user.id) if config[1] else
|
||||
delete_keyboard(admin_id=call.from_user.id)
|
||||
)
|
||||
|
||||
|
||||
async def inline_open_thread(call: types.CallbackQuery, callback_data: OpenThread) -> None:
|
||||
"""
|
||||
Query, what opens thread
|
||||
:param call:
|
||||
:param callback_data:
|
||||
:return:
|
||||
"""
|
||||
|
||||
if callback_data.user_id != call.from_user.id or not call.message.chat.is_forum:
|
||||
return
|
||||
config = await SolutionSimpler.open_topic(msg=call.message, call=call)
|
||||
await call.message.edit_text(
|
||||
config[0],
|
||||
reply_markup=open_thread_keyboard(user_id=call.from_user.id) if config[1] else
|
||||
delete_keyboard(admin_id=call.from_user.id)
|
||||
)
|
Loading…
Reference in a new issue