# На модуль распространяется лицензия "GNU General Public License v3.0"
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @PyModule
# requires: toml
import os
from hikka import loader, utils
import pickle
from telethon.tl.types import Channel
import toml
# noinspection PyCallingNonCallable
@loader.tds
class IrisRP(loader.Module):
"""РП команды как в боте Ирис."""
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"action_decoration",
'normal | без стилей',
lambda: "Декорация для действия РП-команды",
validator=loader.validators.Choice(
[
"normal | без стилей",
"bold | полужирный",
"italic | курсив",
"underlined | подчёркнутый",
"strikethrough | зачёркнутый",
"spoiler | скрытый",
]
),
),
loader.ConfigValue(
"replica_decoration",
'normal | без стилей',
lambda: "Декорация для реплики РП-команды",
validator=loader.validators.Choice(
[
"normal | без стилей",
"bold | полужирный",
"italic | курсив",
"underlined | подчёркнутый",
"strikethrough | зачёркнутый",
"spoiler | скрытый",
]
),
),
loader.ConfigValue(
"speech_bubble",
'💬',
lambda: "Эмодзи речевого пузыря для «с репликой»",
validator=loader.validators.String()
)
)
strings = {'name': 'IrisRP'}
async def client_ready(self, client, db):
self.db = db
if not self.db.get("RPMod", "exlist", False):
self.db.set("RPMod", "exlist", [])
if not self.db.get("RPMod", "status", False):
self.db.get("RPMod", "status", 1)
if not self.db.get("RPMod", "rpcomands", False):
self.db.set("RPMod", "rpcomands", {})
if not self.db.get("RPMod", "rpemoji", False):
self.db.set("RPMod", "rpemoji", {})
if not self.db.get("RPMod", "nrpcommands", False):
if self.db.get("RPMod", "rpcomands", False):
commands_old = self.db.get("RPMod", "rpcomands")
emoji_old = self.db.get("RPMod", "rpemoji")
commands_new = {}
for key in commands_old:
try:
commands_new[key] = [commands_old[key], emoji_old[key]]
except KeyError:
commands_new[key] = [commands_old[key], '']
self.db.set("RPMod", "nrpcommands", commands_new)
else:
self.db.set("RPMod", "nrpcommands", {})
if not self.db.get("RPMod", "useraccept", False):
self.db.set("RPMod", "useraccept", {"chats": [], "users": []})
elif isinstance(type(self.db.get("RPMod", "useraccept")), list):
self.db.set(
"RPMod",
"useraccept",
{"chats": [], "users": self.db.get("RPMod", "useraccept")},
)
async def addrpcmd(self, message):
"""[команда (1-3 слова)] / [действие] / (эмодзи) - Создать РП команду."""
args = utils.get_args_raw(message)
dict_rp = self.db.get("RPMod", "nrpcommands", {})
if not args or not args.strip():
await utils.answer(message, "{key_rp} успешно добавлена"
if emoji_rp:
response += f" с эмодзи {emoji_rp}"
response += "."
await utils.answer(message, response)
except Exception as e:
await utils.answer(message, "{key_rp} успешно удалена.")
except KeyError:
await utils.answer(message, f"{key_rp} не найдена.")
async def rptogglecmd(self, message):
"""- Включить/Выключить РП команды."""
status = self.db.get("RPMod", "status")
if status == 1:
self.db.set("RPMod", "status", 2)
await utils.answer(message, "{i} - {com[i][0]} | {com[i][1]}"
else:
com_list += f"\n• {i} - {com[i][0]}"
await utils.answer(message, com_list)
async def rpbackcmd(self, message):
"""(all) - Сохранить или загрузить список РП команд. All используется для замены всех команд."""
commands = self.db.get("RPMod", "nrpcommands")
mes_id = message.to_id
me = await self.client.get_me()
file_name = f"IrisRP_{me.id}.toml"
reply = await message.get_reply_message()
args = utils.get_args_raw(message)
replace_commands = "all" in args
if not reply:
try:
await message.delete()
with open(file_name, "w") as f:
toml.dump(commands, f)
await message.client.send_file(mes_id, file_name)
os.remove(file_name)
except Exception as e:
await utils.answer(message, f"{e}")
else:
if not reply.document:
await utils.answer(message, "{e}")
async def rpacmd(self, message):
"""(ID/Reply) - Разрешить или запретить доступ к РП командам. Для подробностей напишите .rpa"""
reply = await message.get_reply_message()
args = utils.get_args_raw(message)
user_a = self.db.get("RPMod", "useraccept")
if not reply and not args and message.is_group:
chat = message.chat
if chat.id not in user_a["chats"]:
user_a["chats"].append(chat.id)
return await utils.answer(message, f"{chat_id})"
except:
sms += f"\n• {chat_id}"
else:
sms += "\n\n{user_id})"
except:
sms += f"\n• {user_id}"
else:
sms += "\n\n
\n" "ℹ Используйте:
.rpa в чате - для управления доступом чата.\n"
".rpa [ID] - для управления по ID.\n"
".rpa в ответ на сообщение - для управления пользователем.\n"
".rpa -l - чтобы показать список доступов."
)
async def watcher(self, message):
try:
status = self.db.get("RPMod", "status", 0)
commands = self.db.get("RPMod", "nrpcommands", {})
users_accept = self.db.get("RPMod", "useraccept", {"users": [], "chats": []})
if status != 1:
return
me_id = (await message.client.get_me()).id
if (message.sender_id not in users_accept["users"] and
message.sender_id != me_id and
message.chat_id not in users_accept["chats"]):
return
me = await message.client.get_entity(message.sender_id)
text = message.text or ""
lines = text.splitlines()
if not lines:
return
words = lines[0].split()
if not words:
return
found_command = None
for i in range(min(3, len(words)), 0, -1):
possible_command = " ".join(words[:i]).casefold()
if possible_command in commands:
found_command = possible_command
remaining_text = " ".join(words[i:]) if i < len(words) else ""
break
if not found_command:
return
if len(words) > 1 and words[-1].startswith("@"):
target_mention = words[-1][1:]
try:
if target_mention.isdigit():
user = await message.client.get_entity(int(target_mention))
else:
user = await message.client.get_entity(target_mention)
remaining_text = " ".join(words[len(found_command.split()):-1])
except:
reply = await message.get_reply_message()
if reply:
user = await message.client.get_entity(reply.sender_id)
else:
return
else:
reply = await message.get_reply_message()
if reply:
user = await message.client.get_entity(reply.sender_id)
else:
return
command = commands[found_command]
replica = ""
if len(lines) > 1:
replica = "\n".join(lines[1:])
action_decoration = self.config.get('action_decoration', '')
replica_decoration = self.config.get('replica_decoration', '')
bubble = self.config.get('speech_bubble', '💬')
s1 = {
'bold': ("", ""),
'italic': ("", ""),
'underline': ("", ""),
'strikethrough': ("