# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2021 The Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see .
# █ █ ▀ █▄▀ ▄▀█ █▀█ ▀
# █▀█ █ █ █ █▀█ █▀▄ █
# © Copyright 2022
# https://t.me/hikariatama
#
# 🔒 Licensed under the GNU AGPLv3
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
import os
import telethon
from telethon.tl.types import Message
from telethon.extensions.html import CUSTOM_EMOJIS
from .. import loader, main, translations, utils, version
from ..inline.types import InlineCall
@loader.tds
class CoreMod(loader.Module):
"""Control core userbot settings"""
strings = {
"name": "Settings",
"too_many_args": (
"🚫 Too many args"
),
"blacklisted": (
'👍 Chat {} blacklisted'
" from userbot"
),
"unblacklisted": (
'👍 Chat {}'
" unblacklisted from userbot"
),
"user_blacklisted": (
'👍 User {} blacklisted'
" from userbot"
),
"user_unblacklisted": (
'👍 User {}'
" unblacklisted from userbot"
),
"what_prefix": "❓ What should the prefix be set to?",
"prefix_incorrect": (
"🚫 Prefix must be one"
" symbol in length"
),
"prefix_set": (
'👍 Command prefix'
" updated. Type {newprefix}setprefix {oldprefix}
to"
" change it back"
),
"alias_created": (
'👍 Alias created.'
" Access it with {}
"
),
"aliases": "🔗 Aliases:\n",
"no_command": (
"🚫 Command"
" {}
does not exist"
),
"alias_args": (
"🚫 You must provide a"
" command and the alias for it"
),
"delalias_args": (
"🚫 You must provide the"
" alias name"
),
"alias_removed": (
'👍 Alias'
" {}
removed."
),
"no_alias": (
"🚫 Alias"
" {}
does not exist"
),
"db_cleared": (
'👍 Database cleared'
),
"hikka": (
"{}\n\n🧐 Version:"
" {}.{}.{}\n🧱 Build:"
" {}\n\n⚙️"
" Hikka-TL: {}\n\n⌨️ Developer:"
" t.me/hikariatama"
),
"check_url": (
"🚫 You need to specify"
" valid url containing a langpack"
),
"lang_saved": "{} Language saved!",
"pack_saved": (
'👍 Translate pack'
" saved!"
),
"incorrect_language": (
"🚫 Incorrect language"
" specified"
),
"lang_removed": (
'👍 Translations reset'
" to default ones"
),
"check_pack": (
"🚫 Invalid pack format"
" in url"
),
"confirm_cleardb": "⚠️ Are you sure, that you want to clear database?",
"cleardb_confirm": "🗑 Clear database",
"cancel": "🚫 Cancel",
"who_to_blacklist": (
"❓ Who to blacklist?"
),
"who_to_unblacklist": (
"❓ Who to"
" unblacklist?"
),
"unstable": (
"\n\n🙈 You are using an"
" unstable branch {}
!"
),
}
strings_ru = {
"too_many_args": (
"🚫 Слишком много"
" аргументов"
),
"blacklisted": (
'👍 Чат {} добавлен в'
" черный список юзербота"
),
"unblacklisted": (
'👍 Чат {} удален из'
" черного списка юзербота"
),
"user_blacklisted": (
'👍 Пользователь {}'
" добавлен в черный список юзербота"
),
"user_unblacklisted": (
'👍 Пользователь {}'
" удален из черного списка юзербота"
),
"what_prefix": "❓ А какой префикс ставить то?",
"prefix_incorrect": (
"🚫 Префикс должен"
" состоять только из одного символа"
),
"prefix_set": (
'👍 Префикс обновлен.'
" Чтобы вернуть его, используй {newprefix}setprefix"
" {oldprefix}
"
),
"alias_created": (
'👍 Алиас создан.'
" Используй его через {}
"
),
"aliases": "🔗 Алиасы:\n",
"no_command": (
"🚫 Команда"
" {}
не существует"
),
"alias_args": (
"🚫 Требуется ввести"
" команду и алиас для нее"
),
"delalias_args": (
"🚫 Требуется имя"
" алиаса"
),
"alias_removed": (
'👍 Алиас'
" {}
удален."
),
"no_alias": (
"🚫 Алиас"
" {}
не существует"
),
"db_cleared": (
'👍 База очищена'
),
"hikka": (
"{}\n\n🧐 Версия:"
" {}.{}.{}\n🧱 Сборка:"
" {}\n\n⚙️"
" Hikka-TL: {}\n\n⌨️ Developer:"
" t.me/hikariatama"
),
"check_url": (
"🚫 Укажи правильную"
" ссылку, ведущую на пак с переводом"
),
"lang_saved": "{} Язык сохранен!",
"pack_saved": (
'👍 Пак перевода'
" сохранен!"
),
"incorrect_language": (
"🚫 Указан неверный"
" язык"
),
"lang_removed": (
'👍 Переводы'
" сброшены"
),
"check_pack": (
"🚫 По ссылке находится"
" неправильный пак"
),
"_cls_doc": "Управление базовыми настройками юзербота",
"confirm_cleardb": "⚠️ Вы уверены, что хотите сбросить базу данных?",
"cleardb_confirm": "🗑 Очистить базу",
"cancel": "🚫 Отмена",
"who_to_blacklist": (
"❓ Кого заблокировать"
" то?"
),
"who_to_unblacklist": (
"❓ Кого разблокировать"
" то?"
),
"unstable": (
"\n\n🙈 Ты используешь"
" нестабильную ветку {}
!"
),
}
async def blacklistcommon(self, message: Message):
args = utils.get_args(message)
if len(args) > 2:
await utils.answer(message, self.strings("too_many_args"))
return
chatid = None
module = None
if args:
try:
chatid = int(args[0])
except ValueError:
module = args[0]
if len(args) == 2:
module = args[1]
if chatid is None:
chatid = utils.get_chat_id(message)
module = self.allmodules.get_classname(module)
return f"{str(chatid)}.{module}" if module else chatid
@loader.command(ru_doc="Показать версию Hikka")
async def hikkacmd(self, message: Message):
"""Get Hikka version"""
await utils.answer(
message,
self.strings("hikka").format(
(
utils.get_platform_emoji()
+ (
"✌️✌️✌️✌️"
if "LAVHOST" in os.environ
else ""
)
)
if self._client.hikka_me.premium and CUSTOM_EMOJIS
else "🌘 Hikka userbot",
*version.__version__,
utils.get_commit_url(),
f"{telethon.__version__} #{telethon.tl.alltlobjects.LAYER}",
)
+ (
""
if version.branch == "master"
else self.strings("unstable").format(version.branch)
),
)
@loader.command(ru_doc="[чат] [модуль] - Отключить бота где-либо")
async def blacklist(self, message: Message):
"""[chat_id] [module] - Blacklist the bot from operating somewhere"""
chatid = await self.blacklistcommon(message)
self._db.set(
main.__name__,
"blacklist_chats",
self._db.get(main.__name__, "blacklist_chats", []) + [chatid],
)
await utils.answer(message, self.strings("blacklisted").format(chatid))
@loader.command(ru_doc="[чат] - Включить бота где-либо")
async def unblacklist(self, message: Message):
""" - Unblacklist the bot from operating somewhere"""
chatid = await self.blacklistcommon(message)
self._db.set(
main.__name__,
"blacklist_chats",
list(set(self._db.get(main.__name__, "blacklist_chats", [])) - {chatid}),
)
await utils.answer(message, self.strings("unblacklisted").format(chatid))
async def getuser(self, message: Message):
try:
return int(utils.get_args(message)[0])
except (ValueError, IndexError):
reply = await message.get_reply_message()
if reply:
return reply.sender_id
return message.to_id.user_id if message.is_private else False
@loader.command(ru_doc="[пользователь] - Запретить пользователю выполнять команды")
async def blacklistuser(self, message: Message):
"""[user_id] - Prevent this user from running any commands"""
user = await self.getuser(message)
if not user:
await utils.answer(message, self.strings("who_to_blacklist"))
return
self._db.set(
main.__name__,
"blacklist_users",
self._db.get(main.__name__, "blacklist_users", []) + [user],
)
await utils.answer(message, self.strings("user_blacklisted").format(user))
@loader.command(ru_doc="[пользователь] - Разрешить пользователю выполнять команды")
async def unblacklistuser(self, message: Message):
"""[user_id] - Allow this user to run permitted commands"""
user = await self.getuser(message)
if not user:
await utils.answer(message, self.strings("who_to_unblacklist"))
return
self._db.set(
main.__name__,
"blacklist_users",
list(set(self._db.get(main.__name__, "blacklist_users", [])) - {user}),
)
await utils.answer(
message,
self.strings("user_unblacklisted").format(user),
)
@loader.owner
@loader.command(ru_doc="<префикс> - Установить префикс команд")
async def setprefix(self, message: Message):
""" - Sets command prefix"""
args = utils.get_args_raw(message)
if not args:
await utils.answer(message, self.strings("what_prefix"))
return
if len(args) != 1:
await utils.answer(message, self.strings("prefix_incorrect"))
return
oldprefix = self.get_prefix()
self._db.set(main.__name__, "command_prefix", args)
await utils.answer(
message,
self.strings("prefix_set").format(
newprefix=utils.escape_html(args[0]),
oldprefix=utils.escape_html(oldprefix),
),
)
@loader.owner
@loader.command(ru_doc="Показать список алиасов")
async def aliases(self, message: Message):
"""Print all your aliases"""
aliases = self.allmodules.aliases
string = self.strings("aliases")
string += "\n".join(
[f"▫️ {i}
<- {y}" for i, y in aliases.items()]
)
await utils.answer(message, string)
@loader.owner
@loader.command(ru_doc="Установить алиас для команды")
async def addalias(self, message: Message):
"""Set an alias for a command"""
args = utils.get_args(message)
if len(args) != 2:
await utils.answer(message, self.strings("alias_args"))
return
alias, cmd = args
if self.allmodules.add_alias(alias, cmd):
self.set(
"aliases",
{
**self.get("aliases", {}),
alias: cmd,
},
)
await utils.answer(
message,
self.strings("alias_created").format(utils.escape_html(alias)),
)
else:
await utils.answer(
message,
self.strings("no_command").format(utils.escape_html(cmd)),
)
@loader.owner
@loader.command(ru_doc="Удалить алиас для команды")
async def delalias(self, message: Message):
"""Remove an alias for a command"""
args = utils.get_args(message)
if len(args) != 1:
await utils.answer(message, self.strings("delalias_args"))
return
alias = args[0]
removed = self.allmodules.remove_alias(alias)
if not removed:
await utils.answer(
message,
self.strings("no_alias").format(utils.escape_html(alias)),
)
return
current = self.get("aliases", {})
del current[alias]
self.set("aliases", current)
await utils.answer(
message,
self.strings("alias_removed").format(utils.escape_html(alias)),
)
@loader.command(ru_doc="[ссылка на пак] - Изменить внешний пак перевода")
async def dllangpackcmd(self, message: Message):
"""[link to a langpack | empty to remove] - Change Hikka translate pack (external)
"""
args = utils.get_args_raw(message)
if not args:
self._db.set(translations.__name__, "pack", False)
await self.translator.init()
await utils.answer(message, self.strings("lang_removed"))
return
if not utils.check_url(args):
await utils.answer(message, self.strings("check_url"))
return
self._db.set(translations.__name__, "pack", args)
success = await self.translator.init()
await utils.answer(
message, self.strings("pack_saved" if success else "check_pack")
)
@loader.command(ru_doc="[языки] - Изменить стандартный язык")
async def setlang(self, message: Message):
"""[languages in the order of priority] - Change default language"""
args = utils.get_args_raw(message)
if not args or any(len(i) != 2 for i in args.split(" ")):
await utils.answer(message, self.strings("incorrect_language"))
return
self._db.set(translations.__name__, "lang", args.lower())
await self.translator.init()
await utils.answer(
message,
self.strings("lang_saved").format(
"".join(
[
utils.get_lang_flag(
lang.lower() if lang.lower() != "en" else "gb"
)
for lang in args.lower().split(" ")
]
)
),
)
@loader.owner
@loader.command(ru_doc="Очистить базу данных")
async def cleardb(self, message: Message):
"""Clear the entire database, effectively performing a factory reset"""
await self.inline.form(
self.strings("confirm_cleardb"),
message,
reply_markup=[
{
"text": self.strings("cleardb_confirm"),
"callback": self._inline__cleardb,
},
{
"text": self.strings("cancel"),
"action": "close",
},
],
)
async def _inline__cleardb(self, call: InlineCall):
self._db.clear()
self._db.save()
await utils.answer(call, self.strings("db_cleared"))