Added and updated repositories 2025-07-11 08:27:20

This commit is contained in:
github-actions[bot]
2025-07-11 08:27:20 +00:00
parent 35e8befc45
commit e328cd957a
320 changed files with 37419 additions and 33510 deletions

View File

@@ -1,216 +1,216 @@
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: AuroraAFK
# Author: dend1yy | Felix?
# Commands:
# .afk | .removestatus | .setstatus | .unafk
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/f35de08579b3bd2235bc4.jpg
__version__ = (1, 0, 3)
import datetime
import logging
import time
from telethon import types, functions # type: ignore
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class AuroraAFKMod(loader.Module):
"""Your personal assistant to while you are in AFK mode"""
strings = {
"name": "AuroraAFK",
"gone": "<b><emoji document_id=5287692511945437157>✅</emoji> You have successfully entered AFK mode!</b>",
"back": "<b><emoji document_id=5287692511945437157>✅</emoji> You have successfully exited AFK mode!</b>",
"afk": "<b><emoji document_id=5287613458777387650>😴</emoji> I'm currently in AFK\n<emoji document_id=5287737368583876982>🌀</emoji> Was online <code>{}</code> ago</b>",
"afk_reason": "<b><emoji document_id=5287613458777387650>😴</emoji> I'm currently in AFK\n<emoji document_id=5287737368583876982>🌀</emoji> Was online <code>{}</code> ago\n<emoji document_id=5445161912985724546>✏️</emoji> Reason: <i>{}</i></b>",
"status_added": "<b><emoji document_id=5285372392086976148>🦋</emoji> Status successfully set!</b>",
"status_removed": "<b><emoji document_id=5879896690210639947>🗑</emoji> Status successfully removed!</b>",
"no_user": "<b><emoji document_id=5287611315588707430>❌</emoji> Failed to get user information.</b>",
"no_previous_status": "<b><emoji document_id=5287740598399285194>😵‍💫</emoji> Previous nickname not found.</b>",
}
strings_ru = {
"gone": "<b><emoji document_id=5287692511945437157>✅</emoji> Вы успешно вошли в AFK режим!</b>",
"back": "<b><emoji document_id=5287692511945437157>✅</emoji> Вы успешно вышли из AFK режима!</b>",
"afk": "<b><emoji document_id=5287613458777387650>😴</emoji> Сейчас я нахожусь в AFK\n<emoji document_id=5287737368583876982>🌀</emoji> Был в сети <code>{}</code> назад</b>",
"afk_reason": "<b><emoji document_id=5287613458777387650>😴</emoji> Сейчас я нахожусь в AFK\n<emoji document_id=5287737368583876982>🌀</emoji> Был в сети <code>{}</code> назад\n<emoji document_id=5445161912985724546>✏️</emoji> Причина: <i>{}</i></b>",
"status_added": "<b><emoji document_id=5285372392086976148>🦋</emoji> Статус успешно установлен!</b>",
"status_removed": "<b><emoji document_id=5879896690210639947>🗑</emoji> Статус успешно удалён!</b>",
"no_user": "<b><emoji document_id=5287611315588707430>❌</emoji> Не удалось получить информацию о пользователе.</b>",
"no_previous_status": "<b><emoji document_id=5287740598399285194>😵‍💫</emoji> Предыдущий ник не найден.</b>",
}
strings_uz = {
"gone": "<b><emoji document_id=5287692511945437157>✅</emoji> AFK holatiga muvaffaqiyatli kirdingiz!</b>",
"back": "<b><emoji document_id=5287692511945437157>✅</emoji> AFK rejimidan muvaffaqiyatli chiqdingiz!</b>",
"afk": "<b><emoji document_id=5287613458777387650>😴</emoji> Hozir men AFK holatida\n<emoji document_id=5287737368583876982>🌀</emoji> <code>{}</code> avval onlayn bo'lgan</b>",
"afk_reason": "<b><emoji document_id=5287613458777387650>😴</emoji> Hozir men AFK holatida\n<emoji document_id=5287737368583876982>🌀</emoji> <code>{}</code> avval onlayn bo'lgan\n<emoji document_id=5445161912985724546>✏️</emoji> Sabab: <i>{}</i></b>",
"status_added": "<b><emoji document_id=5285372392086976148>🦋</emoji> Status muvaffaqiyatli o'rnatildi!</b>",
"status_removed": "<b><emoji document_id=5879896690210639947>🗑</emoji> Status muvaffaqiyatli olib tashlandi!</b>",
"no_user": "<b><emoji document_id=5287611315588707430>❌</emoji> Foydalanuvchi ma'lumotlari olishda xatolik.</b>",
"no_previous_status": "<b><emoji document_id=5287740598399285194>😵‍💫</emoji> Avvalgi nom topilmadi.</b>",
}
strings_de = {
"gone": "<b><emoji document_id=5287692511945437157>✅</emoji> Du hast den AFK-Modus erfolgreich aktiviert!</b>",
"back": "<b><emoji document_id=5287692511945437157>✅</emoji> Du hast den AFK-Modus erfolgreich deaktiviert!</b>",
"afk": "<b><emoji document_id=5287613458777387650>😴</emoji> Ich bin derzeit im AFK\n<emoji document_id=5287737368583876982>🌀</emoji> War vor <code>{}</code> online</b>",
"afk_reason": "<b><emoji document_id=5287613458777387650>😴</emoji> Ich bin derzeit im AFK\n<emoji document_id=5287737368583876982>🌀</emoji> War vor <code>{}</code> online\n<emoji document_id=5445161912985724546>✏️</emoji> Grund: <i>{}</i></b>",
"status_added": "<b><emoji document_id=5285372392086976148>🦋</emoji> Status erfolgreich gesetzt!</b>",
"status_removed": "<b><emoji document_id=5879896690210639947>🗑</emoji> Status erfolgreich entfernt!</b>",
"no_user": "<b><emoji document_id=5287611315588707430>❌</emoji> Benutzerinformationen konnten nicht abgerufen werden.</b>",
"no_previous_status": "<b><emoji document_id=5287740598399285194>😵‍💫</emoji> Vorheriger Spitzname nicht gefunden.</b>",
}
strings_es = {
"gone": "<b><emoji document_id=5287692511945437157>✅</emoji> ¡Has entrado correctamente en el modo AFK!</b>",
"back": "<b><emoji document_id=5287692511945437157>✅</emoji> ¡Has salido correctamente del modo AFK!</b>",
"afk": "<b><emoji document_id=5287613458777387650>😴</emoji> Actualmente estoy en AFK\n<emoji document_id=5287737368583876982>🌀</emoji> Estuve en línea hace <code>{}</code></b>",
"afk_reason": "<b><emoji document_id=5287613458777387650>😴</emoji> Actualmente estoy en AFK\n<emoji document_id=5287737368583876982>🌀</emoji> Estuve en línea hace <code>{}</code>\n<emoji document_id=5445161912985724546>✏️</emoji> Razón: <i>{}</i></b>",
"status_added": "<b><emoji document_id=5285372392086976148>🦋</emoji> ¡Estado establecido correctamente!</b>",
"status_removed": "<b><emoji document_id=5879896690210639947>🗑</emoji> ¡Estado eliminado correctamente!</b>",
"no_user": "<b><emoji document_id=5287611315588707430>❌</emoji> No se pudieron obtener las información del usuario.</b>",
"no_previous_status": "<b><emoji document_id=5287740598399285194>😵‍💫</emoji> Nombre de usuario anterior no encontrado.</b>",
}
async def client_ready(self, client, db):
self.client = client
self._db = db
self._me = await client.get_me()
@loader.command(
ru_doc="[reason] - Установить режим AFK",
uz_doc="[reason] - AFK holatini sozlash",
de_doc="[reason] - AFK-Modusstatus setzen",
es_doc="[reason] - Establecer estado de modo AFK"
)
async def afk(self, message):
"""[reason] - Set AFK mode status"""
if utils.get_args_raw(message):
self._db.set(__name__, "afk", utils.get_args_raw(message))
else:
self._db.set(__name__, "afk", True)
self._db.set(__name__, "gone", time.time())
self._db.set(__name__, "ratelimit", [])
await self.allmodules.log("afk", data=utils.get_args_raw(message) or None)
await utils.answer(message, self.strings("gone", message))
@loader.command(
ru_doc="Выйти из режима AFK",
uz_doc="AFK rejimidan chiqish",
de_doc="Verlassen des AFK-Modus",
es_doc="Salir del modo AFK"
)
async def unafk(self, message):
"""Exit AFK mode"""
self._db.set(__name__, "afk", False)
self._db.set(__name__, "gone", None)
self._db.set(__name__, "ratelimit", [])
await self.allmodules.log("unafk")
await utils.answer(message, self.strings("back", message))
@loader.command(
ru_doc="Установить статус AFK",
uz_doc="AFK holatini sozlash",
de_doc="Setzt den AFK-Status",
es_doc="Establece el estado AFK"
)
async def setstatus(self, message):
"""Set the AFK status"""
user = await utils.get_user(message)
if user:
current_last_name = user.last_name if user.last_name else ""
if " || AFK" in current_last_name:
await utils.answer(message, self.strings["status_added"].format(name=current_last_name))
return
new_last_name = current_last_name + " || AFK"
try:
await self.client(functions.account.UpdateProfileRequest(last_name=new_last_name))
await utils.answer(message, self.strings["status_added"].format(name=new_last_name))
except Exception as e:
await utils.answer(message, f"<b>Ошибка при добавлении статуса: {str(e)}</b>")
else:
await utils.answer(message, self.strings["no_user"])
@loader.command(
ru_doc="Удалить статус AFK",
uz_doc="AFK holatini o'chirish",
de_doc="Löscht den AFK-Status",
es_doc="Eliminar el estado AFK"
)
async def removestatus(self, message):
"""Удалить статус AFK."""
user = await utils.get_user(message)
if user:
current_last_name = user.last_name if user.last_name else ""
if " || AFK" in current_last_name:
try:
previous_first_name = user.first_name if user.first_name else ""
previous_last_name = current_last_name.replace(" || AFK", "")
await self.client(functions.account.UpdateProfileRequest(first_name=previous_first_name, last_name=previous_last_name))
await utils.answer(message, self.strings["status_removed"])
except Exception as e:
await utils.answer(message, f"<b>Ошибка при удалении статуса: {str(e)}</b>")
else:
await utils.answer(message, self.strings["no_previous_status"])
else:
await utils.answer(message, self.strings["no_user"])
async def watcher(self, message):
if not isinstance(message, types.Message):
return
if message.mentioned or getattr(message.to_id, "user_id", None) == self._me.id:
afk_state = self.get_afk()
if not afk_state:
return
logger.debug("tagged!")
ratelimit = self._db.get(__name__, "ratelimit", [])
if utils.get_chat_id(message) in ratelimit:
return
else:
self._db.setdefault(__name__, {}).setdefault("ratelimit", []).append(
utils.get_chat_id(message)
)
self._db.save()
user = await utils.get_user(message)
if user.is_self or user.bot or user.verified:
logger.debug("User is self, bot or verified.")
return
if self.get_afk() is False:
return
now = datetime.datetime.now().replace(microsecond=0)
gone = datetime.datetime.fromtimestamp(
self._db.get(__name__, "gone")
).replace(microsecond=0)
diff = now - gone
if afk_state is True:
ret = self.strings("afk", message).format(diff)
elif afk_state is not False:
ret = self.strings("afk_reason", message).format(diff, afk_state)
await utils.answer(message, ret, reply_to=message)
def get_afk(self):
return self._db.get(__name__, "afk", False)
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: AuroraAFK
# Author: dend1yy | Felix?
# Commands:
# .afk | .removestatus | .setstatus | .unafk
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/f35de08579b3bd2235bc4.jpg
__version__ = (1, 0, 3)
import datetime
import logging
import time
from telethon import types, functions # type: ignore
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class AuroraAFKMod(loader.Module):
"""Your personal assistant to while you are in AFK mode"""
strings = {
"name": "AuroraAFK",
"gone": "<b><emoji document_id=5287692511945437157>✅</emoji> You have successfully entered AFK mode!</b>",
"back": "<b><emoji document_id=5287692511945437157>✅</emoji> You have successfully exited AFK mode!</b>",
"afk": "<b><emoji document_id=5287613458777387650>😴</emoji> I'm currently in AFK\n<emoji document_id=5287737368583876982>🌀</emoji> Was online <code>{}</code> ago</b>",
"afk_reason": "<b><emoji document_id=5287613458777387650>😴</emoji> I'm currently in AFK\n<emoji document_id=5287737368583876982>🌀</emoji> Was online <code>{}</code> ago\n<emoji document_id=5445161912985724546>✏️</emoji> Reason: <i>{}</i></b>",
"status_added": "<b><emoji document_id=5285372392086976148>🦋</emoji> Status successfully set!</b>",
"status_removed": "<b><emoji document_id=5879896690210639947>🗑</emoji> Status successfully removed!</b>",
"no_user": "<b><emoji document_id=5287611315588707430>❌</emoji> Failed to get user information.</b>",
"no_previous_status": "<b><emoji document_id=5287740598399285194>😵‍💫</emoji> Previous nickname not found.</b>",
}
strings_ru = {
"gone": "<b><emoji document_id=5287692511945437157>✅</emoji> Вы успешно вошли в AFK режим!</b>",
"back": "<b><emoji document_id=5287692511945437157>✅</emoji> Вы успешно вышли из AFK режима!</b>",
"afk": "<b><emoji document_id=5287613458777387650>😴</emoji> Сейчас я нахожусь в AFK\n<emoji document_id=5287737368583876982>🌀</emoji> Был в сети <code>{}</code> назад</b>",
"afk_reason": "<b><emoji document_id=5287613458777387650>😴</emoji> Сейчас я нахожусь в AFK\n<emoji document_id=5287737368583876982>🌀</emoji> Был в сети <code>{}</code> назад\n<emoji document_id=5445161912985724546>✏️</emoji> Причина: <i>{}</i></b>",
"status_added": "<b><emoji document_id=5285372392086976148>🦋</emoji> Статус успешно установлен!</b>",
"status_removed": "<b><emoji document_id=5879896690210639947>🗑</emoji> Статус успешно удалён!</b>",
"no_user": "<b><emoji document_id=5287611315588707430>❌</emoji> Не удалось получить информацию о пользователе.</b>",
"no_previous_status": "<b><emoji document_id=5287740598399285194>😵‍💫</emoji> Предыдущий ник не найден.</b>",
}
strings_uz = {
"gone": "<b><emoji document_id=5287692511945437157>✅</emoji> AFK holatiga muvaffaqiyatli kirdingiz!</b>",
"back": "<b><emoji document_id=5287692511945437157>✅</emoji> AFK rejimidan muvaffaqiyatli chiqdingiz!</b>",
"afk": "<b><emoji document_id=5287613458777387650>😴</emoji> Hozir men AFK holatida\n<emoji document_id=5287737368583876982>🌀</emoji> <code>{}</code> avval onlayn bo'lgan</b>",
"afk_reason": "<b><emoji document_id=5287613458777387650>😴</emoji> Hozir men AFK holatida\n<emoji document_id=5287737368583876982>🌀</emoji> <code>{}</code> avval onlayn bo'lgan\n<emoji document_id=5445161912985724546>✏️</emoji> Sabab: <i>{}</i></b>",
"status_added": "<b><emoji document_id=5285372392086976148>🦋</emoji> Status muvaffaqiyatli o'rnatildi!</b>",
"status_removed": "<b><emoji document_id=5879896690210639947>🗑</emoji> Status muvaffaqiyatli olib tashlandi!</b>",
"no_user": "<b><emoji document_id=5287611315588707430>❌</emoji> Foydalanuvchi ma'lumotlari olishda xatolik.</b>",
"no_previous_status": "<b><emoji document_id=5287740598399285194>😵‍💫</emoji> Avvalgi nom topilmadi.</b>",
}
strings_de = {
"gone": "<b><emoji document_id=5287692511945437157>✅</emoji> Du hast den AFK-Modus erfolgreich aktiviert!</b>",
"back": "<b><emoji document_id=5287692511945437157>✅</emoji> Du hast den AFK-Modus erfolgreich deaktiviert!</b>",
"afk": "<b><emoji document_id=5287613458777387650>😴</emoji> Ich bin derzeit im AFK\n<emoji document_id=5287737368583876982>🌀</emoji> War vor <code>{}</code> online</b>",
"afk_reason": "<b><emoji document_id=5287613458777387650>😴</emoji> Ich bin derzeit im AFK\n<emoji document_id=5287737368583876982>🌀</emoji> War vor <code>{}</code> online\n<emoji document_id=5445161912985724546>✏️</emoji> Grund: <i>{}</i></b>",
"status_added": "<b><emoji document_id=5285372392086976148>🦋</emoji> Status erfolgreich gesetzt!</b>",
"status_removed": "<b><emoji document_id=5879896690210639947>🗑</emoji> Status erfolgreich entfernt!</b>",
"no_user": "<b><emoji document_id=5287611315588707430>❌</emoji> Benutzerinformationen konnten nicht abgerufen werden.</b>",
"no_previous_status": "<b><emoji document_id=5287740598399285194>😵‍💫</emoji> Vorheriger Spitzname nicht gefunden.</b>",
}
strings_es = {
"gone": "<b><emoji document_id=5287692511945437157>✅</emoji> ¡Has entrado correctamente en el modo AFK!</b>",
"back": "<b><emoji document_id=5287692511945437157>✅</emoji> ¡Has salido correctamente del modo AFK!</b>",
"afk": "<b><emoji document_id=5287613458777387650>😴</emoji> Actualmente estoy en AFK\n<emoji document_id=5287737368583876982>🌀</emoji> Estuve en línea hace <code>{}</code></b>",
"afk_reason": "<b><emoji document_id=5287613458777387650>😴</emoji> Actualmente estoy en AFK\n<emoji document_id=5287737368583876982>🌀</emoji> Estuve en línea hace <code>{}</code>\n<emoji document_id=5445161912985724546>✏️</emoji> Razón: <i>{}</i></b>",
"status_added": "<b><emoji document_id=5285372392086976148>🦋</emoji> ¡Estado establecido correctamente!</b>",
"status_removed": "<b><emoji document_id=5879896690210639947>🗑</emoji> ¡Estado eliminado correctamente!</b>",
"no_user": "<b><emoji document_id=5287611315588707430>❌</emoji> No se pudieron obtener las información del usuario.</b>",
"no_previous_status": "<b><emoji document_id=5287740598399285194>😵‍💫</emoji> Nombre de usuario anterior no encontrado.</b>",
}
async def client_ready(self, client, db):
self.client = client
self._db = db
self._me = await client.get_me()
@loader.command(
ru_doc="[reason] - Установить режим AFK",
uz_doc="[reason] - AFK holatini sozlash",
de_doc="[reason] - AFK-Modusstatus setzen",
es_doc="[reason] - Establecer estado de modo AFK"
)
async def afk(self, message):
"""[reason] - Set AFK mode status"""
if utils.get_args_raw(message):
self._db.set(__name__, "afk", utils.get_args_raw(message))
else:
self._db.set(__name__, "afk", True)
self._db.set(__name__, "gone", time.time())
self._db.set(__name__, "ratelimit", [])
await self.allmodules.log("afk", data=utils.get_args_raw(message) or None)
await utils.answer(message, self.strings("gone", message))
@loader.command(
ru_doc="Выйти из режима AFK",
uz_doc="AFK rejimidan chiqish",
de_doc="Verlassen des AFK-Modus",
es_doc="Salir del modo AFK"
)
async def unafk(self, message):
"""Exit AFK mode"""
self._db.set(__name__, "afk", False)
self._db.set(__name__, "gone", None)
self._db.set(__name__, "ratelimit", [])
await self.allmodules.log("unafk")
await utils.answer(message, self.strings("back", message))
@loader.command(
ru_doc="Установить статус AFK",
uz_doc="AFK holatini sozlash",
de_doc="Setzt den AFK-Status",
es_doc="Establece el estado AFK"
)
async def setstatus(self, message):
"""Set the AFK status"""
user = await utils.get_user(message)
if user:
current_last_name = user.last_name if user.last_name else ""
if " || AFK" in current_last_name:
await utils.answer(message, self.strings["status_added"].format(name=current_last_name))
return
new_last_name = current_last_name + " || AFK"
try:
await self.client(functions.account.UpdateProfileRequest(last_name=new_last_name))
await utils.answer(message, self.strings["status_added"].format(name=new_last_name))
except Exception as e:
await utils.answer(message, f"<b>Ошибка при добавлении статуса: {str(e)}</b>")
else:
await utils.answer(message, self.strings["no_user"])
@loader.command(
ru_doc="Удалить статус AFK",
uz_doc="AFK holatini o'chirish",
de_doc="Löscht den AFK-Status",
es_doc="Eliminar el estado AFK"
)
async def removestatus(self, message):
"""Удалить статус AFK."""
user = await utils.get_user(message)
if user:
current_last_name = user.last_name if user.last_name else ""
if " || AFK" in current_last_name:
try:
previous_first_name = user.first_name if user.first_name else ""
previous_last_name = current_last_name.replace(" || AFK", "")
await self.client(functions.account.UpdateProfileRequest(first_name=previous_first_name, last_name=previous_last_name))
await utils.answer(message, self.strings["status_removed"])
except Exception as e:
await utils.answer(message, f"<b>Ошибка при удалении статуса: {str(e)}</b>")
else:
await utils.answer(message, self.strings["no_previous_status"])
else:
await utils.answer(message, self.strings["no_user"])
async def watcher(self, message):
if not isinstance(message, types.Message):
return
if message.mentioned or getattr(message.to_id, "user_id", None) == self._me.id:
afk_state = self.get_afk()
if not afk_state:
return
logger.debug("tagged!")
ratelimit = self._db.get(__name__, "ratelimit", [])
if utils.get_chat_id(message) in ratelimit:
return
else:
self._db.setdefault(__name__, {}).setdefault("ratelimit", []).append(
utils.get_chat_id(message)
)
self._db.save()
user = await utils.get_user(message)
if user.is_self or user.bot or user.verified:
logger.debug("User is self, bot or verified.")
return
if self.get_afk() is False:
return
now = datetime.datetime.now().replace(microsecond=0)
gone = datetime.datetime.fromtimestamp(
self._db.get(__name__, "gone")
).replace(microsecond=0)
diff = now - gone
if afk_state is True:
ret = self.strings("afk", message).format(diff)
elif afk_state is not False:
ret = self.strings("afk_reason", message).format(diff, afk_state)
await utils.answer(message, ret, reply_to=message)
def get_afk(self):
return self._db.get(__name__, "afk", False)

File diff suppressed because one or more lines are too long

View File

@@ -1,164 +1,164 @@
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: AuroraBull
# Author: Felix?
# Commands:
# .abull | .abullspam | .abulloff
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/7612b5506856c1eb34c56.jpg
version = (1, 0, 0)
import json
import aiohttp
import asyncio
from random import choice
from .. import loader, utils
from telethon.tl.types import Message # type: ignore
@loader.tds
class AuroraBullMod(loader.Module):
"""Module for insults, make the interlocutor depressed."""
strings = {
"name": "AuroraBull",
"error_key": "<b><i>Error: Key 'BullText' not found.</i></b>",
"error_decoding": "<b><i>Error: The JSON could not be decoded.</i></b>",
"error_uploading_data": "<b><i>Error loading data</i></b>",
"error_valid_args": "<b><i>Please enter valid arguments!</i></b>",
"launched": "<b><i>AuroraBull launched!</i></b>\n\n<b><i>Use <code>.abulloff</code> to stop the attack.</i></b>",
"stopped": "<b><i>AuroraBull has stopped.</i></b>",
}
strings_ru = {
"error_key": "<b><i>Error: ключ 'BullText' не найден.</i></b>",
"error_decoding": "<b><i>Error: не удалось декодировать JSON.</i></b>",
"error_uploading_data": "<b><i>Ошибка при загрузке данных</i></b>",
"error_valid_args": "<b><i>Введите корректные аргументы!</i></b>",
"launched": "<b><i>AuroraBull запущен!</i></b>\n\n<b><i>Используйте <code>.abulloff</code>, чтобы остановить атаку.</i></b>",
"stopped": "<b><i>AuroraBull остановлен.</i></b>",
}
strings_uz = {
"error_key": "<b><i>Error: 'BullText' калити топилмади.</i></b>",
"error_decoding": "<b><i>Error: JSON декодлаш муваффақиятли амалга ошмади.</i></b>",
"error_uploading_data": "<b><i>Маълумотлар юклаб олинмади</i></b>",
"error_valid_args": "<b><i>Iltimos, to'g'ri dalillarni kiriting!</i></b>",
"launched": "<b><i>AuroraBull ishga tushirildi!</i></b>\n\n<b><i>Hujumni toʻxtatish uchun <code>.abulloff</code> dan foydalaning.</i></b>",
"stopped": "<b><i>AuroraBull to'xtadi.</i></b>",
}
strings_de = {
"error_key": "<b><i>Error: Der Schlüssel 'BullText' wurde nicht gefunden.</i></b>",
"error_decoding": "<b><i>Error: JSON konnte nicht decodiert werden.</i></b>",
"error_uploading_data": "<b><i>Fehler beim Hochladen der Daten</i></b>",
"error_valid_args": "<b><i>Bitte geben Sie gültige Argumente ein!</i></b>",
"launched": "<b><i>AuroraBull gestartet!</i></b>\n\n<b><i>Verwenden Sie <code>.abulloff</code>, um den Angriff zu stoppen.</i></b>",
"stopped": "<b><i>AuroraBull hat angehalten.</i></b>",
}
strings_es = {
"error_key": "<b><i>Error: No se encontró la clave 'BullText'.</i></b>",
"error_decoding": "<b><i>Error: No se pudo decodificar JSON.</i></b>",
"error_uploading_data": "<b><i>Error al cargar los datos</i></b>",
"error_valid_args": "<b><i>¡Por favor ingrese argumentos válidos!</i></b>",
"launched": "<b><i>¡AuroraBull lanzado!</i></b>\n\n<b><i>Utiliza <code>.abulloff</code> para detener el ataque.</i></b>",
"stopped": "<b><i>AuroraBull se ha detenido.</i></b>",
}
@loader.command(
ru_doc="Оскорбите вашего собеседника.",
uz_doc="Suhbatdoshingizni insult qiling.",
de_doc="Beleidigen Sie Ihren Gesprächspartner.",
es_doc="Insulta a tu interlocutor.",
)
async def abull(self, message):
"""Insult your interlocutor"""
url = "https://raw.githubusercontent.com/KorenbZla/HikkaModules/main/AuroraBull.json"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200:
response = await response.text()
try:
data = json.loads(response)
if "BullText" in data and isinstance(data["BullText"], list) and data["BullText"]:
text = choice(data["BullText"])
await utils.answer(message, text)
else:
await utils.answer(message, self.strings("error_key"))
except json.JSONDecodeError:
await utils.answer(message, self.strings("error_decoding"))
else:
await utils.answer(message, f"{self.strings('error_uploading_data')}: {response.status}")
@loader.command(
ru_doc="[time] [text] - Заспамте оскорблениями вашего собеседника",
uz_doc="[time] [text] - Suhbatdoshingizni haqorat bilan spam qiling",
de_doc="[time] [text] - Spammen Sie Ihren Gesprächspartner mit Beleidigungen zu",
es_doc="[time] [text] - Spamea a tu interlocutor con insultos",
)
async def abullspam(self, message: Message):
"""[time] [text] - Spam your interlocutor with insults"""
url = "https://raw.githubusercontent.com/KorenbZla/HikkaModules/main/AuroraBull.json"
args = utils.get_args(message)
if not args:
await utils.answer(message, self.strings("error_valid_args"))
return
else:
self.db.set(self.strings["AuroraBull"], "state", True)
try:
time = float(args[0])
text = ' '.join(args[1:]) + " " if len(args) > 1 else ""
except ValueError:
await utils.answer(message, self.strings("error_valid_args"))
return
await utils.answer(message, self.strings("launched"))
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200:
response = await response.text()
data = json.loads(response)
if "BullText" in data and isinstance(data["BullText"], list) and data["BullText"]:
while self.db.get(self.strings["AuroraBull"], "state"):
bull_text = choice(data["BullText"])
await message.respond(text + bull_text)
await asyncio.sleep(time)
else:
await utils.answer(message, self.strings("error_key"))
else:
await utils.answer(message, f"{self.strings('error_uploading_data')}: {response.status}")
@loader.command(
ru_doc="Остановить оскорбления",
uz_doc="Haqoratlarni to'xtating",
de_doc="Hört auf mit den Beleidigungen",
es_doc="basta de insultos",
)
async def abulloff(self, message: Message):
"""Stop the insults"""
self.db.set(self.strings["AuroraBull"], "state", False)
await utils.answer(message, self.strings("stopped"))
return
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: AuroraBull
# Author: Felix?
# Commands:
# .abull | .abullspam | .abulloff
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/7612b5506856c1eb34c56.jpg
version = (1, 0, 0)
import json
import aiohttp
import asyncio
from random import choice
from .. import loader, utils
from telethon.tl.types import Message # type: ignore
@loader.tds
class AuroraBullMod(loader.Module):
"""Module for insults, make the interlocutor depressed."""
strings = {
"name": "AuroraBull",
"error_key": "<b><i>Error: Key 'BullText' not found.</i></b>",
"error_decoding": "<b><i>Error: The JSON could not be decoded.</i></b>",
"error_uploading_data": "<b><i>Error loading data</i></b>",
"error_valid_args": "<b><i>Please enter valid arguments!</i></b>",
"launched": "<b><i>AuroraBull launched!</i></b>\n\n<b><i>Use <code>.abulloff</code> to stop the attack.</i></b>",
"stopped": "<b><i>AuroraBull has stopped.</i></b>",
}
strings_ru = {
"error_key": "<b><i>Error: ключ 'BullText' не найден.</i></b>",
"error_decoding": "<b><i>Error: не удалось декодировать JSON.</i></b>",
"error_uploading_data": "<b><i>Ошибка при загрузке данных</i></b>",
"error_valid_args": "<b><i>Введите корректные аргументы!</i></b>",
"launched": "<b><i>AuroraBull запущен!</i></b>\n\n<b><i>Используйте <code>.abulloff</code>, чтобы остановить атаку.</i></b>",
"stopped": "<b><i>AuroraBull остановлен.</i></b>",
}
strings_uz = {
"error_key": "<b><i>Error: 'BullText' калити топилмади.</i></b>",
"error_decoding": "<b><i>Error: JSON декодлаш муваффақиятли амалга ошмади.</i></b>",
"error_uploading_data": "<b><i>Маълумотлар юклаб олинмади</i></b>",
"error_valid_args": "<b><i>Iltimos, to'g'ri dalillarni kiriting!</i></b>",
"launched": "<b><i>AuroraBull ishga tushirildi!</i></b>\n\n<b><i>Hujumni toʻxtatish uchun <code>.abulloff</code> dan foydalaning.</i></b>",
"stopped": "<b><i>AuroraBull to'xtadi.</i></b>",
}
strings_de = {
"error_key": "<b><i>Error: Der Schlüssel 'BullText' wurde nicht gefunden.</i></b>",
"error_decoding": "<b><i>Error: JSON konnte nicht decodiert werden.</i></b>",
"error_uploading_data": "<b><i>Fehler beim Hochladen der Daten</i></b>",
"error_valid_args": "<b><i>Bitte geben Sie gültige Argumente ein!</i></b>",
"launched": "<b><i>AuroraBull gestartet!</i></b>\n\n<b><i>Verwenden Sie <code>.abulloff</code>, um den Angriff zu stoppen.</i></b>",
"stopped": "<b><i>AuroraBull hat angehalten.</i></b>",
}
strings_es = {
"error_key": "<b><i>Error: No se encontró la clave 'BullText'.</i></b>",
"error_decoding": "<b><i>Error: No se pudo decodificar JSON.</i></b>",
"error_uploading_data": "<b><i>Error al cargar los datos</i></b>",
"error_valid_args": "<b><i>¡Por favor ingrese argumentos válidos!</i></b>",
"launched": "<b><i>¡AuroraBull lanzado!</i></b>\n\n<b><i>Utiliza <code>.abulloff</code> para detener el ataque.</i></b>",
"stopped": "<b><i>AuroraBull se ha detenido.</i></b>",
}
@loader.command(
ru_doc="Оскорбите вашего собеседника.",
uz_doc="Suhbatdoshingizni insult qiling.",
de_doc="Beleidigen Sie Ihren Gesprächspartner.",
es_doc="Insulta a tu interlocutor.",
)
async def abull(self, message):
"""Insult your interlocutor"""
url = "https://raw.githubusercontent.com/KorenbZla/HikkaModules/main/AuroraBull.json"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200:
response = await response.text()
try:
data = json.loads(response)
if "BullText" in data and isinstance(data["BullText"], list) and data["BullText"]:
text = choice(data["BullText"])
await utils.answer(message, text)
else:
await utils.answer(message, self.strings("error_key"))
except json.JSONDecodeError:
await utils.answer(message, self.strings("error_decoding"))
else:
await utils.answer(message, f"{self.strings('error_uploading_data')}: {response.status}")
@loader.command(
ru_doc="[time] [text] - Заспамте оскорблениями вашего собеседника",
uz_doc="[time] [text] - Suhbatdoshingizni haqorat bilan spam qiling",
de_doc="[time] [text] - Spammen Sie Ihren Gesprächspartner mit Beleidigungen zu",
es_doc="[time] [text] - Spamea a tu interlocutor con insultos",
)
async def abullspam(self, message: Message):
"""[time] [text] - Spam your interlocutor with insults"""
url = "https://raw.githubusercontent.com/KorenbZla/HikkaModules/main/AuroraBull.json"
args = utils.get_args(message)
if not args:
await utils.answer(message, self.strings("error_valid_args"))
return
else:
self.db.set(self.strings["AuroraBull"], "state", True)
try:
time = float(args[0])
text = ' '.join(args[1:]) + " " if len(args) > 1 else ""
except ValueError:
await utils.answer(message, self.strings("error_valid_args"))
return
await utils.answer(message, self.strings("launched"))
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200:
response = await response.text()
data = json.loads(response)
if "BullText" in data and isinstance(data["BullText"], list) and data["BullText"]:
while self.db.get(self.strings["AuroraBull"], "state"):
bull_text = choice(data["BullText"])
await message.respond(text + bull_text)
await asyncio.sleep(time)
else:
await utils.answer(message, self.strings("error_key"))
else:
await utils.answer(message, f"{self.strings('error_uploading_data')}: {response.status}")
@loader.command(
ru_doc="Остановить оскорбления",
uz_doc="Haqoratlarni to'xtating",
de_doc="Hört auf mit den Beleidigungen",
es_doc="basta de insultos",
)
async def abulloff(self, message: Message):
"""Stop the insults"""
self.db.set(self.strings["AuroraBull"], "state", False)
await utils.answer(message, self.strings("stopped"))
return

View File

@@ -23,7 +23,7 @@
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/d3f0f14e90ce2f82d8f1f.jpg
__version__ = (1, 2, 0)
__version__ = (1, 2, 1)
from hikkatl.types import Message # type: ignore
from .. import loader, utils
@@ -77,7 +77,7 @@ class AuroraDonateMod(loader.Module):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"custom_text",
None,
"<b><i>Created by: @AuroraModules</i></b>",
lambda: self.strings["cfg_custom_text"],
),
loader.ConfigValue(
@@ -121,18 +121,15 @@ class AuroraDonateMod(loader.Module):
banner_url = self.config["banner_url"]
custom_text = self.config["custom_text"]
hide_text = self.config["hide_text"]
if custom_text is None:
custom_text = "<b><i>Created by: @AuroraModules</i></b>"
else:
custom_text = custom_text
if args[0] == "-h":
if hide_text is None:
if len(args) > 0 and args[0] == '-h':
if hide_text == None:
custom_text = custom_text
else:
custom_text = hide_text
else:
custom_text = custom_text
if CryptoBot is None and xRocket is None:
if banner_url is None:
await utils.answer(message, custom_text)
@@ -142,6 +139,7 @@ class AuroraDonateMod(loader.Module):
banner_url,
caption=custom_text
)
await message.delete()
else:
await self.inline.form(
message=message,

View File

@@ -1,179 +1,179 @@
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: AutoDeleteMessages
# Author: Felix?
# Commands:
# .autodel
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/b3e9c4bef7348c0fda21e.jpg
__version__ = (1, 0, 0)
import asyncio
from hikkatl.types import Message # type: ignore
from .. import loader, utils
class AutoDeleteMessagesMod(loader.Module):
"""Automatically deletes all your messages in the specified chats."""
strings = {
"name": "AutoDeleteMessages",
"status": "<emoji document_id=6028435952299413210></emoji> Status of AutoDeleteMessages",
"s_True": "Active.",
"s_False": "Inactive.",
"on": "Activated.",
"off": "Deactivated.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Please provide arguments",
"error": "Error: {}",
"cfg_chat_id": "Enter the chat ID where messages will be deleted",
"cfg_time_delete": "Enter the interval in minutes after which your messages will be deleted",
"cfg_error": "Configuration error or value not specified",
}
strings_ru = {
"status": "<emoji document_id=6028435952299413210></emoji> Статус работы AutoDeleteMessages",
"s_True": "Активно.",
"s_False": "Неактивно.",
"on": "Включено.",
"off": "Выключено.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Укажите аргументы",
"error": "Error: {}",
"cfg_chat_id": "Введите идентификатор чата, в котором будут удаляться сообщения",
"cfg_time_delete": "Введите интервал в минутах, через который будут удаляться ваши сообщения",
"cfg_error": "Ошибка в конфигурации или не указано значение",
}
strings_uz = {
"status": "<emoji document_id=6028435952299413210></emoji> AutoDeleteMessages holati",
"s_True": "Faol.",
"s_False": "Faol emas.",
"on": "Faollashtirildi.",
"off": "O'chirildi.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Iltimos, argumentlarni kiriting",
"error": "Error: {}",
"cfg_chat_id": "Xabarlar o'chiriladigan chat ID'sini kiriting",
"cfg_time_delete": "Xabarlaringiz qachon o'chirilishini daqiqalarda kiriting",
"cfg_error": "Konfiguratsiya xatosi yoki qiymat ko'rsatilmagan",
}
strings_de = {
"status": "<emoji document_id=6028435952299413210></emoji> Status von AutoDeleteMessages",
"s_True": "Aktiv.",
"s_False": "Inaktiv.",
"on": "Aktiviert.",
"off": "Deaktiviert.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Bitte geben Sie Argumente an",
"error": "Error: {}",
"cfg_chat_id": "Geben Sie die Chat-ID ein, in der Nachrichten gelöscht werden sollen",
"cfg_time_delete": "Geben Sie das Intervall in Minuten ein, nach dem Ihre Nachrichten gelöscht werden",
"cfg_error": "Konfigurationsfehler oder Wert nicht angegeben",
}
strings_es = {
"status": "<emoji document_id=6028435952299413210></emoji> Estado de AutoDeleteMessages",
"s_True": "Activo.",
"s_False": "Inactivo.",
"on": "Activado.",
"off": "Desactivado.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Por favor, proporcione argumentos",
"error": "Error: {}",
"cfg_chat_id": "Ingrese el ID del chat donde se eliminarán los mensajes",
"cfg_time_delete": "Ingrese el intervalo en minutos después del cual se eliminarán sus mensajes",
"cfg_error": "Error de configuración o valor no especificado",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"chat_id",
[],
lambda: self.strings["cfg_chat_id"],
),
loader.ConfigValue(
"time_delete",
15,
lambda: self.strings["cfg_time_delete"],
validator=loader.validators.Integer(minimum=1),
),
)
async def client_ready(self, client, db):
self.client = client
self.db = db
@loader.command(
ru_doc="<on/off> - установить статус работы модуля.",
uz_doc="<on/off> - modulning ish holatini sozlash.",
de_doc="<on/off> - Den Status des Moduls festlegen.",
es_doc="<on/off> - Establecer el estado de operación del módulo.",
)
async def autodel(self, message):
"""<on/off> - set the module operation status"""
args = utils.get_args_raw(message).lower()
if self.config["chat_id"] is None or self.config["chat_id"] == []:
await utils.answer(message, self.strings("cfg_error"))
return
else:
chat_ids = self.config["chat_id"]
if isinstance(chat_ids, int):
chat_ids = [chat_ids]
elif not isinstance(chat_ids, list):
chat_ids = []
if self.config["time_delete"] == None:
await utils.answer(message, self.strings("cfg_error"))
return
else:
time = self.config["time_delete"]
status_result_True = self.db.get("AutoDeleteMessages", "status", True)
if status_result_True:
status_result = self.strings("s_True")
else:
status_result = self.strings("s_False")
if not args:
status = self.strings("status")
await utils.answer(message, f"<b>{status}: <i>{status_result}</i></b>")
return
if args == "on":
args_s = self.strings("on")
self.db.set("AutoDeleteMessages", "status", True)
await utils.answer(message, f"<emoji document_id=5287692511945437157>✅</emoji> <b>AutoDeleteMessages: <i>{args_s}</i></b>")
elif args == "off":
args_s = self.strings("off")
self.db.set("AutoDeleteMessages", "status", False)
await utils.answer(message, f"<emoji document_id=5287692511945437157>✅</emoji> <b>AutoDeleteMessages: <i>{args_s}</i></b>")
else:
n_args = self.strings("n_args")
await utils.answer(message, f"<b>{n_args}</b>")
return
await asyncio.sleep(time)
while self.db.get("AutoDeleteMessages", "status"):
for chat_id in chat_ids:
try:
async for msg in self.client.iter_messages(chat_id, from_user="me"):
await msg.delete()
except Exception as e:
await utils.answer(message, self.strings['error'].format(e))
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: AutoDeleteMessages
# Author: Felix?
# Commands:
# .autodel
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/b3e9c4bef7348c0fda21e.jpg
__version__ = (1, 0, 0)
import asyncio
from hikkatl.types import Message # type: ignore
from .. import loader, utils
class AutoDeleteMessagesMod(loader.Module):
"""Automatically deletes all your messages in the specified chats."""
strings = {
"name": "AutoDeleteMessages",
"status": "<emoji document_id=6028435952299413210></emoji> Status of AutoDeleteMessages",
"s_True": "Active.",
"s_False": "Inactive.",
"on": "Activated.",
"off": "Deactivated.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Please provide arguments",
"error": "Error: {}",
"cfg_chat_id": "Enter the chat ID where messages will be deleted",
"cfg_time_delete": "Enter the interval in minutes after which your messages will be deleted",
"cfg_error": "Configuration error or value not specified",
}
strings_ru = {
"status": "<emoji document_id=6028435952299413210></emoji> Статус работы AutoDeleteMessages",
"s_True": "Активно.",
"s_False": "Неактивно.",
"on": "Включено.",
"off": "Выключено.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Укажите аргументы",
"error": "Error: {}",
"cfg_chat_id": "Введите идентификатор чата, в котором будут удаляться сообщения",
"cfg_time_delete": "Введите интервал в минутах, через который будут удаляться ваши сообщения",
"cfg_error": "Ошибка в конфигурации или не указано значение",
}
strings_uz = {
"status": "<emoji document_id=6028435952299413210></emoji> AutoDeleteMessages holati",
"s_True": "Faol.",
"s_False": "Faol emas.",
"on": "Faollashtirildi.",
"off": "O'chirildi.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Iltimos, argumentlarni kiriting",
"error": "Error: {}",
"cfg_chat_id": "Xabarlar o'chiriladigan chat ID'sini kiriting",
"cfg_time_delete": "Xabarlaringiz qachon o'chirilishini daqiqalarda kiriting",
"cfg_error": "Konfiguratsiya xatosi yoki qiymat ko'rsatilmagan",
}
strings_de = {
"status": "<emoji document_id=6028435952299413210></emoji> Status von AutoDeleteMessages",
"s_True": "Aktiv.",
"s_False": "Inaktiv.",
"on": "Aktiviert.",
"off": "Deaktiviert.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Bitte geben Sie Argumente an",
"error": "Error: {}",
"cfg_chat_id": "Geben Sie die Chat-ID ein, in der Nachrichten gelöscht werden sollen",
"cfg_time_delete": "Geben Sie das Intervall in Minuten ein, nach dem Ihre Nachrichten gelöscht werden",
"cfg_error": "Konfigurationsfehler oder Wert nicht angegeben",
}
strings_es = {
"status": "<emoji document_id=6028435952299413210></emoji> Estado de AutoDeleteMessages",
"s_True": "Activo.",
"s_False": "Inactivo.",
"on": "Activado.",
"off": "Desactivado.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Por favor, proporcione argumentos",
"error": "Error: {}",
"cfg_chat_id": "Ingrese el ID del chat donde se eliminarán los mensajes",
"cfg_time_delete": "Ingrese el intervalo en minutos después del cual se eliminarán sus mensajes",
"cfg_error": "Error de configuración o valor no especificado",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"chat_id",
[],
lambda: self.strings["cfg_chat_id"],
),
loader.ConfigValue(
"time_delete",
15,
lambda: self.strings["cfg_time_delete"],
validator=loader.validators.Integer(minimum=1),
),
)
async def client_ready(self, client, db):
self.client = client
self.db = db
@loader.command(
ru_doc="<on/off> - установить статус работы модуля.",
uz_doc="<on/off> - modulning ish holatini sozlash.",
de_doc="<on/off> - Den Status des Moduls festlegen.",
es_doc="<on/off> - Establecer el estado de operación del módulo.",
)
async def autodel(self, message):
"""<on/off> - set the module operation status"""
args = utils.get_args_raw(message).lower()
if self.config["chat_id"] is None or self.config["chat_id"] == []:
await utils.answer(message, self.strings("cfg_error"))
return
else:
chat_ids = self.config["chat_id"]
if isinstance(chat_ids, int):
chat_ids = [chat_ids]
elif not isinstance(chat_ids, list):
chat_ids = []
if self.config["time_delete"] == None:
await utils.answer(message, self.strings("cfg_error"))
return
else:
time = self.config["time_delete"]
status_result_True = self.db.get("AutoDeleteMessages", "status", True)
if status_result_True:
status_result = self.strings("s_True")
else:
status_result = self.strings("s_False")
if not args:
status = self.strings("status")
await utils.answer(message, f"<b>{status}: <i>{status_result}</i></b>")
return
if args == "on":
args_s = self.strings("on")
self.db.set("AutoDeleteMessages", "status", True)
await utils.answer(message, f"<emoji document_id=5287692511945437157>✅</emoji> <b>AutoDeleteMessages: <i>{args_s}</i></b>")
elif args == "off":
args_s = self.strings("off")
self.db.set("AutoDeleteMessages", "status", False)
await utils.answer(message, f"<emoji document_id=5287692511945437157>✅</emoji> <b>AutoDeleteMessages: <i>{args_s}</i></b>")
else:
n_args = self.strings("n_args")
await utils.answer(message, f"<b>{n_args}</b>")
return
await asyncio.sleep(time)
while self.db.get("AutoDeleteMessages", "status"):
for chat_id in chat_ids:
try:
async for msg in self.client.iter_messages(chat_id, from_user="me"):
await msg.delete()
except Exception as e:
await utils.answer(message, self.strings['error'].format(e))
await asyncio.sleep(time)

View File

@@ -1,222 +1,222 @@
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: AutoFarmUniversal
# Author: Felix?
# Commands:
# .ufarm
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/77e64e3d33263a669125f.jpg
__version__ = (1, 0, 0)
import asyncio
import random
from .. import loader, utils
@loader.tds
class AutoFarmUniversalMod(loader.Module):
"""Universal auto farmer with settings in the config"""
strings = {
"name": "AutoFarmUniversal",
"status": "<emoji document_id=6028435952299413210></emoji> Module operation status",
"s_1": "Active.",
"s_0": "Inactive.",
"on": "Activated.",
"off": "Deactivated.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Specify the arguments",
"error_cfg": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error! Incorrect config value.</b>",
"cfg_chat_id": "Enter the chat identifier.",
"cfg_text": "Enter the text that will be sent.",
"cfg_time_delay": "Enter the delay in seconds",
"random_time_delay_min": "Enter the minimum value after how long the command will be sent",
"random_time_delay_max": "Enter the maximum value after how long the command will be sent",
}
strings_ru = {
"status": "<emoji document_id=6028435952299413210></emoji> Статус работы модуля",
"s_1": "Активно.",
"s_0": "Неактивно.",
"on": "Активировано.",
"off": "Деактивировано.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Укажите аргументы",
"error_cfg": "<emoji document_id=5287611315588707430>❌</emoji> <b>Ошибка! Неверное значение конфигурации.</b>",
"cfg_chat_id": "Введите идентификатор чата.",
"cfg_text": "Введите текст, который будет отправлен.",
"cfg_time_delay": "Введите задержку в секундах",
"random_time_delay_min": "Введите минимальное значение времени, через которое будет отправлена команда",
"random_time_delay_max": "Введите максимальное значение времени, через которое будет отправлена команда",
}
strings_uz = {
"status": "<emoji document_id=6028435952299413210></emoji> Modul ishlash holati",
"s_1": "Faol.",
"s_0": "Faol emas.",
"on": "Faollashtirildi.",
"off": "O'chirildi.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Argumentlarni kiriting",
"error_cfg": "<emoji document_id=5287611315588707430>❌</emoji> <b>Xato! Noto'g'ri konfiguratsiya qiymati.</b>",
"cfg_chat_id": "Chat identifikatorini kiriting.",
"cfg_text": "Yuboriladigan matnni kiriting.",
"cfg_time_delay": "Kechikishni sekundlarda kiriting",
"random_time_delay_min": "Buyruq yuboriladigan minimal vaqtni kiriting",
"random_time_delay_max": "Buyruq yuboriladigan maksimal vaqtni kiriting",
}
strings_de = {
"status": "<emoji document_id=6028435952299413210></emoji> Modulbetriebsstatus",
"s_1": "Aktiv.",
"s_0": "Inaktiv.",
"on": "Aktiviert.",
"off": "Deaktiviert.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Geben Sie die Argumente an",
"error_cfg": "<emoji document_id=5287611315588707430>❌</emoji> <b>Fehler! Ungültiger Konfigurationswert.</b>",
"cfg_chat_id": "Geben Sie die Chat-ID ein.",
"cfg_text": "Geben Sie den zu sendenden Text ein.",
"cfg_time_delay": "Geben Sie die Verzögerung in Sekunden ein",
"random_time_delay_min": "Geben Sie den minimalen Wert an, nach dem der Befehl gesendet wird",
"random_time_delay_max": "Geben Sie den maximalen Wert an, nach dem der Befehl gesendet wird",
}
strings_es = {
"status": "<emoji document_id=6028435952299413210></emoji> Estado de operación del módulo",
"s_1": "Activo.",
"s_0": "Inactivo.",
"on": "Activado.",
"off": "Desactivado.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Especifica los argumentos",
"error_cfg": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error! Valor de configuración incorrecto.</b>",
"cfg_chat_id": "Introduce el identificador del chat.",
"cfg_text": "Introduce el texto que se enviará.",
"cfg_time_delay": "Introduce el retraso en segundos",
"random_time_delay_min": "Introduce el valor mínimo después del cual se enviará el comando",
"random_time_delay_max": "Introduce el valor máximo después del cual se enviará el comando",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"chat_id",
None,
lambda: self.strings["cfg_chat_id"]
),
loader.ConfigValue(
"text",
None,
lambda: self.strings["cfg_text"]
),
loader.ConfigValue(
"time_delay",
None,
lambda: self.strings["cfg_time_delay"],
validator=loader.validators.Integer(minimum=1),
),
loader.ConfigValue(
"random_time_delay_min",
None,
lambda: self.strings["cfg_random_time_delay_min"],
validator=loader.validators.Integer(minimum=1),
),
loader.ConfigValue(
"random_time_delay_max",
None,
lambda: self.strings["cfg_random_time_delay_max"],
validator=loader.validators.Integer(minimum=2),
),
)
async def client_ready(self, client, db):
self.db = db
self.client = client
@loader.command(
ru_doc="{on/off} - включить или выключить автоматическую фарминг",
uz_doc="{on/off} - avtomatik fermani yoqish yoki o'chirish",
de_doc="{on/off} - Auto-Farm ein- oder ausschalten",
es_doc="{on/off} - activar o desactivar la auto-granja",
)
async def ufarm(self, message):
"""{on/off} - turn auto farm on or off"""
args = utils.get_args_raw(message).lower()
status_result_True = self.db.get("AutoFarmUniversal", "status", True)
if status_result_True:
status_result = self.strings("s_1")
else:
status_result = self.strings("s_0")
error_cfg = self.strings("error_cfg")
time_delay = self.config["time_delay"]
random_time_delay = self.config["random_time_delay_min"] or self.config["random_time_delay_max"]
if self.config["chat_id"] == None:
await utils.answer(message, f"<b>{error_cfg}</b>")
self.db.set("AutoFarmUniversal", "status", False)
await self.allmodules.commands["config"](await message.client.send_message(message.chat_id, f"{self.get_prefix()}cfg AutoFarmUniversal"))
return
if self.config["text"] == None:
await utils.answer(message, f"<b>{error_cfg}</b>")
self.db.set("AutoFarmUniversal", "status", False)
await self.allmodules.commands["config"](await message.client.send_message(message.chat_id, f"{self.get_prefix()}cfg AutoFarmUniversal"))
return
if (time_delay is not None and time_delay != 0) and (random_time_delay is not None and random_time_delay != 0):
await utils.answer(message, f"<b>{error_cfg}</b>")
self.db.set("AutoFarmUniversal", "status", False)
await self.allmodules.commands["config"](await message.client.send_message(message.chat_id, f"{self.get_prefix()}cfg AutoFarmUniversal"))
return
if (time_delay is None or time_delay == 0) and (random_time_delay is None or random_time_delay == 0):
await utils.answer(message, f"<b>{error_cfg}</b>")
self.db.set("AutoFarmUniversal", "status", False)
await self.allmodules.commands["config"](await message.client.send_message(message.chat_id, f"{self.get_prefix()}cfg AutoFarmUniversal"))
return
if not args:
status = self.strings("status")
await utils.answer(message, f"<b>{status}: <i>{status_result}</i></b>")
return
if args == "on":
args_s = self.strings("on")
self.db.set("AutoFarmUniversal", "status", True)
await utils.answer(message, f"<emoji document_id=5287692511945437157>✅</emoji> <b>AutoFarmUniversal: <i>{args_s}</i></b>")
elif args == "off":
args_s = self.strings("off")
self.db.set("AutoFarmUniversal", "status", False)
await utils.answer(message, f"<emoji document_id=5287692511945437157>✅</emoji> <b>AutoFarmUniversal: <i>{args_s}</i></b>")
else:
n_args = self.strings("n_args")
await utils.answer(message, f"<b>{n_args}</b>")
return
chat_id = self.config["chat_id"]
text = self.config["text"]
if time_delay is not None and time_delay != 0:
while self.db.get("AutoFarmUniversal", "status"):
await message.client.send_message(chat_id, str(text))
time = self.config["time_delay"]
await asyncio.sleep(time)
if random_time_delay is not None and random_time_delay != 0:
while self.db.get("AutoFarmUniversal", "status"):
min_delay = self.config['random_time_delay_min']
max_delay = self.config['random_time_delay_max']
r_time = random.randint(min_delay, max_delay)
await message.client.send_message(chat_id, str(text))
await asyncio.sleep(r_time)
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: AutoFarmUniversal
# Author: Felix?
# Commands:
# .ufarm
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/77e64e3d33263a669125f.jpg
__version__ = (1, 0, 0)
import asyncio
import random
from .. import loader, utils
@loader.tds
class AutoFarmUniversalMod(loader.Module):
"""Universal auto farmer with settings in the config"""
strings = {
"name": "AutoFarmUniversal",
"status": "<emoji document_id=6028435952299413210></emoji> Module operation status",
"s_1": "Active.",
"s_0": "Inactive.",
"on": "Activated.",
"off": "Deactivated.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Specify the arguments",
"error_cfg": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error! Incorrect config value.</b>",
"cfg_chat_id": "Enter the chat identifier.",
"cfg_text": "Enter the text that will be sent.",
"cfg_time_delay": "Enter the delay in seconds",
"random_time_delay_min": "Enter the minimum value after how long the command will be sent",
"random_time_delay_max": "Enter the maximum value after how long the command will be sent",
}
strings_ru = {
"status": "<emoji document_id=6028435952299413210></emoji> Статус работы модуля",
"s_1": "Активно.",
"s_0": "Неактивно.",
"on": "Активировано.",
"off": "Деактивировано.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Укажите аргументы",
"error_cfg": "<emoji document_id=5287611315588707430>❌</emoji> <b>Ошибка! Неверное значение конфигурации.</b>",
"cfg_chat_id": "Введите идентификатор чата.",
"cfg_text": "Введите текст, который будет отправлен.",
"cfg_time_delay": "Введите задержку в секундах",
"random_time_delay_min": "Введите минимальное значение времени, через которое будет отправлена команда",
"random_time_delay_max": "Введите максимальное значение времени, через которое будет отправлена команда",
}
strings_uz = {
"status": "<emoji document_id=6028435952299413210></emoji> Modul ishlash holati",
"s_1": "Faol.",
"s_0": "Faol emas.",
"on": "Faollashtirildi.",
"off": "O'chirildi.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Argumentlarni kiriting",
"error_cfg": "<emoji document_id=5287611315588707430>❌</emoji> <b>Xato! Noto'g'ri konfiguratsiya qiymati.</b>",
"cfg_chat_id": "Chat identifikatorini kiriting.",
"cfg_text": "Yuboriladigan matnni kiriting.",
"cfg_time_delay": "Kechikishni sekundlarda kiriting",
"random_time_delay_min": "Buyruq yuboriladigan minimal vaqtni kiriting",
"random_time_delay_max": "Buyruq yuboriladigan maksimal vaqtni kiriting",
}
strings_de = {
"status": "<emoji document_id=6028435952299413210></emoji> Modulbetriebsstatus",
"s_1": "Aktiv.",
"s_0": "Inaktiv.",
"on": "Aktiviert.",
"off": "Deaktiviert.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Geben Sie die Argumente an",
"error_cfg": "<emoji document_id=5287611315588707430>❌</emoji> <b>Fehler! Ungültiger Konfigurationswert.</b>",
"cfg_chat_id": "Geben Sie die Chat-ID ein.",
"cfg_text": "Geben Sie den zu sendenden Text ein.",
"cfg_time_delay": "Geben Sie die Verzögerung in Sekunden ein",
"random_time_delay_min": "Geben Sie den minimalen Wert an, nach dem der Befehl gesendet wird",
"random_time_delay_max": "Geben Sie den maximalen Wert an, nach dem der Befehl gesendet wird",
}
strings_es = {
"status": "<emoji document_id=6028435952299413210></emoji> Estado de operación del módulo",
"s_1": "Activo.",
"s_0": "Inactivo.",
"on": "Activado.",
"off": "Desactivado.",
"n_args": "<emoji document_id=5285372392086976148>🚫</emoji> Especifica los argumentos",
"error_cfg": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error! Valor de configuración incorrecto.</b>",
"cfg_chat_id": "Introduce el identificador del chat.",
"cfg_text": "Introduce el texto que se enviará.",
"cfg_time_delay": "Introduce el retraso en segundos",
"random_time_delay_min": "Introduce el valor mínimo después del cual se enviará el comando",
"random_time_delay_max": "Introduce el valor máximo después del cual se enviará el comando",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"chat_id",
None,
lambda: self.strings["cfg_chat_id"]
),
loader.ConfigValue(
"text",
None,
lambda: self.strings["cfg_text"]
),
loader.ConfigValue(
"time_delay",
None,
lambda: self.strings["cfg_time_delay"],
validator=loader.validators.Integer(minimum=1),
),
loader.ConfigValue(
"random_time_delay_min",
None,
lambda: self.strings["cfg_random_time_delay_min"],
validator=loader.validators.Integer(minimum=1),
),
loader.ConfigValue(
"random_time_delay_max",
None,
lambda: self.strings["cfg_random_time_delay_max"],
validator=loader.validators.Integer(minimum=2),
),
)
async def client_ready(self, client, db):
self.db = db
self.client = client
@loader.command(
ru_doc="{on/off} - включить или выключить автоматическую фарминг",
uz_doc="{on/off} - avtomatik fermani yoqish yoki o'chirish",
de_doc="{on/off} - Auto-Farm ein- oder ausschalten",
es_doc="{on/off} - activar o desactivar la auto-granja",
)
async def ufarm(self, message):
"""{on/off} - turn auto farm on or off"""
args = utils.get_args_raw(message).lower()
status_result_True = self.db.get("AutoFarmUniversal", "status", True)
if status_result_True:
status_result = self.strings("s_1")
else:
status_result = self.strings("s_0")
error_cfg = self.strings("error_cfg")
time_delay = self.config["time_delay"]
random_time_delay = self.config["random_time_delay_min"] or self.config["random_time_delay_max"]
if self.config["chat_id"] == None:
await utils.answer(message, f"<b>{error_cfg}</b>")
self.db.set("AutoFarmUniversal", "status", False)
await self.allmodules.commands["config"](await message.client.send_message(message.chat_id, f"{self.get_prefix()}cfg AutoFarmUniversal"))
return
if self.config["text"] == None:
await utils.answer(message, f"<b>{error_cfg}</b>")
self.db.set("AutoFarmUniversal", "status", False)
await self.allmodules.commands["config"](await message.client.send_message(message.chat_id, f"{self.get_prefix()}cfg AutoFarmUniversal"))
return
if (time_delay is not None and time_delay != 0) and (random_time_delay is not None and random_time_delay != 0):
await utils.answer(message, f"<b>{error_cfg}</b>")
self.db.set("AutoFarmUniversal", "status", False)
await self.allmodules.commands["config"](await message.client.send_message(message.chat_id, f"{self.get_prefix()}cfg AutoFarmUniversal"))
return
if (time_delay is None or time_delay == 0) and (random_time_delay is None or random_time_delay == 0):
await utils.answer(message, f"<b>{error_cfg}</b>")
self.db.set("AutoFarmUniversal", "status", False)
await self.allmodules.commands["config"](await message.client.send_message(message.chat_id, f"{self.get_prefix()}cfg AutoFarmUniversal"))
return
if not args:
status = self.strings("status")
await utils.answer(message, f"<b>{status}: <i>{status_result}</i></b>")
return
if args == "on":
args_s = self.strings("on")
self.db.set("AutoFarmUniversal", "status", True)
await utils.answer(message, f"<emoji document_id=5287692511945437157>✅</emoji> <b>AutoFarmUniversal: <i>{args_s}</i></b>")
elif args == "off":
args_s = self.strings("off")
self.db.set("AutoFarmUniversal", "status", False)
await utils.answer(message, f"<emoji document_id=5287692511945437157>✅</emoji> <b>AutoFarmUniversal: <i>{args_s}</i></b>")
else:
n_args = self.strings("n_args")
await utils.answer(message, f"<b>{n_args}</b>")
return
chat_id = self.config["chat_id"]
text = self.config["text"]
if time_delay is not None and time_delay != 0:
while self.db.get("AutoFarmUniversal", "status"):
await message.client.send_message(chat_id, str(text))
time = self.config["time_delay"]
await asyncio.sleep(time)
if random_time_delay is not None and random_time_delay != 0:
while self.db.get("AutoFarmUniversal", "status"):
min_delay = self.config['random_time_delay_min']
max_delay = self.config['random_time_delay_max']
r_time = random.randint(min_delay, max_delay)
await message.client.send_message(chat_id, str(text))
await asyncio.sleep(r_time)

View File

@@ -1,368 +1,368 @@
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: AuroraFeedBack
# Author: Felix? || n3rcy
# Commands:
# .flink | .banfeedback | .unbanfeedback
# scope: hikka_only
# meta developer: @AuroraModules & @nercymods
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/05a519da50f993b950260.jpg
__version__ = (1, 0, 2)
from aiogram.types import Message as AiogramMessage
from aiogram.types import CallbackQuery as AiogramCallbackQuery
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from ..inline.types import InlineCall # type: ignore
from html import escape
from .. import loader, utils
@loader.tds
class AuroraFeedBackMod(loader.Module):
"""Multifunctional feedback bot."""
strings = {
"name": "AuroraFeedBack",
"new_m": "🗣 New message from",
"not_text": "🔎 The text was not found.",
"waiting_answer": "⏳ Waiting for answer to user",
"flink": "Here is my link to the feedback bot",
"owner_answer": "🗣 Owner's Response",
"successfully_send": "💬 Message successfully sent",
"not_arg": "❌ No UserID argument provided",
"successfully_ban": "✅ User successfully banned",
"successfully_unban": "✅ User successfully unbanned",
"already_banned": "🚫 User is already banned",
"not_in_ban": "✅ User is not in the ban list",
"cfg_mode": "Enable/Disable feedback bot functionality",
"cfg_custom_text": "Enter custom greeting text",
"cfg_no_meta": "Enter custom text for /nometa",
"cfg_no_meta_baner": "Enter custom link for meta-banner",
}
strings_ru = {
"new_m": "🗣 Новое сообщение от",
"not_text": "🔎 Текст не найден.",
"waiting_answer": "⏳ Ожидание ответа пользователя",
"flink": "Вот моя ссылка на feedback бота",
"owner_answer": "🗣 Ответ владельца",
"successfully_send": "💬 Сообщение успешно отправлено",
"not_arg": "Не указан UserID",
"successfully_ban": "✅ Пользователь успешно заблокирован",
"successfully_unban": "✅ Пользователь успешно разблокирован",
"already_banned": "🚫 Пользователь уже заблокирован",
"not_in_ban": "✅ Пользователь не находится в списке заблокированных",
"cfg_mode": "Включить/выключить функционал feedback бота",
"cfg_custom_text": "Введите кастомный текст для приветствия",
"cfg_no_meta": "Введите кастомный текст для команды /nometa",
"cfg_no_meta_baner": "Введите кастомную ссылку на мета-баннер",
}
strings_uz = {
"new_m": "🗣 Yangi xabar",
"not_text": "🔎 Matn topilmadi.",
"waiting_answer": "⏳ Foydalanuvchidan javob kutilmoqda",
"flink": "Bu mening feedback botim havolam",
"owner_answer": "🗣 Egasi javobi",
"successfully_send": "💬 Xabar muvaffaqiyatli yuborildi",
"not_arg": "❌ UserID argument kiritilmagan",
"successfully_ban": "✅ Foydalanuvchi muvaffaqiyatli bloklandi",
"successfully_unban": "✅ Foydalanuvchi muvaffaqiyatli ochib tashlandi",
"already_banned": "🚫 Foydalanuvchi allaqachon bloklangan",
"not_in_ban": "✅ Foydalanuvchi blok ro'yxatida yo'q",
"cfg_mode": "Feedback bot funktsiyasini yoqish/yopish",
"cfg_custom_text": "Xush kelibsiz matnini kiriting",
"cfg_no_meta": "/nometa uchun maxsus matnni kiriting",
"cfg_no_meta_baner": "Meta-banner uchun maxsus havolani kiriting",
}
strings_de = {
"new_m": "🗣 Neue Nachricht von",
"not_text": "🔎 Der Text wurde nicht gefunden.",
"waiting_answer": "⏳ Warten auf die Antwort des Benutzers",
"flink": "Hier ist mein Link zum Feedback-Bot",
"owner_answer": "🗣 Antwort des Eigentümers",
"successfully_send": "💬 Nachricht erfolgreich gesendet",
"not_arg": "❌ Kein UserID-Argument angegeben",
"successfully_ban": "✅ Benutzer erfolgreich gesperrt",
"successfully_unban": "✅ Benutzer erfolgreich entsperrt",
"already_banned": "🚫 Benutzer ist bereits gesperrt",
"not_in_ban": "✅ Benutzer befindet sich nicht in der Sperrliste",
"cfg_mode": "Feedback-Bot-Funktionalität aktivieren/deaktivieren",
"cfg_custom_text": "Geben Sie benutzerdefinierten Begrüßungstext ein",
"cfg_no_meta": "Geben Sie benutzerdefinierten Text für /nometa ein",
"cfg_no_meta_baner": "Geben Sie einen benutzerdefinierten Link für den Meta-Banner ein",
}
strings_es = {
"new_m": "🗣 Nuevo mensaje de",
"not_text": "🔎 No se encontró el texto.",
"waiting_answer": "⏳ Esperando la respuesta del usuario",
"flink": "Aquí está mi enlace al bot de retroalimentación",
"owner_answer": "🗣 Respuesta del propietario",
"successfully_send": "💬 Mensaje enviado con éxito",
"not_arg": "❌ No se proporcionó el argumento UserID",
"successfully_ban": "✅ Usuario bloqueado correctamente",
"successfully_unban": "✅ Usuario desbloqueado correctamente",
"already_banned": "🚫 El usuario ya está bloqueado",
"not_in_ban": "✅ El usuario no está en la lista de bloqueados",
"cfg_mode": "Activar/Desactivar la funcionalidad del bot de retroalimentación",
"cfg_custom_text": "Ingrese texto de saludo personalizado",
"cfg_no_meta": "Ingrese texto personalizado para /nometa",
"cfg_no_meta_baner": "Ingrese el enlace personalizado para el meta-banner",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"mode",
True,
lambda: self.strings["cfg_mode"],
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"start_custom_text",
None,
lambda: self.strings["cfg_custom_text"],
),
loader.ConfigValue(
"no_meta",
None,
lambda: self.strings["cfg_no_meta"],
),
loader.ConfigValue(
"no_meta_baner",
"https://te.legra.ph/file/91a54dee84cf1ec5990fd.jpg",
lambda: self.strings["cfg_no_meta_baner"],
validator=loader.validators.Link(),
),
)
async def on_dlmod(self, client, db):
self.db.set("AuroraFeedBackMod", "ban_list", [])
async def client_ready(self, client, db):
self.forwarding_enabled = {}
self._ban_list = self.db.get("AuroraFeedBackMod", "ban_list")
self._name = utils.escape_html((await client.get_me()).first_name)
self.db.set("AuroraFeedBackMod", "state", "done")
@loader.command(
ru_doc="- Получить ссылку на feedback бота",
uz_doc="- Feedback botga havolani olish",
de_doc="- Erhalten Sie einen Link zum Feedback-Bot",
es_doc="- Obtener un enlace al bot de retroalimentación",
)
async def flink(self, message):
"""- Get a link to the feedback bot"""
slinkbot = f"{self.strings['flink']}: https://t.me/{self.inline.bot_username}?start=AuroraFeedBack"
await utils.answer(message, slinkbot)
@loader.command(
ru_doc="[UserID] - Заблокировать пользователю feedback бота",
uz_doc="[UserID] - Feedback botga foydalanuvchi kirishini bloklang",
de_doc="[UserID] - Blockiere den Zugriff des Benutzers auf den Feedback-Bot",
es_doc="[UserID] - Bloquear el acceso del usuario al bot de retroalimentación",
)
async def banfeedback(self, message):
"""[UserID] - Block the feedback bot user"""
user_id = utils.get_args_raw(message)
if not user_id:
await utils.answer(message, self.strings["not_arg"])
else:
user_id = int(user_id)
if user_id not in self._ban_list:
self._ban_list.append(user_id)
self.db.set("AuroraFeedBackMod", "ban_list", self._ban_list)
await utils.answer(message, self.strings["successfully_ban"])
else:
await utils.answer(message, self.strings["already_banned"])
@loader.command(
ru_doc="[UserID] - Разблокировать пользователю feedback бота",
uz_doc="[UserID] - Feedback bot foydalanuvchisini ochib tashlash",
de_doc="[UserID] - Feedback-Bot-Benutzer entsperren",
es_doc="[UserID] - Desbloquear al usuario del bot de retroalimentación",
)
async def unbanfeedback(self, message):
"""[UserID] - Unblock the feedback bot user"""
user_id = utils.get_args_raw(message)
if not user_id:
await utils.answer(message, self.strings["not_arg"])
else:
user_id = int(user_id)
if user_id in self._ban_list:
self._ban_list.remove(user_id)
self.db.set("AuroraFeedBackMod", "ban_list", self._ban_list)
await utils.answer(message, self.strings["successfully_unban"])
else:
await utils.answer(message, self.strings["not_in_ban"])
async def aiogram_watcher(self, message: AiogramMessage):
if self.config["mode"] is False:
return
if message.from_user.id in list(self.db.get("AuroraFeedBackMod", "ban_list")):
return
if message.text == "/start AuroraFeedBack":
if self.config["start_custom_text"] is None:
text = "Добро пожаловать в Aurora Feedback Bot!\nПожалуйста, ознакомтесь с /nometa"
else:
text = self.config["start_custom_text"]
await message.answer(text)
return
elif message.text == "/nometa":
if self.config["no_meta"] is None:
meta_text = "<b>🫦 Уважаемый пользователь!</b>\nПожалуйста, не задавайте мне вопросы такие, как:\n\n«Привет» , «Какие дела?» , «Что делаешь?» , «Чем занимаешься?» и т.д.\n\nЕсли вы хотите у меня что-то спросить, спрашивайте по делу, а также всю суть вопроса опишите в одном сообщении."
else:
meta_text = self.config["no_meta"]
if self.config["no_meta_baner"] is None:
await self.inline.bot.send_message(
chat_id=message.from_user.id, text=meta_text
)
else:
await self.inline.bot.send_photo(
chat_id=message.from_user.id,
photo=self.config["no_meta_baner"],
caption=meta_text,
)
return
if message.from_user.id == self.tg_id:
state = self.db.get("AuroraFeedBackMod", "state")
if state.startswith("waiting_"):
to_id = int(state.split("_")[1])
waiting_message_id = int(state.split("_")[2])
custom_text = f"{self.strings['owner_answer']}:\n\n{message.text}"
await self.inline.bot.send_message(chat_id=to_id, text=custom_text)
await self.inline.bot.delete_message(
chat_id=message.chat.id, message_id=waiting_message_id
)
await self.inline.bot.send_message(
chat_id=self.tg_id, text=f"{self.strings['successfully_send']}"
)
self.db.set("AuroraFeedBackMod", "state", "done")
return
original_text = message.caption if message.caption else message.text
user_id = message.from_user.id
WriteInPM = f'<b><a href="tg://user?id={user_id}">✏Write in PM</a></b>'
custom_text = f"{self.strings['new_m']} {escape(message.from_user.first_name)}:\n\n{escape(original_text) if original_text is not None else self.strings['not_text']}\n\nUserID: {message.from_user.id}\n{WriteInPM}"
buttons = []
if message.from_user.id != getattr(self, "_tg_id", None):
buttons.append(
[
InlineKeyboardButton(
text="📃 Reply", callback_data=f"reply_{user_id}"
)
]
)
buttons.append(
[InlineKeyboardButton(text="🔐 Ban", callback_data=f"ban_{user_id}")]
)
buttons.append(
[InlineKeyboardButton(text="🗑️ Delete", callback_data=f"MessageDelete")]
)
reply_markup = InlineKeyboardMarkup(inline_keyboard=buttons)
await self.inline.bot.send_message(
chat_id=self.tg_id, text=custom_text, reply_markup=reply_markup
)
await self.inline.bot.send_message(
chat_id=message.from_user.id, text=f"{self.strings['successfully_send']}"
)
async def feedback_callback_handler(self, call: InlineCall):
if call.data == "MessageDelete":
self.inline.ss(call.from_user.id, False)
await self.inline.bot.delete_message(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
)
return
if call.data.startswith("ban_"):
user_id = int(call.data.split("_")[1])
if user_id not in self._ban_list:
self._ban_list.append(user_id)
self.db.set("AuroraFeedBackMod", "ban_list", self._ban_list)
reply_markup = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text="🔓 Unban", callback_data=f"unban_{user_id}"
)
]
]
)
await self.inline.bot.send_message(
chat_id=self.tg_id,
text=f"{self.strings['successfully_ban']} ({user_id})",
reply_markup=reply_markup,
)
return
if call.data.startswith("unban_"):
user_id = int(call.data.split("_")[1])
if user_id in self._ban_list:
self._ban_list.remove(user_id)
self.db.set("AuroraFeedBackMod", "ban_list", self._ban_list)
reply_markup = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text="🔐 Ban", callback_data=f"ban_{user_id}"
)
]
]
)
await self.inline.bot.send_message(
chat_id=self.tg_id,
text=f"{self.strings['successfully_unban']} ({user_id})",
reply_markup=reply_markup,
)
return
if call.data.startswith("reply"):
user_id = int(call.data.split("_")[1])
self.db.set(
"AuroraFeedBackMod",
"state",
f"waiting_{user_id}_{call.message.message_id}",
)
reply_markup = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text="❌ Cancel", callback_data=f"cancel_reply"
)
]
]
)
await self.inline.bot.send_message(
chat_id=self.tg_id,
text=f"{self.strings['waiting_answer']}",
reply_markup=reply_markup,
)
if call.data == "cancel_reply":
self.db.set("AuroraFeedBackMod", "state", "done")
await self.inline.bot.delete_message(
chat_id=call.message.chat.id, message_id=call.message.message_id
)
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: AuroraFeedBack
# Author: Felix? || n3rcy
# Commands:
# .flink | .banfeedback | .unbanfeedback
# scope: hikka_only
# meta developer: @AuroraModules & @nercymods
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/05a519da50f993b950260.jpg
__version__ = (1, 0, 2)
from aiogram.types import Message as AiogramMessage
from aiogram.types import CallbackQuery as AiogramCallbackQuery
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from ..inline.types import InlineCall # type: ignore
from html import escape
from .. import loader, utils
@loader.tds
class AuroraFeedBackMod(loader.Module):
"""Multifunctional feedback bot."""
strings = {
"name": "AuroraFeedBack",
"new_m": "🗣 New message from",
"not_text": "🔎 The text was not found.",
"waiting_answer": "⏳ Waiting for answer to user",
"flink": "Here is my link to the feedback bot",
"owner_answer": "🗣 Owner's Response",
"successfully_send": "💬 Message successfully sent",
"not_arg": "❌ No UserID argument provided",
"successfully_ban": "✅ User successfully banned",
"successfully_unban": "✅ User successfully unbanned",
"already_banned": "🚫 User is already banned",
"not_in_ban": "✅ User is not in the ban list",
"cfg_mode": "Enable/Disable feedback bot functionality",
"cfg_custom_text": "Enter custom greeting text",
"cfg_no_meta": "Enter custom text for /nometa",
"cfg_no_meta_baner": "Enter custom link for meta-banner",
}
strings_ru = {
"new_m": "🗣 Новое сообщение от",
"not_text": "🔎 Текст не найден.",
"waiting_answer": "⏳ Ожидание ответа пользователя",
"flink": "Вот моя ссылка на feedback бота",
"owner_answer": "🗣 Ответ владельца",
"successfully_send": "💬 Сообщение успешно отправлено",
"not_arg": "Не указан UserID",
"successfully_ban": "✅ Пользователь успешно заблокирован",
"successfully_unban": "✅ Пользователь успешно разблокирован",
"already_banned": "🚫 Пользователь уже заблокирован",
"not_in_ban": "✅ Пользователь не находится в списке заблокированных",
"cfg_mode": "Включить/выключить функционал feedback бота",
"cfg_custom_text": "Введите кастомный текст для приветствия",
"cfg_no_meta": "Введите кастомный текст для команды /nometa",
"cfg_no_meta_baner": "Введите кастомную ссылку на мета-баннер",
}
strings_uz = {
"new_m": "🗣 Yangi xabar",
"not_text": "🔎 Matn topilmadi.",
"waiting_answer": "⏳ Foydalanuvchidan javob kutilmoqda",
"flink": "Bu mening feedback botim havolam",
"owner_answer": "🗣 Egasi javobi",
"successfully_send": "💬 Xabar muvaffaqiyatli yuborildi",
"not_arg": "❌ UserID argument kiritilmagan",
"successfully_ban": "✅ Foydalanuvchi muvaffaqiyatli bloklandi",
"successfully_unban": "✅ Foydalanuvchi muvaffaqiyatli ochib tashlandi",
"already_banned": "🚫 Foydalanuvchi allaqachon bloklangan",
"not_in_ban": "✅ Foydalanuvchi blok ro'yxatida yo'q",
"cfg_mode": "Feedback bot funktsiyasini yoqish/yopish",
"cfg_custom_text": "Xush kelibsiz matnini kiriting",
"cfg_no_meta": "/nometa uchun maxsus matnni kiriting",
"cfg_no_meta_baner": "Meta-banner uchun maxsus havolani kiriting",
}
strings_de = {
"new_m": "🗣 Neue Nachricht von",
"not_text": "🔎 Der Text wurde nicht gefunden.",
"waiting_answer": "⏳ Warten auf die Antwort des Benutzers",
"flink": "Hier ist mein Link zum Feedback-Bot",
"owner_answer": "🗣 Antwort des Eigentümers",
"successfully_send": "💬 Nachricht erfolgreich gesendet",
"not_arg": "❌ Kein UserID-Argument angegeben",
"successfully_ban": "✅ Benutzer erfolgreich gesperrt",
"successfully_unban": "✅ Benutzer erfolgreich entsperrt",
"already_banned": "🚫 Benutzer ist bereits gesperrt",
"not_in_ban": "✅ Benutzer befindet sich nicht in der Sperrliste",
"cfg_mode": "Feedback-Bot-Funktionalität aktivieren/deaktivieren",
"cfg_custom_text": "Geben Sie benutzerdefinierten Begrüßungstext ein",
"cfg_no_meta": "Geben Sie benutzerdefinierten Text für /nometa ein",
"cfg_no_meta_baner": "Geben Sie einen benutzerdefinierten Link für den Meta-Banner ein",
}
strings_es = {
"new_m": "🗣 Nuevo mensaje de",
"not_text": "🔎 No se encontró el texto.",
"waiting_answer": "⏳ Esperando la respuesta del usuario",
"flink": "Aquí está mi enlace al bot de retroalimentación",
"owner_answer": "🗣 Respuesta del propietario",
"successfully_send": "💬 Mensaje enviado con éxito",
"not_arg": "❌ No se proporcionó el argumento UserID",
"successfully_ban": "✅ Usuario bloqueado correctamente",
"successfully_unban": "✅ Usuario desbloqueado correctamente",
"already_banned": "🚫 El usuario ya está bloqueado",
"not_in_ban": "✅ El usuario no está en la lista de bloqueados",
"cfg_mode": "Activar/Desactivar la funcionalidad del bot de retroalimentación",
"cfg_custom_text": "Ingrese texto de saludo personalizado",
"cfg_no_meta": "Ingrese texto personalizado para /nometa",
"cfg_no_meta_baner": "Ingrese el enlace personalizado para el meta-banner",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"mode",
True,
lambda: self.strings["cfg_mode"],
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"start_custom_text",
None,
lambda: self.strings["cfg_custom_text"],
),
loader.ConfigValue(
"no_meta",
None,
lambda: self.strings["cfg_no_meta"],
),
loader.ConfigValue(
"no_meta_baner",
"https://te.legra.ph/file/91a54dee84cf1ec5990fd.jpg",
lambda: self.strings["cfg_no_meta_baner"],
validator=loader.validators.Link(),
),
)
async def on_dlmod(self, client, db):
self.db.set("AuroraFeedBackMod", "ban_list", [])
async def client_ready(self, client, db):
self.forwarding_enabled = {}
self._ban_list = self.db.get("AuroraFeedBackMod", "ban_list")
self._name = utils.escape_html((await client.get_me()).first_name)
self.db.set("AuroraFeedBackMod", "state", "done")
@loader.command(
ru_doc="- Получить ссылку на feedback бота",
uz_doc="- Feedback botga havolani olish",
de_doc="- Erhalten Sie einen Link zum Feedback-Bot",
es_doc="- Obtener un enlace al bot de retroalimentación",
)
async def flink(self, message):
"""- Get a link to the feedback bot"""
slinkbot = f"{self.strings['flink']}: https://t.me/{self.inline.bot_username}?start=AuroraFeedBack"
await utils.answer(message, slinkbot)
@loader.command(
ru_doc="[UserID] - Заблокировать пользователю feedback бота",
uz_doc="[UserID] - Feedback botga foydalanuvchi kirishini bloklang",
de_doc="[UserID] - Blockiere den Zugriff des Benutzers auf den Feedback-Bot",
es_doc="[UserID] - Bloquear el acceso del usuario al bot de retroalimentación",
)
async def banfeedback(self, message):
"""[UserID] - Block the feedback bot user"""
user_id = utils.get_args_raw(message)
if not user_id:
await utils.answer(message, self.strings["not_arg"])
else:
user_id = int(user_id)
if user_id not in self._ban_list:
self._ban_list.append(user_id)
self.db.set("AuroraFeedBackMod", "ban_list", self._ban_list)
await utils.answer(message, self.strings["successfully_ban"])
else:
await utils.answer(message, self.strings["already_banned"])
@loader.command(
ru_doc="[UserID] - Разблокировать пользователю feedback бота",
uz_doc="[UserID] - Feedback bot foydalanuvchisini ochib tashlash",
de_doc="[UserID] - Feedback-Bot-Benutzer entsperren",
es_doc="[UserID] - Desbloquear al usuario del bot de retroalimentación",
)
async def unbanfeedback(self, message):
"""[UserID] - Unblock the feedback bot user"""
user_id = utils.get_args_raw(message)
if not user_id:
await utils.answer(message, self.strings["not_arg"])
else:
user_id = int(user_id)
if user_id in self._ban_list:
self._ban_list.remove(user_id)
self.db.set("AuroraFeedBackMod", "ban_list", self._ban_list)
await utils.answer(message, self.strings["successfully_unban"])
else:
await utils.answer(message, self.strings["not_in_ban"])
async def aiogram_watcher(self, message: AiogramMessage):
if self.config["mode"] is False:
return
if message.from_user.id in list(self.db.get("AuroraFeedBackMod", "ban_list")):
return
if message.text == "/start AuroraFeedBack":
if self.config["start_custom_text"] is None:
text = "Добро пожаловать в Aurora Feedback Bot!\nПожалуйста, ознакомтесь с /nometa"
else:
text = self.config["start_custom_text"]
await message.answer(text)
return
elif message.text == "/nometa":
if self.config["no_meta"] is None:
meta_text = "<b>🫦 Уважаемый пользователь!</b>\nПожалуйста, не задавайте мне вопросы такие, как:\n\n«Привет» , «Какие дела?» , «Что делаешь?» , «Чем занимаешься?» и т.д.\n\nЕсли вы хотите у меня что-то спросить, спрашивайте по делу, а также всю суть вопроса опишите в одном сообщении."
else:
meta_text = self.config["no_meta"]
if self.config["no_meta_baner"] is None:
await self.inline.bot.send_message(
chat_id=message.from_user.id, text=meta_text
)
else:
await self.inline.bot.send_photo(
chat_id=message.from_user.id,
photo=self.config["no_meta_baner"],
caption=meta_text,
)
return
if message.from_user.id == self.tg_id:
state = self.db.get("AuroraFeedBackMod", "state")
if state.startswith("waiting_"):
to_id = int(state.split("_")[1])
waiting_message_id = int(state.split("_")[2])
custom_text = f"{self.strings['owner_answer']}:\n\n{message.text}"
await self.inline.bot.send_message(chat_id=to_id, text=custom_text)
await self.inline.bot.delete_message(
chat_id=message.chat.id, message_id=waiting_message_id
)
await self.inline.bot.send_message(
chat_id=self.tg_id, text=f"{self.strings['successfully_send']}"
)
self.db.set("AuroraFeedBackMod", "state", "done")
return
original_text = message.caption if message.caption else message.text
user_id = message.from_user.id
WriteInPM = f'<b><a href="tg://user?id={user_id}">✏Write in PM</a></b>'
custom_text = f"{self.strings['new_m']} {escape(message.from_user.first_name)}:\n\n{escape(original_text) if original_text is not None else self.strings['not_text']}\n\nUserID: {message.from_user.id}\n{WriteInPM}"
buttons = []
if message.from_user.id != getattr(self, "_tg_id", None):
buttons.append(
[
InlineKeyboardButton(
text="📃 Reply", callback_data=f"reply_{user_id}"
)
]
)
buttons.append(
[InlineKeyboardButton(text="🔐 Ban", callback_data=f"ban_{user_id}")]
)
buttons.append(
[InlineKeyboardButton(text="🗑️ Delete", callback_data=f"MessageDelete")]
)
reply_markup = InlineKeyboardMarkup(inline_keyboard=buttons)
await self.inline.bot.send_message(
chat_id=self.tg_id, text=custom_text, reply_markup=reply_markup
)
await self.inline.bot.send_message(
chat_id=message.from_user.id, text=f"{self.strings['successfully_send']}"
)
async def feedback_callback_handler(self, call: InlineCall):
if call.data == "MessageDelete":
self.inline.ss(call.from_user.id, False)
await self.inline.bot.delete_message(
chat_id=call.message.chat.id,
message_id=call.message.message_id,
)
return
if call.data.startswith("ban_"):
user_id = int(call.data.split("_")[1])
if user_id not in self._ban_list:
self._ban_list.append(user_id)
self.db.set("AuroraFeedBackMod", "ban_list", self._ban_list)
reply_markup = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text="🔓 Unban", callback_data=f"unban_{user_id}"
)
]
]
)
await self.inline.bot.send_message(
chat_id=self.tg_id,
text=f"{self.strings['successfully_ban']} ({user_id})",
reply_markup=reply_markup,
)
return
if call.data.startswith("unban_"):
user_id = int(call.data.split("_")[1])
if user_id in self._ban_list:
self._ban_list.remove(user_id)
self.db.set("AuroraFeedBackMod", "ban_list", self._ban_list)
reply_markup = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text="🔐 Ban", callback_data=f"ban_{user_id}"
)
]
]
)
await self.inline.bot.send_message(
chat_id=self.tg_id,
text=f"{self.strings['successfully_unban']} ({user_id})",
reply_markup=reply_markup,
)
return
if call.data.startswith("reply"):
user_id = int(call.data.split("_")[1])
self.db.set(
"AuroraFeedBackMod",
"state",
f"waiting_{user_id}_{call.message.message_id}",
)
reply_markup = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text="❌ Cancel", callback_data=f"cancel_reply"
)
]
]
)
await self.inline.bot.send_message(
chat_id=self.tg_id,
text=f"{self.strings['waiting_answer']}",
reply_markup=reply_markup,
)
if call.data == "cancel_reply":
self.db.set("AuroraFeedBackMod", "state", "done")
await self.inline.bot.delete_message(
chat_id=call.message.chat.id, message_id=call.message.message_id
)

View File

@@ -1,198 +1,198 @@
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: HistoryFacts
# Author: dend1yya
# Commands:
# .rfact | .hfact | .mfact | .sfact
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/388d6138470f2036d08ed.jpg
__version__ = (1, 1, 0)
import json
import aiohttp
import asyncio
import random
from random import choice
from .. import loader, utils
from telethon.tl.types import Message # type: ignore
@loader.tds
class HistoryFactMod(loader.Module):
"""Get a random historical fact"""
strings = {
"name": "HistoryFact",
"fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Random interesting fact about the Great Patriotic War:\n {}</b>",
"adolf_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Random fact about Adolf Hitler:\n{}</b>",
"mussolini_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Random fact about Benito Mussolini:\n{}</b>",
"stalin_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Random fact about Iosif Stalin:\n{}</b>",
"error_key": "<b><i>Error: Key not found.</i></b>",
"error_decoding": "<b><i>Error: The JSON could not be decoded.</i></b>",
"error_uploading_data": "<b><i>Error loading data</i></b>",
"error_valid_args": "<b><i>Please enter valid arguments!</i></b>",
}
strings_ru = {
"fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Случайный интересный факт о Великой Отечественной войне:\n{}</b>",
"adolf_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Случайный факт об Адольфе Гитлере:\n{}</b>",
"mussolini_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Случайный факт о Бенито Муссолини:\n{}</b>",
"stalin_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Случайный факт об Иосифе Сталине:\n{}</b>",
"error_key": "<b><i>Error: ключ не найден.</i></b>",
"error_decoding": "<b><i>Error: не удалось декодировать JSON.</i></b>",
"error_uploading_data": "<b><i>Ошибка при загрузке данных</i></b>",
"error_valid_args": "<b><i>Введите корректные аргументы!</i></b>",
}
strings_uz = {
"fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Buyuk Vatan jangiga oid qiziq fikr:\n{}</b>",
"adolf_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Adolf Gitler haqida tasodifiy fakt:\n{}</b>",
"mussolini_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Benito Mussolini haqida tasodifiy fakt:\n{}</b>",
"stalin_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Iosif Stalin haqida tasodifiy fakt:\n{}</b>",
"error_key": "<b><i>Error: калити топилмади.</i></b>",
"error_decoding": "<b><i>Error: JSON декодлаш муваффақиятли амалга ошмади.</i></b>",
"error_uploading_data": "<b><i>Маълумотлар юклаб олинмади</i></b>",
"error_valid_args": "<b><i>Iltimos, to'g'ri dalillarni kiriting!</i></b>",
}
strings_de = {
"fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Zufällige interessante Tatsache über den Großen Vaterländischen Krieg:\n{}</b>",
"adolf_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Zufällige Tatsache über Adolf Hitler:\n{}</b>",
"mussolini_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Zufällige Tatsache über Benito Mussolini:\n{}</b>",
"stalin_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Zufällige Tatsache über Iosif Stalin:\n{}</b>",
"error_key": "<b><i>Error: Der Schlüssel wurde nicht gefunden.</i></b>",
"error_decoding": "<b><i>Error: JSON konnte nicht decodiert werden.</i></b>",
"error_uploading_data": "<b><i>Fehler beim Hochladen der Daten</i></b>",
"error_valid_args": "<b><i>Bitte geben Sie gültige Argumente ein!</i></b>",
}
strings_es = {
"fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Hecho interesante aleatorio sobre la Gran Guerra Patria:\n{}</b>",
"adolf_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Hecho aleatorio sobre Adolf Hitler:\n{}</b>",
"mussolini_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Hecho aleatorio sobre Benito Mussolini:\n{}</b>",
"stalin_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Hecho aleatorio sobre Iosif Stalin:\n{}</b>",
"error_key": "<b><i>Error: No se encontró la clave.</i></b>",
"error_decoding": "<b><i>Error: No se pudo decodificar JSON.</i></b>",
"error_uploading_data": "<b><i>Error al cargar los datos</i></b>",
"error_valid_args": "<b><i>¡Por favor ingrese argumentos válidos!</i></b>",
}
@loader.command(
ru_doc="Вывод случайного исторического факта",
uz_doc="tasodifiy tarixiy faktlar chiqarish",
de_doc="Gibt eine zufällige historische Tatsache aus",
es_doc="Muestra un hecho histórico aleatorio",
)
async def rfact(self, message):
"""Output a random historical fact"""
url = "https://raw.githubusercontent.com/KorenbZla/HikkaModules/main/HistoryFacts.json"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200:
response_text = await response.text()
try:
data = json.loads(response_text)
if "RandomFact" in data and isinstance(data["RandomFact"], list) and data["RandomFact"]:
text = choice(data["RandomFact"])
await utils.answer(message, self.strings['fact'].format(text))
else:
await utils.answer(message, self.strings["error_key"])
except json.JSONDecodeError:
await utils.answer(message, self.strings["error_decoding"])
else:
await utils.answer(message, f"{self.strings('error_uploading_data')}: {response.status}")
@loader.command(
ru_doc="Вывод случайного факта об Адольфе Гитлере",
uz_doc="Adolf Gitler haqida tasodifiy faktlar chiqarish",
de_doc="Gibt eine zufällige Tatsache über Adolf Hitler aus",
es_doc="Muestra un hecho aleatorio sobre Adolf Hitler",
)
async def hfact(self, message):
"""To deduce a random fact about Adolf Hitler"""
url = "https://raw.githubusercontent.com/KorenbZla/HikkaModules/main/HistoryFacts.json"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200:
response_text = await response.text()
try:
data = json.loads(response_text)
if "AdolfFact" in data and isinstance(data["AdolfFact"], list) and data["AdolfFact"]:
text = choice(data["AdolfFact"])
await utils.answer(message, self.strings['adolf_fact'].format(text))
else:
await utils.answer(message, self.strings["error_key"])
except json.JSONDecodeError:
await utils.answer(message, self.strings["error_decoding"])
else:
await utils.answer(message, f"{self.strings('error_uploading_data')}: {response.status}")
@loader.command(
ru_doc="Вывести случайный факт о Бенито Муссолини",
uz_doc="Benito Mussolini haqida tasodifiy faktlar chiqarish",
de_doc="Gibt eine zufällige Tatsache über Benito Mussolini aus",
es_doc="Muestra un hecho aleatorio sobre Benito Mussolini",
)
async def mfact(self, message):
"""To deduce a random fact about Benito Mussolini"""
url = "https://raw.githubusercontent.com/KorenbZla/HikkaModules/main/HistoryFacts.json"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200:
response_text = await response.text()
try:
data = json.loads(response_text)
if "MussoliniFact" in data and isinstance(data["MussoliniFact"], list) and data["MussoliniFact"]:
text = choice(data["MussoliniFact"])
await utils.answer(message, self.strings['mussolini_fact'].format(text))
else:
await utils.answer(message, self.strings["error_key"])
except json.JSONDecodeError:
await utils.answer(message, self.strings["error_decoding"])
else:
await utils.answer(message, f"{self.strings('error_uploading_data')}: {response.status}")
@loader.command(
ru_doc="Вывести случайный факт о Иосифе Сталине",
uz_doc="Iosif Stalin haqida tasodifiy faktlar chiqarish",
de_doc="Gibt eine zufällige Tatsache über Joseph Stalin aus",
es_doc="Muestra un hecho aleatorio sobre Joseph Stalin",
)
async def sfact(self, message):
"""To deduce a random fact about Joseph Stalin"""
url = "https://raw.githubusercontent.com/KorenbZla/HikkaModules/main/HistoryFacts.json"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200:
response_text = await response.text()
try:
data = json.loads(response_text)
if "StalinFact" in data and isinstance(data["StalinFact"], list) and data["StalinFact"]:
text = choice(data["StalinFact"])
await utils.answer(message, self.strings['stalin_fact'].format(text))
else:
await utils.answer(message, self.strings["error_key"])
except json.JSONDecodeError:
await utils.answer(message, self.strings["error_decoding"])
else:
await utils.answer(message, f"{self.strings('error_uploading_data')}: {response.status}")
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: HistoryFacts
# Author: dend1yya
# Commands:
# .rfact | .hfact | .mfact | .sfact
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/388d6138470f2036d08ed.jpg
__version__ = (1, 1, 0)
import json
import aiohttp
import asyncio
import random
from random import choice
from .. import loader, utils
from telethon.tl.types import Message # type: ignore
@loader.tds
class HistoryFactMod(loader.Module):
"""Get a random historical fact"""
strings = {
"name": "HistoryFact",
"fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Random interesting fact about the Great Patriotic War:\n {}</b>",
"adolf_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Random fact about Adolf Hitler:\n{}</b>",
"mussolini_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Random fact about Benito Mussolini:\n{}</b>",
"stalin_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Random fact about Iosif Stalin:\n{}</b>",
"error_key": "<b><i>Error: Key not found.</i></b>",
"error_decoding": "<b><i>Error: The JSON could not be decoded.</i></b>",
"error_uploading_data": "<b><i>Error loading data</i></b>",
"error_valid_args": "<b><i>Please enter valid arguments!</i></b>",
}
strings_ru = {
"fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Случайный интересный факт о Великой Отечественной войне:\n{}</b>",
"adolf_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Случайный факт об Адольфе Гитлере:\n{}</b>",
"mussolini_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Случайный факт о Бенито Муссолини:\n{}</b>",
"stalin_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Случайный факт об Иосифе Сталине:\n{}</b>",
"error_key": "<b><i>Error: ключ не найден.</i></b>",
"error_decoding": "<b><i>Error: не удалось декодировать JSON.</i></b>",
"error_uploading_data": "<b><i>Ошибка при загрузке данных</i></b>",
"error_valid_args": "<b><i>Введите корректные аргументы!</i></b>",
}
strings_uz = {
"fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Buyuk Vatan jangiga oid qiziq fikr:\n{}</b>",
"adolf_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Adolf Gitler haqida tasodifiy fakt:\n{}</b>",
"mussolini_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Benito Mussolini haqida tasodifiy fakt:\n{}</b>",
"stalin_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Iosif Stalin haqida tasodifiy fakt:\n{}</b>",
"error_key": "<b><i>Error: калити топилмади.</i></b>",
"error_decoding": "<b><i>Error: JSON декодлаш муваффақиятли амалга ошмади.</i></b>",
"error_uploading_data": "<b><i>Маълумотлар юклаб олинмади</i></b>",
"error_valid_args": "<b><i>Iltimos, to'g'ri dalillarni kiriting!</i></b>",
}
strings_de = {
"fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Zufällige interessante Tatsache über den Großen Vaterländischen Krieg:\n{}</b>",
"adolf_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Zufällige Tatsache über Adolf Hitler:\n{}</b>",
"mussolini_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Zufällige Tatsache über Benito Mussolini:\n{}</b>",
"stalin_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Zufällige Tatsache über Iosif Stalin:\n{}</b>",
"error_key": "<b><i>Error: Der Schlüssel wurde nicht gefunden.</i></b>",
"error_decoding": "<b><i>Error: JSON konnte nicht decodiert werden.</i></b>",
"error_uploading_data": "<b><i>Fehler beim Hochladen der Daten</i></b>",
"error_valid_args": "<b><i>Bitte geben Sie gültige Argumente ein!</i></b>",
}
strings_es = {
"fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Hecho interesante aleatorio sobre la Gran Guerra Patria:\n{}</b>",
"adolf_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Hecho aleatorio sobre Adolf Hitler:\n{}</b>",
"mussolini_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Hecho aleatorio sobre Benito Mussolini:\n{}</b>",
"stalin_fact": "<b><emoji document_id=5386596911463541476>📚</emoji> Hecho aleatorio sobre Iosif Stalin:\n{}</b>",
"error_key": "<b><i>Error: No se encontró la clave.</i></b>",
"error_decoding": "<b><i>Error: No se pudo decodificar JSON.</i></b>",
"error_uploading_data": "<b><i>Error al cargar los datos</i></b>",
"error_valid_args": "<b><i>¡Por favor ingrese argumentos válidos!</i></b>",
}
@loader.command(
ru_doc="Вывод случайного исторического факта",
uz_doc="tasodifiy tarixiy faktlar chiqarish",
de_doc="Gibt eine zufällige historische Tatsache aus",
es_doc="Muestra un hecho histórico aleatorio",
)
async def rfact(self, message):
"""Output a random historical fact"""
url = "https://raw.githubusercontent.com/KorenbZla/HikkaModules/main/HistoryFacts.json"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200:
response_text = await response.text()
try:
data = json.loads(response_text)
if "RandomFact" in data and isinstance(data["RandomFact"], list) and data["RandomFact"]:
text = choice(data["RandomFact"])
await utils.answer(message, self.strings['fact'].format(text))
else:
await utils.answer(message, self.strings["error_key"])
except json.JSONDecodeError:
await utils.answer(message, self.strings["error_decoding"])
else:
await utils.answer(message, f"{self.strings('error_uploading_data')}: {response.status}")
@loader.command(
ru_doc="Вывод случайного факта об Адольфе Гитлере",
uz_doc="Adolf Gitler haqida tasodifiy faktlar chiqarish",
de_doc="Gibt eine zufällige Tatsache über Adolf Hitler aus",
es_doc="Muestra un hecho aleatorio sobre Adolf Hitler",
)
async def hfact(self, message):
"""To deduce a random fact about Adolf Hitler"""
url = "https://raw.githubusercontent.com/KorenbZla/HikkaModules/main/HistoryFacts.json"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200:
response_text = await response.text()
try:
data = json.loads(response_text)
if "AdolfFact" in data and isinstance(data["AdolfFact"], list) and data["AdolfFact"]:
text = choice(data["AdolfFact"])
await utils.answer(message, self.strings['adolf_fact'].format(text))
else:
await utils.answer(message, self.strings["error_key"])
except json.JSONDecodeError:
await utils.answer(message, self.strings["error_decoding"])
else:
await utils.answer(message, f"{self.strings('error_uploading_data')}: {response.status}")
@loader.command(
ru_doc="Вывести случайный факт о Бенито Муссолини",
uz_doc="Benito Mussolini haqida tasodifiy faktlar chiqarish",
de_doc="Gibt eine zufällige Tatsache über Benito Mussolini aus",
es_doc="Muestra un hecho aleatorio sobre Benito Mussolini",
)
async def mfact(self, message):
"""To deduce a random fact about Benito Mussolini"""
url = "https://raw.githubusercontent.com/KorenbZla/HikkaModules/main/HistoryFacts.json"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200:
response_text = await response.text()
try:
data = json.loads(response_text)
if "MussoliniFact" in data and isinstance(data["MussoliniFact"], list) and data["MussoliniFact"]:
text = choice(data["MussoliniFact"])
await utils.answer(message, self.strings['mussolini_fact'].format(text))
else:
await utils.answer(message, self.strings["error_key"])
except json.JSONDecodeError:
await utils.answer(message, self.strings["error_decoding"])
else:
await utils.answer(message, f"{self.strings('error_uploading_data')}: {response.status}")
@loader.command(
ru_doc="Вывести случайный факт о Иосифе Сталине",
uz_doc="Iosif Stalin haqida tasodifiy faktlar chiqarish",
de_doc="Gibt eine zufällige Tatsache über Joseph Stalin aus",
es_doc="Muestra un hecho aleatorio sobre Joseph Stalin",
)
async def sfact(self, message):
"""To deduce a random fact about Joseph Stalin"""
url = "https://raw.githubusercontent.com/KorenbZla/HikkaModules/main/HistoryFacts.json"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200:
response_text = await response.text()
try:
data = json.loads(response_text)
if "StalinFact" in data and isinstance(data["StalinFact"], list) and data["StalinFact"]:
text = choice(data["StalinFact"])
await utils.answer(message, self.strings['stalin_fact'].format(text))
else:
await utils.answer(message, self.strings["error_key"])
except json.JSONDecodeError:
await utils.answer(message, self.strings["error_decoding"])
else:
await utils.answer(message, f"{self.strings('error_uploading_data')}: {response.status}")

View File

@@ -1,335 +1,335 @@
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: RPSgame
# Author: Felix
# Commands:
# .sgamerps (.rps) | .cleargames (.clg)
# scope: hikka_only
# meta developer: @AuroraModules
__version__ = (1, 0, 0)
import time
import random
from .. import loader, utils
from telethon.utils import get_display_name # type: ignore
class RPSgameMod(loader.Module):
"""With this module, you can play the game «rock, paper, scissors»."""
strings = {
"name": "RPSgame",
"searching": "<b>✌️ The game «Rock, Paper, Scissors» begins!\n👀 Waiting for a second player to join...</b>",
"join_game": "👾 Join the game",
"rules": "📄 Game rules",
"game_started": "⚠ The game has already started",
"game_already_running": "<emoji document_id=5255772095958229697>🤚</emoji> <b>Oops, a game is already running, use </b><code>{}cleargames</code><b> to end all active games.</b>",
"games_cleared": "<emoji document_id=6007942490076745785>🧹</emoji> <b>All active games have been ended and cleared.</b>",
"turn": "<b>🕹 The game has started!\n👀 The first turn goes to {}</b>!",
"next_player": "<b>😱 It's {}'s turn next</b>",
"not_your_turn": "⚠ It's not your turn!",
"not_player": "❌ You're not participating in the game",
"cooldown": "⚠ Not so fast!",
"winner": "<b>🎉 Winner: {}</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> chose: {}</b> \n<b>👤<a href='tg://openmessage?user_id={}'>{}</a> chose: {}</b>",
"draw": "<b>🤝 It's a draw!</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> chose: {}</b>\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> chose: {}</b>",
"error_play_yourself": "⚠ You can't play against yourself",
"rock": "🪨 Rock",
"scissors": "✂️ Scissors",
"paper": "📄 Paper",
"random": "🎲 Random choice",
"close_button": "🔻 Close",
}
strings_ru = {
"searching": "<b>✌️ Игра «Камень, ножницы, бумага» начинается!\n👀 Ожидание, присоединение 2 игрока...</b>",
"join_game": "👾 Присоединиться к игре",
"rules": "📄 Правила игры",
"game_started": "⚠ Игра уже началась",
"game_already_running": "<emoji document_id=5255772095958229697>🤚</emoji> <b>Упс, игра уже запущена, используйте </b><code>{}cleargames</code><b>, чтобы завершить все начатые игры.</b>",
"games_cleared": "<emoji document_id=6007942490076745785>🧹</emoji> <b>Все активные игры были завершены и очищены.</b>",
"turn": "<b>🕹 Игра началась!\n👀 Первый ход за {}</b>!",
"next_player": "<b>😱 Следующий ходит {}</b>",
"not_your_turn": "⚠ Это не ваш ход!",
"not_player": "❌ Вы не участвуете в игре",
"cooldown": "Не так быстро!",
"winner": "<b>🎉 Победитель: {}</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> выбрал: {}</b> \n<b>👤<a href='tg://openmessage?user_id={}'>{}</a> выбрал: {}</b>",
"draw": "<b>🤝 Ничья!</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> выбрал: {}</b>\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> выбрал: {}</b>",
"error_play_yourself": "⚠ Вы не можете играть с самим сабой",
"rock": "🪨 Камень",
"scissors": "✂️ Ножницы",
"paper": "📄 Бумага",
"random": "🎲 Случайный выбор",
"close_button": "🔻 Закрыть",
}
strings_uz = {
"searching": "<b>✌️ «Qog'oz, Qaychi, Tosh» o'yini boshlanmoqda!\n👀 Ikkinchi o'yinchi kutilmoqda...</b>",
"join_game": "👾 O'yinga qo'shilish",
"rules": "📄 O'yin qoidalari",
"game_started": "⚠ O'yin allaqachon boshlangan",
"game_already_running": "<emoji document_id=5255772095958229697>🤚</emoji> <b>Oops, o'yin allaqachon boshlangan, </b><code>{}cleargames</code><b> buyruqni ishlating, barcha o'yinlarni tugatish uchun.</b>",
"games_cleared": "<emoji document_id=6007942490076745785>🧹</emoji> <b>Barcha faol o'yinlar tugatildi va tozalandi.</b>",
"turn": "<b>🕹 O'yin boshlandi!\n👀 Birinchi yurish {}</b>!",
"next_player": "<b>😱 Keyingi yurish {} da</b>",
"not_your_turn": "⚠ Bu sizning navbatingiz emas!",
"not_player": "❌ Siz o'yinda emassiz",
"cooldown": "⚠ Shoshilmang!",
"winner": "<b>🎉 G'olib: {}</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> tanladi: {}</b> \n<b>👤<a href='tg://openmessage?user_id={}'>{}</a> tanladi: {}</b>",
"draw": "<b>🤝 Durrang!</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> tanladi: {}</b>\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> tanladi: {}</b>",
"error_play_yourself": "⚠ O'zingiz bilan o'ynay olmaysiz",
"rock": "🪨 Tosh",
"scissors": "✂️ Qaychi",
"paper": "📄 Qog'oz",
"random": "🎲 Tasodifiy tanlash",
"close_button": "🔻 Yopish",
}
strings_de = {
"searching": "<b>✌️ Das Spiel «Schere, Stein, Papier» beginnt!\n👀 Warte auf den zweiten Spieler...</b>",
"join_game": "👾 Dem Spiel beitreten",
"rules": "📄 Spielregeln",
"game_started": "⚠ Das Spiel hat bereits begonnen",
"game_already_running": "<emoji document_id=5255772095958229697>🤚</emoji> <b>Ups, ein Spiel läuft bereits, benutze </b><code>{}cleargames</code><b>, um alle aktiven Spiele zu beenden.</b>",
"games_cleared": "<emoji document_id=6007942490076745785>🧹</emoji> <b>Alle aktiven Spiele wurden beendet und gelöscht.</b>",
"turn": "<b>🕹 Das Spiel hat begonnen!\n👀 Der erste Zug geht an {}</b>!",
"next_player": "<b>😱 Der nächste Zug geht an {}</b>",
"not_your_turn": "⚠ Es ist nicht dein Zug!",
"not_player": "❌ Du nimmst nicht am Spiel teil",
"cooldown": "⚠ Nicht so schnell!",
"winner": "<b>🎉 Gewinner: {}</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> wählte: {}</b> \n<b>👤<a href='tg://openmessage?user_id={}'>{}</a> wählte: {}</b>",
"draw": "<b>🤝 Unentschieden!</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> wählte: {}</b>\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> wählte: {}</b>",
"error_play_yourself": "⚠ Du kannst nicht gegen dich selbst spielen",
"rock": "🪨 Stein",
"scissors": "✂️ Schere",
"paper": "📄 Papier",
"random": "🎲 Zufällige Wahl",
"close_button": "🔻 Schließen",
}
strings_es = {
"searching": "<b>✌️ El juego «Piedra, Papel, Tijeras» comienza!\n👀 Esperando que se una un segundo jugador...</b>",
"join_game": "👾 Unirse al juego",
"rules": "📄 Reglas del juego",
"game_started": "⚠ El juego ya ha comenzado",
"game_already_running": "<emoji document_id=5255772095958229697>🤚</emoji> <b>Ups, un juego ya está en marcha, usa </b><code>{}cleargames</code><b> para terminar todos los juegos activos.</b>",
"games_cleared": "<emoji document_id=6007942490076745785>🧹</emoji> <b>Todos los juegos activos han sido terminados y eliminados.</b>",
"turn": "<b>🕹 ¡El juego ha comenzado!\n👀 El primer turno es para {}</b>!",
"next_player": "<b>😱 El siguiente turno es para {}</b>",
"not_your_turn": "⚠ ¡No es tu turno!",
"not_player": "❌ No estás participando en el juego",
"cooldown": "⚠ ¡No tan rápido!",
"winner": "<b>🎉 Ganador: {}</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> eligió: {}</b> \n<b>👤<a href='tg://openmessage?user_id={}'>{}</a> eligió: {}</b>",
"draw": "<b>🤝 ¡Empate!</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> eligió: {}</b>\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> eligió: {}</b>",
"error_play_yourself": "⚠ No puedes jugar contra ti mismo",
"rock": "🪨 Piedra",
"scissors": "✂️ Tijeras",
"paper": "📄 Papel",
"random": "🎲 Elección aleatoria",
"close_button": "🔻 Cerrar",
}
def __init__(self):
self.games = {}
self.last_click_time = {}
@loader.command(
ru_doc="- Начать игру «Камень, ножницы, бумага»",
uz_doc="- «Tosh, qog'oz, qaychi» o'yinining boshlanishi",
de_doc="- Beginn des Spiels «Stein, Papier, Schere»",
es_doc="- El comienzo del juego «Piedra, papel o tijera»",
alias="rps"
)
async def sgamerps(self, message):
"""- Start the game «Rock, Paper, Scissors»"""
chat_id = message.chat_id
player1_id = message.sender_id
game_id = f"{chat_id}_{player1_id}"
prefix = utils.escape_html(self.get_prefix())
if game_id in self.games:
await utils.answer(message, self.strings["game_already_running"].format(prefix))
return
self.games[game_id] = {
"player1": player1_id,
"player2": None,
"choices": {},
"current_turn": None,
}
await self.inline.form(
message=message,
text=self.strings["searching"],
reply_markup=[
[
{"text": self.strings['rules'], "url": "https://ru.wikipedia.org/wiki/Камень,_ножницы,_бумагаравилагры:~:text=Победитель%20определяется%20по%20следующим%20правилам%3A"}
],
[
{"text": self.strings['join_game'], "callback": self.join_game, "args": (game_id,),}
],
],
disable_security=True,
)
async def join_game(self, call, game_id: str):
game = self.games.get(game_id)
player2_id = call.from_user.id
current_time = time.time()
if player2_id in self.last_click_time and current_time - self.last_click_time[player2_id] < 3:
await call.answer(self.strings["cooldown"])
return
self.last_click_time[player2_id] = current_time
if game["player1"] == player2_id:
await call.answer(self.strings["error_play_yourself"])
return
if game["player2"] is not None:
await call.answer(self.strings["game_started"])
return
game["player2"] = player2_id
game["current_turn"] = random.choice([game["player1"], game["player2"]])
await call.edit(
text=self.strings["turn"].format(
get_display_name(await self._client.get_entity(game["current_turn"]))
),
reply_markup=[
[
{"text": self.strings["rock"], "callback": self.make_choice, "args": (game_id, "rock")},
{"text": self.strings["scissors"], "callback": self.make_choice, "args": (game_id, "scissors")},
{"text": self.strings["paper"], "callback": self.make_choice, "args": (game_id, "paper")},
],
[
{"text": self.strings["random"], "callback": self.make_choice, "args": (game_id, "random")},
],
]
)
async def make_choice(self, call, game_id: str, choice: str):
game = self.games.get(game_id)
current_time = time.time()
if call.from_user.id in self.last_click_time and current_time - self.last_click_time[call.from_user.id] < 2:
await call.answer(self.strings["cooldown"])
return
self.last_click_time[call.from_user.id] = current_time
if call.from_user.id not in [game["player1"], game["player2"]]:
await call.answer(self.strings["not_player"])
return
is_random = choice == "random"
if is_random:
choice = random.choice(["rock", "scissors", "paper"])
game["choices"][call.from_user.id] = (choice, "random" if is_random else None)
if len(game["choices"]) == 2:
await self.resolve_game(call, game_id)
else:
game["current_turn"] = game["player1"] if call.from_user.id == game["player2"] else game["player2"]
next_player = get_display_name(await self._client.get_entity(game['current_turn']))
await call.edit(
text=self.strings['next_player'].format(next_player),
reply_markup=[
[
{"text": self.strings["rock"], "callback": self.make_choice, "args": (game_id, "rock")},
{"text": self.strings["scissors"], "callback": self.make_choice, "args": (game_id, "scissors")},
{"text": self.strings["paper"], "callback": self.make_choice, "args": (game_id, "paper")},
],
[
{"text": self.strings["random"], "callback": self.make_choice, "args": (game_id, "random")},
],
]
)
async def resolve_game(self, call, game_id: str):
game = self.games.get(game_id)
if not game:
return
player1_id = game["player1"]
player2_id = game["player2"]
player1_choice, player1_random = game["choices"].get(player1_id, (None, None))
player2_choice, player2_random = game["choices"].get(player2_id, (None, None))
if player1_choice is None or player2_choice is None:
return
player1_choice_text = self.strings[player1_choice]
player2_choice_text = self.strings[player2_choice]
if player1_random:
player1_choice_text += " [🎲RANDOM]"
if player2_random:
player2_choice_text += " [🎲RANDOM]"
if player1_choice == player2_choice:
result_message = self.strings["draw"].format(
player1_id,
utils.escape_html(get_display_name(await self._client.get_entity(player1_id))),
player1_choice_text,
player2_id,
utils.escape_html(get_display_name(await self._client.get_entity(player2_id))),
player2_choice_text,
)
else:
winning_conditions = {
"rock": "scissors",
"scissors": "paper",
"paper": "rock"
}
winner_id = player1_id if winning_conditions[player1_choice] == player2_choice else player2_id
result_message = self.strings["winner"].format(
utils.escape_html(get_display_name(await self._client.get_entity(winner_id))),
winner_id,
utils.escape_html(get_display_name(await self._client.get_entity(player1_id))),
player1_choice_text,
player2_id,
utils.escape_html(get_display_name(await self._client.get_entity(player2_id))),
player2_choice_text,
)
await call.edit(text=result_message, reply_markup=[
[
{"text": self.strings["close_button"], "callback": self.call_del},
]
])
del self.games[game_id]
async def call_del(self, call):
await call.delete()
@loader.command(
ru_doc=f"- Завершить все активные игры.",
uz_doc="- Barcha faol o'yinlarni tugatish.",
de_doc="- Alle aktiven Spiele beenden.",
es_doc="- Completar todos los juegos en curso.",
alias="clg"
)
async def cleargames(self, message):
"""- Complete all running games."""
self.games.clear()
await utils.answer(message, self.strings["games_cleared"])
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: RPSgame
# Author: Felix
# Commands:
# .sgamerps (.rps) | .cleargames (.clg)
# scope: hikka_only
# meta developer: @AuroraModules
__version__ = (1, 0, 0)
import time
import random
from .. import loader, utils
from telethon.utils import get_display_name # type: ignore
class RPSgameMod(loader.Module):
"""With this module, you can play the game «rock, paper, scissors»."""
strings = {
"name": "RPSgame",
"searching": "<b>✌️ The game «Rock, Paper, Scissors» begins!\n👀 Waiting for a second player to join...</b>",
"join_game": "👾 Join the game",
"rules": "📄 Game rules",
"game_started": "⚠ The game has already started",
"game_already_running": "<emoji document_id=5255772095958229697>🤚</emoji> <b>Oops, a game is already running, use </b><code>{}cleargames</code><b> to end all active games.</b>",
"games_cleared": "<emoji document_id=6007942490076745785>🧹</emoji> <b>All active games have been ended and cleared.</b>",
"turn": "<b>🕹 The game has started!\n👀 The first turn goes to {}</b>!",
"next_player": "<b>😱 It's {}'s turn next</b>",
"not_your_turn": "⚠ It's not your turn!",
"not_player": "❌ You're not participating in the game",
"cooldown": "⚠ Not so fast!",
"winner": "<b>🎉 Winner: {}</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> chose: {}</b> \n<b>👤<a href='tg://openmessage?user_id={}'>{}</a> chose: {}</b>",
"draw": "<b>🤝 It's a draw!</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> chose: {}</b>\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> chose: {}</b>",
"error_play_yourself": "⚠ You can't play against yourself",
"rock": "🪨 Rock",
"scissors": "✂️ Scissors",
"paper": "📄 Paper",
"random": "🎲 Random choice",
"close_button": "🔻 Close",
}
strings_ru = {
"searching": "<b>✌️ Игра «Камень, ножницы, бумага» начинается!\n👀 Ожидание, присоединение 2 игрока...</b>",
"join_game": "👾 Присоединиться к игре",
"rules": "📄 Правила игры",
"game_started": "⚠ Игра уже началась",
"game_already_running": "<emoji document_id=5255772095958229697>🤚</emoji> <b>Упс, игра уже запущена, используйте </b><code>{}cleargames</code><b>, чтобы завершить все начатые игры.</b>",
"games_cleared": "<emoji document_id=6007942490076745785>🧹</emoji> <b>Все активные игры были завершены и очищены.</b>",
"turn": "<b>🕹 Игра началась!\n👀 Первый ход за {}</b>!",
"next_player": "<b>😱 Следующий ходит {}</b>",
"not_your_turn": "⚠ Это не ваш ход!",
"not_player": "❌ Вы не участвуете в игре",
"cooldown": "Не так быстро!",
"winner": "<b>🎉 Победитель: {}</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> выбрал: {}</b> \n<b>👤<a href='tg://openmessage?user_id={}'>{}</a> выбрал: {}</b>",
"draw": "<b>🤝 Ничья!</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> выбрал: {}</b>\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> выбрал: {}</b>",
"error_play_yourself": "⚠ Вы не можете играть с самим сабой",
"rock": "🪨 Камень",
"scissors": "✂️ Ножницы",
"paper": "📄 Бумага",
"random": "🎲 Случайный выбор",
"close_button": "🔻 Закрыть",
}
strings_uz = {
"searching": "<b>✌️ «Qog'oz, Qaychi, Tosh» o'yini boshlanmoqda!\n👀 Ikkinchi o'yinchi kutilmoqda...</b>",
"join_game": "👾 O'yinga qo'shilish",
"rules": "📄 O'yin qoidalari",
"game_started": "⚠ O'yin allaqachon boshlangan",
"game_already_running": "<emoji document_id=5255772095958229697>🤚</emoji> <b>Oops, o'yin allaqachon boshlangan, </b><code>{}cleargames</code><b> buyruqni ishlating, barcha o'yinlarni tugatish uchun.</b>",
"games_cleared": "<emoji document_id=6007942490076745785>🧹</emoji> <b>Barcha faol o'yinlar tugatildi va tozalandi.</b>",
"turn": "<b>🕹 O'yin boshlandi!\n👀 Birinchi yurish {}</b>!",
"next_player": "<b>😱 Keyingi yurish {} da</b>",
"not_your_turn": "⚠ Bu sizning navbatingiz emas!",
"not_player": "❌ Siz o'yinda emassiz",
"cooldown": "⚠ Shoshilmang!",
"winner": "<b>🎉 G'olib: {}</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> tanladi: {}</b> \n<b>👤<a href='tg://openmessage?user_id={}'>{}</a> tanladi: {}</b>",
"draw": "<b>🤝 Durrang!</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> tanladi: {}</b>\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> tanladi: {}</b>",
"error_play_yourself": "⚠ O'zingiz bilan o'ynay olmaysiz",
"rock": "🪨 Tosh",
"scissors": "✂️ Qaychi",
"paper": "📄 Qog'oz",
"random": "🎲 Tasodifiy tanlash",
"close_button": "🔻 Yopish",
}
strings_de = {
"searching": "<b>✌️ Das Spiel «Schere, Stein, Papier» beginnt!\n👀 Warte auf den zweiten Spieler...</b>",
"join_game": "👾 Dem Spiel beitreten",
"rules": "📄 Spielregeln",
"game_started": "⚠ Das Spiel hat bereits begonnen",
"game_already_running": "<emoji document_id=5255772095958229697>🤚</emoji> <b>Ups, ein Spiel läuft bereits, benutze </b><code>{}cleargames</code><b>, um alle aktiven Spiele zu beenden.</b>",
"games_cleared": "<emoji document_id=6007942490076745785>🧹</emoji> <b>Alle aktiven Spiele wurden beendet und gelöscht.</b>",
"turn": "<b>🕹 Das Spiel hat begonnen!\n👀 Der erste Zug geht an {}</b>!",
"next_player": "<b>😱 Der nächste Zug geht an {}</b>",
"not_your_turn": "⚠ Es ist nicht dein Zug!",
"not_player": "❌ Du nimmst nicht am Spiel teil",
"cooldown": "⚠ Nicht so schnell!",
"winner": "<b>🎉 Gewinner: {}</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> wählte: {}</b> \n<b>👤<a href='tg://openmessage?user_id={}'>{}</a> wählte: {}</b>",
"draw": "<b>🤝 Unentschieden!</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> wählte: {}</b>\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> wählte: {}</b>",
"error_play_yourself": "⚠ Du kannst nicht gegen dich selbst spielen",
"rock": "🪨 Stein",
"scissors": "✂️ Schere",
"paper": "📄 Papier",
"random": "🎲 Zufällige Wahl",
"close_button": "🔻 Schließen",
}
strings_es = {
"searching": "<b>✌️ El juego «Piedra, Papel, Tijeras» comienza!\n👀 Esperando que se una un segundo jugador...</b>",
"join_game": "👾 Unirse al juego",
"rules": "📄 Reglas del juego",
"game_started": "⚠ El juego ya ha comenzado",
"game_already_running": "<emoji document_id=5255772095958229697>🤚</emoji> <b>Ups, un juego ya está en marcha, usa </b><code>{}cleargames</code><b> para terminar todos los juegos activos.</b>",
"games_cleared": "<emoji document_id=6007942490076745785>🧹</emoji> <b>Todos los juegos activos han sido terminados y eliminados.</b>",
"turn": "<b>🕹 ¡El juego ha comenzado!\n👀 El primer turno es para {}</b>!",
"next_player": "<b>😱 El siguiente turno es para {}</b>",
"not_your_turn": "⚠ ¡No es tu turno!",
"not_player": "❌ No estás participando en el juego",
"cooldown": "⚠ ¡No tan rápido!",
"winner": "<b>🎉 Ganador: {}</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> eligió: {}</b> \n<b>👤<a href='tg://openmessage?user_id={}'>{}</a> eligió: {}</b>",
"draw": "<b>🤝 ¡Empate!</b>\n\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> eligió: {}</b>\n<b>👤 <a href='tg://openmessage?user_id={}'>{}</a> eligió: {}</b>",
"error_play_yourself": "⚠ No puedes jugar contra ti mismo",
"rock": "🪨 Piedra",
"scissors": "✂️ Tijeras",
"paper": "📄 Papel",
"random": "🎲 Elección aleatoria",
"close_button": "🔻 Cerrar",
}
def __init__(self):
self.games = {}
self.last_click_time = {}
@loader.command(
ru_doc="- Начать игру «Камень, ножницы, бумага»",
uz_doc="- «Tosh, qog'oz, qaychi» o'yinining boshlanishi",
de_doc="- Beginn des Spiels «Stein, Papier, Schere»",
es_doc="- El comienzo del juego «Piedra, papel o tijera»",
alias="rps"
)
async def sgamerps(self, message):
"""- Start the game «Rock, Paper, Scissors»"""
chat_id = message.chat_id
player1_id = message.sender_id
game_id = f"{chat_id}_{player1_id}"
prefix = utils.escape_html(self.get_prefix())
if game_id in self.games:
await utils.answer(message, self.strings["game_already_running"].format(prefix))
return
self.games[game_id] = {
"player1": player1_id,
"player2": None,
"choices": {},
"current_turn": None,
}
await self.inline.form(
message=message,
text=self.strings["searching"],
reply_markup=[
[
{"text": self.strings['rules'], "url": "https://ru.wikipedia.org/wiki/Камень,_ножницы,_бумагаравилагры:~:text=Победитель%20определяется%20по%20следующим%20правилам%3A"}
],
[
{"text": self.strings['join_game'], "callback": self.join_game, "args": (game_id,),}
],
],
disable_security=True,
)
async def join_game(self, call, game_id: str):
game = self.games.get(game_id)
player2_id = call.from_user.id
current_time = time.time()
if player2_id in self.last_click_time and current_time - self.last_click_time[player2_id] < 3:
await call.answer(self.strings["cooldown"])
return
self.last_click_time[player2_id] = current_time
if game["player1"] == player2_id:
await call.answer(self.strings["error_play_yourself"])
return
if game["player2"] is not None:
await call.answer(self.strings["game_started"])
return
game["player2"] = player2_id
game["current_turn"] = random.choice([game["player1"], game["player2"]])
await call.edit(
text=self.strings["turn"].format(
get_display_name(await self._client.get_entity(game["current_turn"]))
),
reply_markup=[
[
{"text": self.strings["rock"], "callback": self.make_choice, "args": (game_id, "rock")},
{"text": self.strings["scissors"], "callback": self.make_choice, "args": (game_id, "scissors")},
{"text": self.strings["paper"], "callback": self.make_choice, "args": (game_id, "paper")},
],
[
{"text": self.strings["random"], "callback": self.make_choice, "args": (game_id, "random")},
],
]
)
async def make_choice(self, call, game_id: str, choice: str):
game = self.games.get(game_id)
current_time = time.time()
if call.from_user.id in self.last_click_time and current_time - self.last_click_time[call.from_user.id] < 2:
await call.answer(self.strings["cooldown"])
return
self.last_click_time[call.from_user.id] = current_time
if call.from_user.id not in [game["player1"], game["player2"]]:
await call.answer(self.strings["not_player"])
return
is_random = choice == "random"
if is_random:
choice = random.choice(["rock", "scissors", "paper"])
game["choices"][call.from_user.id] = (choice, "random" if is_random else None)
if len(game["choices"]) == 2:
await self.resolve_game(call, game_id)
else:
game["current_turn"] = game["player1"] if call.from_user.id == game["player2"] else game["player2"]
next_player = get_display_name(await self._client.get_entity(game['current_turn']))
await call.edit(
text=self.strings['next_player'].format(next_player),
reply_markup=[
[
{"text": self.strings["rock"], "callback": self.make_choice, "args": (game_id, "rock")},
{"text": self.strings["scissors"], "callback": self.make_choice, "args": (game_id, "scissors")},
{"text": self.strings["paper"], "callback": self.make_choice, "args": (game_id, "paper")},
],
[
{"text": self.strings["random"], "callback": self.make_choice, "args": (game_id, "random")},
],
]
)
async def resolve_game(self, call, game_id: str):
game = self.games.get(game_id)
if not game:
return
player1_id = game["player1"]
player2_id = game["player2"]
player1_choice, player1_random = game["choices"].get(player1_id, (None, None))
player2_choice, player2_random = game["choices"].get(player2_id, (None, None))
if player1_choice is None or player2_choice is None:
return
player1_choice_text = self.strings[player1_choice]
player2_choice_text = self.strings[player2_choice]
if player1_random:
player1_choice_text += " [🎲RANDOM]"
if player2_random:
player2_choice_text += " [🎲RANDOM]"
if player1_choice == player2_choice:
result_message = self.strings["draw"].format(
player1_id,
utils.escape_html(get_display_name(await self._client.get_entity(player1_id))),
player1_choice_text,
player2_id,
utils.escape_html(get_display_name(await self._client.get_entity(player2_id))),
player2_choice_text,
)
else:
winning_conditions = {
"rock": "scissors",
"scissors": "paper",
"paper": "rock"
}
winner_id = player1_id if winning_conditions[player1_choice] == player2_choice else player2_id
result_message = self.strings["winner"].format(
utils.escape_html(get_display_name(await self._client.get_entity(winner_id))),
winner_id,
utils.escape_html(get_display_name(await self._client.get_entity(player1_id))),
player1_choice_text,
player2_id,
utils.escape_html(get_display_name(await self._client.get_entity(player2_id))),
player2_choice_text,
)
await call.edit(text=result_message, reply_markup=[
[
{"text": self.strings["close_button"], "callback": self.call_del},
]
])
del self.games[game_id]
async def call_del(self, call):
await call.delete()
@loader.command(
ru_doc=f"- Завершить все активные игры.",
uz_doc="- Barcha faol o'yinlarni tugatish.",
de_doc="- Alle aktiven Spiele beenden.",
es_doc="- Completar todos los juegos en curso.",
alias="clg"
)
async def cleargames(self, message):
"""- Complete all running games."""
self.games.clear()
await utils.answer(message, self.strings["games_cleared"])

View File

@@ -1,109 +1,109 @@
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: RandomAvatars
# Author: Felix?
# Commands:
# .rpavatars
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/64b1e88536b3ba59c94da.jpg
__version__ = (1, 3, 0)
import os
import logging
from .. import loader, utils
from telethon.tl.functions.channels import JoinChannelRequest # type: ignore
logger = logging.getLogger("RandomAvatars")
@loader.tds
class RandomAvatars(loader.Module):
strings = {
"name": "RandomAvatars",
"loading_avatars": "<emoji document_id=5215327832040811010>⏳</emoji> <b>loading the avatars</b>",
"error_loading": "<b>Failed to get avatars. Please check the PM with the bot @anime_4bot</b>",
}
strings_ru = {
"loading_avatars": "<emoji document_id=5215327832040811010>⏳</emoji> <b>загрузка аватарок</b>",
"error_loading": "<b>Не удалось получить аватарки. Пожалуйста проверьте ЛС с ботом @anime_4bot</b>",
}
strings_uz = {
"loading_avatars": "<emoji document_id=5215327832040811010>⏳</emoji> <b>avatarlarni yuklash</b>",
"error_loading": "<b>Avatarlar olinmadi. Iltimos, PMni @anime_4bot boti bilan tekshiring</b>",
}
strings_de= {
"loading_avatars": "<emoji document_id=5215327832040811010>⏳</emoji> <b>Laden der Avatare</b>",
"error_loading": "<b>Avatare konnten nicht abgerufen werden. Bitte überprüfen Sie die PM mit dem Bot @anime_4bot</b>",
}
strings_es = {
"loading_avatars": "<emoji document_id=5215327832040811010>⏳</emoji> <b>cargando los avatares</b>",
"error_loading": "<b>No se pudieron obtener avatares. Por favor revisa el MP con el bot @anime_4bot</b>",
}
@loader.command(
ru_doc="Поиск случайных парных аватарок",
uz_doc="Tasodifiy juftlashtirilgan avatarlarni qidiring",
de_doc="Suchen Sie nach zufällig gepaarten Avataren",
es_doc="Buscar avatares emparejados aleatoriamente",
)
async def rpavatars(self, message):
"""random paired avatars"""
try:
channel_a = "https://t.me/anime4_avatarki"
channel_b = "https://t.me/anime4_arts"
await self.client(JoinChannelRequest(channel_a))
await self.client(JoinChannelRequest(channel_b))
except Exception:
logger.error("Error when subscribing to channels.")
await utils.answer(message, self.strings("loading_avatars"))
async with self._client.conversation("@anime_4bot") as conv:
await conv.send_message("🎎 Парные аватарки")
response1 = await conv.get_response()
if response1.photo:
media1 = await self._client.download_media(response1.photo, "avatars")
response2 = await conv.get_response()
if response2.photo:
media2 = await self._client.download_media(response2.photo, "avatars")
await message.client.send_message(
message.peer_id,
file=media1,
)
await message.client.send_message(
message.peer_id,
file=media2,
)
os.remove(media1)
os.remove(media2)
await message.delete()
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: RandomAvatars
# Author: Felix?
# Commands:
# .rpavatars
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/64b1e88536b3ba59c94da.jpg
__version__ = (1, 3, 0)
import os
import logging
from .. import loader, utils
from telethon.tl.functions.channels import JoinChannelRequest # type: ignore
logger = logging.getLogger("RandomAvatars")
@loader.tds
class RandomAvatars(loader.Module):
strings = {
"name": "RandomAvatars",
"loading_avatars": "<emoji document_id=5215327832040811010>⏳</emoji> <b>loading the avatars</b>",
"error_loading": "<b>Failed to get avatars. Please check the PM with the bot @anime_4bot</b>",
}
strings_ru = {
"loading_avatars": "<emoji document_id=5215327832040811010>⏳</emoji> <b>загрузка аватарок</b>",
"error_loading": "<b>Не удалось получить аватарки. Пожалуйста проверьте ЛС с ботом @anime_4bot</b>",
}
strings_uz = {
"loading_avatars": "<emoji document_id=5215327832040811010>⏳</emoji> <b>avatarlarni yuklash</b>",
"error_loading": "<b>Avatarlar olinmadi. Iltimos, PMni @anime_4bot boti bilan tekshiring</b>",
}
strings_de= {
"loading_avatars": "<emoji document_id=5215327832040811010>⏳</emoji> <b>Laden der Avatare</b>",
"error_loading": "<b>Avatare konnten nicht abgerufen werden. Bitte überprüfen Sie die PM mit dem Bot @anime_4bot</b>",
}
strings_es = {
"loading_avatars": "<emoji document_id=5215327832040811010>⏳</emoji> <b>cargando los avatares</b>",
"error_loading": "<b>No se pudieron obtener avatares. Por favor revisa el MP con el bot @anime_4bot</b>",
}
@loader.command(
ru_doc="Поиск случайных парных аватарок",
uz_doc="Tasodifiy juftlashtirilgan avatarlarni qidiring",
de_doc="Suchen Sie nach zufällig gepaarten Avataren",
es_doc="Buscar avatares emparejados aleatoriamente",
)
async def rpavatars(self, message):
"""random paired avatars"""
try:
channel_a = "https://t.me/anime4_avatarki"
channel_b = "https://t.me/anime4_arts"
await self.client(JoinChannelRequest(channel_a))
await self.client(JoinChannelRequest(channel_b))
except Exception:
logger.error("Error when subscribing to channels.")
await utils.answer(message, self.strings("loading_avatars"))
async with self._client.conversation("@anime_4bot") as conv:
await conv.send_message("🎎 Парные аватарки")
response1 = await conv.get_response()
if response1.photo:
media1 = await self._client.download_media(response1.photo, "avatars")
response2 = await conv.get_response()
if response2.photo:
media2 = await self._client.download_media(response2.photo, "avatars")
await message.client.send_message(
message.peer_id,
file=media1,
)
await message.client.send_message(
message.peer_id,
file=media2,
)
os.remove(media1)
os.remove(media2)
await message.delete()

View File

@@ -1,96 +1,96 @@
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: RandomNumber
# Author: Felix?
# Commands:
# .RandomNumber
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/f35de08579b3bd2235bc4.jpg
__version__ = (1, 0, 1)
import random
from telethon.tl.types import Message # type: ignore
from .. import loader, utils
@loader.tds
class RandomNumberMod(loader.Module):
"""Random numbers generator"""
strings = {
"name": "RandomNumber",
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>The number dropped</b>",
"cfg_Number_Min": "Minimum number to be drawn",
"cfg_Number_Max": "Maximum number rolled",
}
strings_ru = {
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>Выпало число</b>",
"cfg_Number_Min": "Минимальное число в выпадении",
"cfg_Number_Max": "Максимальное число в выпадении",
}
strings_uz = {
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>Chiqqan raqam</b>",
"cfg_Number_Min": "Chiqqan eng kichik raqam",
"cfg_Number_Max": "Chiqqan eng katta raqam",
}
strings_de = {
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>Die Zahl ist gefallen</b>",
"cfg_Number_Min": "Mindestanzahl beim Wurf",
"cfg_Number_Max": "Maximale Anzahl beim Wurf",
}
strings_es = {
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>El número ha caído</b>",
"cfg_Number_Min": "Número mínimo en la caída",
"cfg_Number_Max": "Número máximo en la caída",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"Number_Min",
0,
lambda: self.strings["cfg_Number_Min"],
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Number_Max",
1000,
lambda: self.strings["cfg_Number_Max"],
validator=loader.validators.Integer(),
),
)
@loader.command(
ru_doc="Случайное число",
uz_doc="Tasodifiy raqam",
de_doc="Zufallszahl",
es_doc="Número aleatorio",
)
async def RandomNumber(self, message: Message):
"""Random number"""
min_number = min(self.config["Number_Min"], self.config["Number_Max"])
max_number = max(self.config["Number_Min"], self.config["Number_Max"])
Number = random.randint(min_number, max_number)
result = Number
await utils.answer(message, f"{self.strings('rnumber')}: {result}")
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: RandomNumber
# Author: Felix?
# Commands:
# .RandomNumber
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/f35de08579b3bd2235bc4.jpg
__version__ = (1, 0, 1)
import random
from telethon.tl.types import Message # type: ignore
from .. import loader, utils
@loader.tds
class RandomNumberMod(loader.Module):
"""Random numbers generator"""
strings = {
"name": "RandomNumber",
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>The number dropped</b>",
"cfg_Number_Min": "Minimum number to be drawn",
"cfg_Number_Max": "Maximum number rolled",
}
strings_ru = {
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>Выпало число</b>",
"cfg_Number_Min": "Минимальное число в выпадении",
"cfg_Number_Max": "Максимальное число в выпадении",
}
strings_uz = {
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>Chiqqan raqam</b>",
"cfg_Number_Min": "Chiqqan eng kichik raqam",
"cfg_Number_Max": "Chiqqan eng katta raqam",
}
strings_de = {
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>Die Zahl ist gefallen</b>",
"cfg_Number_Min": "Mindestanzahl beim Wurf",
"cfg_Number_Max": "Maximale Anzahl beim Wurf",
}
strings_es = {
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>El número ha caído</b>",
"cfg_Number_Min": "Número mínimo en la caída",
"cfg_Number_Max": "Número máximo en la caída",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"Number_Min",
0,
lambda: self.strings["cfg_Number_Min"],
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Number_Max",
1000,
lambda: self.strings["cfg_Number_Max"],
validator=loader.validators.Integer(),
),
)
@loader.command(
ru_doc="Случайное число",
uz_doc="Tasodifiy raqam",
de_doc="Zufallszahl",
es_doc="Número aleatorio",
)
async def RandomNumber(self, message: Message):
"""Random number"""
min_number = min(self.config["Number_Min"], self.config["Number_Max"])
max_number = max(self.config["Number_Min"], self.config["Number_Max"])
Number = random.randint(min_number, max_number)
result = Number
await utils.answer(message, f"{self.strings('rnumber')}: {result}")

View File

@@ -1,224 +1,224 @@
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: Randomizer
# Author: dend1yya | Felix?
# Commands:
# .cube | .monetka | .rnum
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/201288f407537011ce0ed.jpg
__version__ = (1, 1, 1)
import random
import asyncio
from telethon.tl.types import Message # type: ignore
from .. import loader, utils
@loader.tds
class RandomizerMod(loader.Module):
"""Module for playing with dice, heads/tails and other games."""
strings = {
"name": "Randomizer",
"invalid_number": "🚫 <b>Invalid number! Please choose a number between 1 and 6.</b>",
"rolled": "🎲 <b>Rolled the cube, got:</b> <code>{}</code>",
"win": "🎉 <b>Congratulations! You guessed it right!</b>",
"lose": "😞 <b>Sorry, you didn't guess it right. Try again!</b>",
"invalid_monetka": "🚫 <b>Invalid choice! Please choose 'Heads' or 'Tails'.</b>",
"flipping": "🔄 <b>Flipping the coin...</b>",
"flipped": "🪙 <b>Coin flipped, it's:</b> <code>{}</code>",
"cfg_Number_Min": "Minimum number to be drawn",
"cfg_Number_Max": "Maximum number rolled",
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>The number dropped</b>",
"error_min": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: Value is less than the minimum number from the configuration.</b>",
"error_max": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: Value is greater than the maximum number from the configuration.",
"invalid_rnumber": "🚫 <b>The number is specified incorrectly or is not a number.</b>",
}
strings_ru = {
"invalid_number": "🚫<b>Указано неверное число! Пожалуйста выберите число от 1 до 6.</b>",
"rolled": "🎲<b>Подробсил кубик и получил:</b> <code>{}</code>",
"win": "🎉<b>Поздравляем! Вы выйграли</b>",
"lose": "😞<b>Вы проиграли, вы загадали неверное число. Попробуйте ещё раз!</b>",
"invalid_monetka": "🚫<b>Неверный выбор! Пожалуйста выберите 'орёл' или 'решка'</b>",
"flipping": "🔄<b>Подрбасываю монетку...</b>",
"flipped": "🪙<b>Монетка подброшена, выпало:</b> <code>{}</code>",
"cfg_Number_Min": "Минимальное число в выпадении",
"cfg_Number_Max": "Максимальное число в выпадении",
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>Выпало число</b>",
"error_min": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: Значение меньше минимального числа из конфигурации.</b>",
"error_max": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: Значение больше максимального числа из конфигурации.</b>",
"invalid_rnumber": "🚫 <b>Число указано неправильно или не является им.</b>",
}
strings_uz = {
"invalid_number": "🚫<b>Noto'g'ri raqam kiritildi! Iltimos, 1 dan 6 gacha bo'lgan bir raqam tanlang.</b>",
"rolled": "🎲<b>Zar ni chiqarib oldi:</b> <code>{}</code>",
"win": "🎉<b>Tabriklaymiz! Siz yutdingiz</b>",
"lose": "😞<b>Siz yo'qotdingiz, siz noto'g'ri raqam o'yladiz. Qaytadan urinib ko'ring!</b>",
"invalid_monetka": "🚫<b>Noto'g'ri tanlov! Iltimos, 'to'g' va 'yuqori' tanlang</b>",
"flipping": "🔄<b>Yig'ishni zarba shaklida qilmoqda...</b>",
"flipped": "🪙<b>Zarba qilindi, natija:</b> <code>{}</code>",
"cfg_Number_Min": "Chiqqan eng kichik raqam",
"cfg_Number_Max": "Chiqqan eng katta raqam",
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>Chiqqan raqam</b>",
"error_min": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: Qiymat sozlamadan minimal sonidan kichik.</b>",
"error_max": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: Qiymat sozlamadan maksimal sonidan katta.</b>",
"invalid_rnumber": "🚫 <b>Raqam noto'g'ri kiritilgan yoki u raqam emas.</b>",
}
strings_de = {
"invalid_number": "🚫<b>Ungültige Zahl angegeben! Bitte wählen Sie eine Zahl zwischen 1 und 6.</b>",
"rolled": "🎲<b>Der Würfel wurde geworfen und ergab:</b> <code>{}</code>",
"win": "🎉<b>Herzlichen Glückwunsch! Sie haben gewonnen</b>",
"lose": "😞<b>Sie haben verloren, Sie haben eine falsche Zahl erraten. Versuchen Sie es erneut!</b>",
"invalid_monetka": "🚫<b>Falsche Auswahl! Bitte wählen Sie 'Kopf' oder 'Zahl'</b>",
"flipping": "🔄<b>Die Münze wird geworfen...</b>",
"flipped": "🪙<b>Die Münze wurde geworfen, das Ergebnis ist:</b> <code>{}</code>",
"cfg_Number_Min": "Mindestanzahl beim Wurf",
"cfg_Number_Max": "Maximale Anzahl beim Wurf",
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>Die Zahl ist gefallen</b>",
"error_min": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: Wert ist kleiner als die minimale Zahl in der Konfiguration.</b>",
"error_max": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: Wert ist größer als die maximale Zahl in der Konfiguration.</b>",
"invalid_rnumber": "🚫 <b>Die Zahl ist falsch angegeben oder keine Zahl.</b>",
}
strings_es = {
"invalid_number": "🚫<b>¡Número invalido especificado! Por favor elige un número entre 1 y 6.</b>",
"rolled": "🎲<b>El dado fue lanzado y obtuvo:</b> <code>{}</code>",
"win": "🎉<b>¡Felicidades! Has ganado</b>",
"lose": "😞<b>Has perdido, has adivinado un número incorrecto. ¡Inténtalo de nuevo!</b>",
"invalid_monetka": "🚫<b>¡Selección no válida! Por favor elige 'cara' o 'cruz'</b>",
"flipping": "🔄<b>Lanzando la moneda...</b>",
"flipped": "🪙<b>La moneda ha sido lanzada, el resultado es:</b> <code>{}</code>",
"cfg_Number_Min": "Número mínimo en la caída",
"cfg_Number_Max": "Número máximo en la caída",
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>El número ha caído</b>",
"error_min": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: El valor es menor que el número mínimo de la configuración.</b>",
"error_max": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: El valor es mayor que el número máximo de la configuración.</b>",
"invalid_rnumber": "🚫 <b>El número está especificado incorrectamente o no es un número.</b>",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"Number_Min",
0,
lambda: self.strings["cfg_Number_Min"],
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Number_Max",
10,
lambda: self.strings["cfg_Number_Max"],
validator=loader.validators.Integer(),
),
)
@loader.command(
ru_doc="[0-6] - Бросить кубик с числом",
uz_doc="[0-6] - Son bilan zar tashlash",
de_doc="[0-6] - Würfeln mit einer Zahl",
es_doc="[0-6] - Tirar un dado con un número",
)
async def cube(self, message: Message):
"""[0-6] - Roll a dice with a number"""
args = utils.get_args_raw(message)
try:
guessed_number = int(args)
except ValueError:
await utils.answer(message, self.strings("invalid_number"))
return
if not (1 <= guessed_number <= 6):
await utils.answer(message, self.strings("invalid_number"))
return
result = random.randint(1, 6)
await utils.answer(message, self.strings("rolled").format(result))
await asyncio.sleep(2)
if guessed_number == result:
await utils.answer(message, self.strings("win"))
else:
await utils.answer(message, self.strings("lose"))
@loader.command(
ru_doc="[орёл/решка] - Подбрасывает монетку, и выдает случайный результат",
uz_doc="[орёл/решка] - Chiqqan va tasodifiy natijani ko'rsatadi",
de_doc="[орёл/решка] - Wirft eine Münze und gibt ein zufälliges Ergebnis aus",
es_doc="[орёл/решка] - Voltea una moneda y da un resultado aleatorio",
)
async def monetka(self, message: Message):
"""[орёл/решка] - Flips a coin and gives a random result"""
args = utils.get_args_raw(message)
if args not in ["орёл", "решка"]:
await utils.answer(message, self.strings("invalid_monetka"))
return
animated_text = self.strings("flipping")
animated_message = await utils.answer(message, animated_text)
await asyncio.sleep(1)
result = random.choice(["орёл", "решка"])
await animated_message.edit(self.strings("flipped").format(result))
await asyncio.sleep(2)
if args == result:
await utils.answer(message, self.strings("win"))
else:
await utils.answer(message, self.strings("lose"))
@loader.command(
ru_doc="[number] - Случайное число",
uz_doc="[number] - Tasodifiy raqam",
de_doc="[number] - Zufallszahl",
es_doc="[number] - Número aleatorio",
)
async def rnum(self, message: Message):
"""[number] - Random number"""
args = utils.get_args_raw(message)
min_number = min(self.config["Number_Min"], self.config["Number_Max"])
max_number = max(self.config["Number_Min"], self.config["Number_Max"])
try:
number_guess = int(args)
except ValueError:
await utils.answer(message, self.strings("invalid_rnumber"))
return
if number_guess < min_number:
await utils.answer(message, self.strings["error_min"])
return
elif number_guess > max_number:
await utils.answer(message, self.strings("error_max"))
return
Number = random.randint(min_number, max_number)
result = Number
await utils.answer(message, f"{self.strings('rnumber')}: {result}")
if number_guess == result:
await asyncio.sleep(1.3)
await utils.answer(message, self.strings("win"))
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: Randomizer
# Author: dend1yya | Felix?
# Commands:
# .cube | .monetka | .rnum
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/201288f407537011ce0ed.jpg
__version__ = (1, 1, 1)
import random
import asyncio
from telethon.tl.types import Message # type: ignore
from .. import loader, utils
@loader.tds
class RandomizerMod(loader.Module):
"""Module for playing with dice, heads/tails and other games."""
strings = {
"name": "Randomizer",
"invalid_number": "🚫 <b>Invalid number! Please choose a number between 1 and 6.</b>",
"rolled": "🎲 <b>Rolled the cube, got:</b> <code>{}</code>",
"win": "🎉 <b>Congratulations! You guessed it right!</b>",
"lose": "😞 <b>Sorry, you didn't guess it right. Try again!</b>",
"invalid_monetka": "🚫 <b>Invalid choice! Please choose 'Heads' or 'Tails'.</b>",
"flipping": "🔄 <b>Flipping the coin...</b>",
"flipped": "🪙 <b>Coin flipped, it's:</b> <code>{}</code>",
"cfg_Number_Min": "Minimum number to be drawn",
"cfg_Number_Max": "Maximum number rolled",
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>The number dropped</b>",
"error_min": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: Value is less than the minimum number from the configuration.</b>",
"error_max": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: Value is greater than the maximum number from the configuration.",
"invalid_rnumber": "🚫 <b>The number is specified incorrectly or is not a number.</b>",
}
strings_ru = {
"invalid_number": "🚫<b>Указано неверное число! Пожалуйста выберите число от 1 до 6.</b>",
"rolled": "🎲<b>Подробсил кубик и получил:</b> <code>{}</code>",
"win": "🎉<b>Поздравляем! Вы выйграли</b>",
"lose": "😞<b>Вы проиграли, вы загадали неверное число. Попробуйте ещё раз!</b>",
"invalid_monetka": "🚫<b>Неверный выбор! Пожалуйста выберите 'орёл' или 'решка'</b>",
"flipping": "🔄<b>Подрбасываю монетку...</b>",
"flipped": "🪙<b>Монетка подброшена, выпало:</b> <code>{}</code>",
"cfg_Number_Min": "Минимальное число в выпадении",
"cfg_Number_Max": "Максимальное число в выпадении",
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>Выпало число</b>",
"error_min": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: Значение меньше минимального числа из конфигурации.</b>",
"error_max": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: Значение больше максимального числа из конфигурации.</b>",
"invalid_rnumber": "🚫 <b>Число указано неправильно или не является им.</b>",
}
strings_uz = {
"invalid_number": "🚫<b>Noto'g'ri raqam kiritildi! Iltimos, 1 dan 6 gacha bo'lgan bir raqam tanlang.</b>",
"rolled": "🎲<b>Zar ni chiqarib oldi:</b> <code>{}</code>",
"win": "🎉<b>Tabriklaymiz! Siz yutdingiz</b>",
"lose": "😞<b>Siz yo'qotdingiz, siz noto'g'ri raqam o'yladiz. Qaytadan urinib ko'ring!</b>",
"invalid_monetka": "🚫<b>Noto'g'ri tanlov! Iltimos, 'to'g' va 'yuqori' tanlang</b>",
"flipping": "🔄<b>Yig'ishni zarba shaklida qilmoqda...</b>",
"flipped": "🪙<b>Zarba qilindi, natija:</b> <code>{}</code>",
"cfg_Number_Min": "Chiqqan eng kichik raqam",
"cfg_Number_Max": "Chiqqan eng katta raqam",
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>Chiqqan raqam</b>",
"error_min": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: Qiymat sozlamadan minimal sonidan kichik.</b>",
"error_max": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: Qiymat sozlamadan maksimal sonidan katta.</b>",
"invalid_rnumber": "🚫 <b>Raqam noto'g'ri kiritilgan yoki u raqam emas.</b>",
}
strings_de = {
"invalid_number": "🚫<b>Ungültige Zahl angegeben! Bitte wählen Sie eine Zahl zwischen 1 und 6.</b>",
"rolled": "🎲<b>Der Würfel wurde geworfen und ergab:</b> <code>{}</code>",
"win": "🎉<b>Herzlichen Glückwunsch! Sie haben gewonnen</b>",
"lose": "😞<b>Sie haben verloren, Sie haben eine falsche Zahl erraten. Versuchen Sie es erneut!</b>",
"invalid_monetka": "🚫<b>Falsche Auswahl! Bitte wählen Sie 'Kopf' oder 'Zahl'</b>",
"flipping": "🔄<b>Die Münze wird geworfen...</b>",
"flipped": "🪙<b>Die Münze wurde geworfen, das Ergebnis ist:</b> <code>{}</code>",
"cfg_Number_Min": "Mindestanzahl beim Wurf",
"cfg_Number_Max": "Maximale Anzahl beim Wurf",
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>Die Zahl ist gefallen</b>",
"error_min": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: Wert ist kleiner als die minimale Zahl in der Konfiguration.</b>",
"error_max": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: Wert ist größer als die maximale Zahl in der Konfiguration.</b>",
"invalid_rnumber": "🚫 <b>Die Zahl ist falsch angegeben oder keine Zahl.</b>",
}
strings_es = {
"invalid_number": "🚫<b>¡Número invalido especificado! Por favor elige un número entre 1 y 6.</b>",
"rolled": "🎲<b>El dado fue lanzado y obtuvo:</b> <code>{}</code>",
"win": "🎉<b>¡Felicidades! Has ganado</b>",
"lose": "😞<b>Has perdido, has adivinado un número incorrecto. ¡Inténtalo de nuevo!</b>",
"invalid_monetka": "🚫<b>¡Selección no válida! Por favor elige 'cara' o 'cruz'</b>",
"flipping": "🔄<b>Lanzando la moneda...</b>",
"flipped": "🪙<b>La moneda ha sido lanzada, el resultado es:</b> <code>{}</code>",
"cfg_Number_Min": "Número mínimo en la caída",
"cfg_Number_Max": "Número máximo en la caída",
"rnumber": "<emoji document_id=5285372392086976148>🦋</emoji> <b>El número ha caído</b>",
"error_min": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: El valor es menor que el número mínimo de la configuración.</b>",
"error_max": "<emoji document_id=5287611315588707430>❌</emoji> <b>Error: El valor es mayor que el número máximo de la configuración.</b>",
"invalid_rnumber": "🚫 <b>El número está especificado incorrectamente o no es un número.</b>",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"Number_Min",
0,
lambda: self.strings["cfg_Number_Min"],
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Number_Max",
10,
lambda: self.strings["cfg_Number_Max"],
validator=loader.validators.Integer(),
),
)
@loader.command(
ru_doc="[0-6] - Бросить кубик с числом",
uz_doc="[0-6] - Son bilan zar tashlash",
de_doc="[0-6] - Würfeln mit einer Zahl",
es_doc="[0-6] - Tirar un dado con un número",
)
async def cube(self, message: Message):
"""[0-6] - Roll a dice with a number"""
args = utils.get_args_raw(message)
try:
guessed_number = int(args)
except ValueError:
await utils.answer(message, self.strings("invalid_number"))
return
if not (1 <= guessed_number <= 6):
await utils.answer(message, self.strings("invalid_number"))
return
result = random.randint(1, 6)
await utils.answer(message, self.strings("rolled").format(result))
await asyncio.sleep(2)
if guessed_number == result:
await utils.answer(message, self.strings("win"))
else:
await utils.answer(message, self.strings("lose"))
@loader.command(
ru_doc="[орёл/решка] - Подбрасывает монетку, и выдает случайный результат",
uz_doc="[орёл/решка] - Chiqqan va tasodifiy natijani ko'rsatadi",
de_doc="[орёл/решка] - Wirft eine Münze und gibt ein zufälliges Ergebnis aus",
es_doc="[орёл/решка] - Voltea una moneda y da un resultado aleatorio",
)
async def monetka(self, message: Message):
"""[орёл/решка] - Flips a coin and gives a random result"""
args = utils.get_args_raw(message)
if args not in ["орёл", "решка"]:
await utils.answer(message, self.strings("invalid_monetka"))
return
animated_text = self.strings("flipping")
animated_message = await utils.answer(message, animated_text)
await asyncio.sleep(1)
result = random.choice(["орёл", "решка"])
await animated_message.edit(self.strings("flipped").format(result))
await asyncio.sleep(2)
if args == result:
await utils.answer(message, self.strings("win"))
else:
await utils.answer(message, self.strings("lose"))
@loader.command(
ru_doc="[number] - Случайное число",
uz_doc="[number] - Tasodifiy raqam",
de_doc="[number] - Zufallszahl",
es_doc="[number] - Número aleatorio",
)
async def rnum(self, message: Message):
"""[number] - Random number"""
args = utils.get_args_raw(message)
min_number = min(self.config["Number_Min"], self.config["Number_Max"])
max_number = max(self.config["Number_Min"], self.config["Number_Max"])
try:
number_guess = int(args)
except ValueError:
await utils.answer(message, self.strings("invalid_rnumber"))
return
if number_guess < min_number:
await utils.answer(message, self.strings["error_min"])
return
elif number_guess > max_number:
await utils.answer(message, self.strings("error_max"))
return
Number = random.randint(min_number, max_number)
result = Number
await utils.answer(message, f"{self.strings('rnumber')}: {result}")
if number_guess == result:
await asyncio.sleep(1.3)
await utils.answer(message, self.strings("win"))

View File

@@ -1,236 +1,236 @@
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: Reports
# Author: dend1yya
# Commands:
# .addadmins | .chaton | .chatoff | .report
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/5131a980bd2f80ad463ad.jpg
__version__ = (1, 0, 0)
from hikkatl.types import Message # type: ignore
from telethon.tl.functions.channels import InviteToChannelRequest # type: ignore
from telethon.tl.functions.users import GetFullUserRequest #type: ignore
from telethon.tl.functions.channels import CreateChannelRequest, InviteToChannelRequest #type: ignore
from telethon.tl.types import ChatAdminRights #type: ignore
from .. import loader, utils
import logging
logger = logging.getLogger(__name__)
@loader.tds
class ReportsMod(loader.Module):
"""Module for sending reports to the administration."""
strings = {
"name": "Reports",
"admin_id": "ADMIN_ID",
"loading": "<b>Loading...</b>",
"group_created": "<b>Report Channel accessed and admin(s) invited if specified.</b>",
"group_error": "<b>Error accessing the report channel.</b>",
"no_admins": "<b>No admins configered to ivnite.</b>",
"reports_enabled": "Report reception enabled in this chat.",
"reports_disabled": "Report reception disabled in this chat.",
"reports_not_enabled": "<b>Reports not enabled in this chat.</b>",
"not_args": "<b>Usage: .report {userID/@username} (reason)</b>",
"parts_both_2": "<b>Please provide both a user and a reason.</b>",
"success": "<b>Report submitted successfully.</b>",
"fail": "<b>Failed to submit the report.</b>",
}
strings_ru = {
"admin_id": "ADMIN_ID",
"loading": "<b>Загрузка...</b>",
"group_created": "<b>Группа для репортов создана, и администраторы были приглашены.</b>",
"group_error": "<b>Ошибка при создании канала с репортами.",
"no_admins": "<b>Нету администраторов которых можно добавить в группу.</b>",
"reports_enabled": "<b>Репорты включены в этом чате</b>",
"reports_disabled": "<b>Репорты выключены в этом чате</b>",
"reports_not_enabled": "<b>Репорты не включены в этом чате.</b>",
"not_args": "<b>Использование: .report{userID/@username} (причина)</b>",
"parts_both_2": "<b>Пожалуйста введите имя пользователя и причину.</b>",
"success": "<b>Репорт успешно отправлен.</b>",
"fail": "<b>Ошибка при отправке репорта.</b>"
}
strings_uz = {
"admin_id": "ADMIN_ID",
"loading": "<b>Yuklanmoqda...</b>",
"group_created": "<b>Hisobot kanali ochildi va agar ko'rsatilgan bo'lsa, administrator(lar) taklif qilindi.</b>",
"group_error": "<b>Hisobot kanaliga kirishda xato yuz berdi.</b>",
"no_admins": "<b>Taklif qilish uchun administratorlar mavjud emas.</b>",
"reports_enabled": "<b>Hisobot qabul qilish ushbu chatda yoqilgan.</b>",
"reports_disabled": "<b>Hisobot qabul qilish ushbu chatda o'chirilgan.</b>",
"reports_not_enabled": "<b>Hisobot ushbu chatda yoqilmagan.</b>",
"not_args": "<b>Foydalanish: .report {userID/@username} (sababi)</b>",
"parts_both_2": "<b>Iltimos, foydalanuvchi va sababni taqdim eting.</b>",
"success": "<b>Hisobot muvaffaqiyatli yuborildi.</b>",
"fail": "<b>Hisobot yuborishda xato yuz berdi.</b>",
}
strings_de = {
"admin_id": "ADMIN_ID",
"loading": "<b>Wird geladen...</b>",
"group_created": "<b>Berichtskanal aufgerufen und Administrator(en) eingeladen, falls angegeben.</b>",
"group_error": "<b>Fehler beim Zugreifen auf den Berichtskanal.</b>",
"no_admins": "<b>Keine Administratoren konfiguriert, um einzuladen.</b>",
"reports_enabled": "<b>Berichtserfassung in diesem Chat aktiviert.</b>",
"reports_disabled": "<b>Berichtserfassung in diesem Chat deaktiviert.</b>",
"reports_not_enabled": "<b>Berichte in diesem Chat nicht aktiviert.</b>",
"not_args": "<b>Verwendung: .report {userID/@username} (Grund)</b>",
"parts_both_2": "<b>Bitte sowohl einen Benutzer als auch einen Grund angeben.</b>",
"success": "<b>Bericht erfolgreich eingereicht.</b>",
"fail": "<b>Fehler beim Einreichen des Berichts.</b>",
}
strings_es = {
"admin_id": "ADMIN_ID",
"loading": "<b>Cargando...</b>",
"group_created": "<b>Canal de informes accedido y administrador(es) invitado(s) si se especificó.</b>",
"group_error": "<b>Error al acceder al canal de informes.</b>",
"no_admins": "<b>No hay administradores configurados para invitar.</b>",
"reports_enabled": "<b>Recepción de informes habilitada en este chat.</b>",
"reports_disabled": "<b>Recepción de informes deshabilitada en este chat.</b>",
"reports_not_enabled": "<b>Los informes no están habilitados en este chat.</b>",
"not_args": "<b>Uso: .report {userID/@username} (razón)</b>",
"parts_both_2": "<b>Por favor, proporcione tanto un usuario como una razón.</b>",
"success": "<b>Informe enviado con éxito.</b>",
"fail": "<b>Error al enviar el informe.</b>",
}
def __init__(self):
self.config = loader.ModuleConfig(
"admin_id",
None,
lambda: self.strings["admin_id"]
)
async def client_ready(self, client, db):
self.client = client
self.db = db
try:
result = await client(CreateChannelRequest(
title="Aurora-Reports",
about="🐬 chat for reports from users",
megagroup=True
))
self.Aurora_Reports = result.chats[0]
except Exception as e:
logger.error(f"Failed to create report group: {str(e)}")
@loader.command(
ru_doc="Добавить администраторов из конфигурации в группу.",
uz_doc="Konfiguratsiyadan administratorlarni guruhga qo'shadi.",
de_doc="Fügt Administratoren aus der Konfiguration zur Gruppe hinzu.",
es_doc="Agrega administradores desde la configuración al grupo.",
)
async def addadmins(self, message):
"""Add administrators from the config to the group"""
await utils.answer(message, self.strings["loading"])
try:
admin_ids = self.config.get("admin_id")
if not admin_ids:
await utils.answer(message, self.strings["no_admins"])
return
if isinstance(admin_ids, list):
for admin_id in admin_ids:
await self.client(InviteToChannelRequest(
channel=self.Aurora_Reports,
users=[admin_id]
))
else:
await self.client(InviteToChannelRequest(
channel=self.Aurora_Reports,
users=[admin_ids]
))
await utils.answer(message, self.strings["group_created"])
except Exception as e:
logger.error(f"Failed to invite admins to the report group: {str(e)}")
await utils.answer(message, self.strings["group_error"])
@loader.command(
ru_doc="Включает чат для репортов.",
uz_doc="Hisobotlar uchun chatni yoqadi.",
de_doc="Aktiviert den Chat für Berichte.",
es_doc="Habilita el chat para informes.",
)
async def chaton(self, message):
"""Enable chat for reports"""
chat_id = str(message.chat_id)
self.db.set("ReportsMod", f"report_active_{chat_id}", True)
await utils.answer(message, self.strings["reports_enabled"])
@loader.command(
ru_doc="Отключает чат для репортов.",
uz_doc="Hisobotlar uchun chatni o'chiradi.",
de_doc="Deaktiviert den Chat für Berichte.",
es_doc="Desactiva el chat para informes.",
)
async def chatoff(self, message):
"""Disable chat for reports"""
chat_id = str(message.chat_id)
self.db.set("ReportsMod", f"report_active_{chat_id}", False)
await utils.answer(message, self.strings["reports_disabled"])
@loader.command(
ru_doc="Отправляет репорт администрации.",
uz_doc="Ma'muriyatga hisobot yuboradi.",
de_doc="Sendet einen Bericht an die Verwaltung.",
es_doc="Envía un informe a la administración.",
)
async def report(self, message):
"""Sends a report to the administration."""
chat_id = str(message.chat_id)
report_active = self.db.get("ReportsMod", f"report_active_{chat_id}", False)
if not report_active:
await utils.answer(message, self.strings["reports_not_enabled"])
return
args = utils.get_args_raw(message)
if not args:
await utils.answer(message, self.strings["not_args"])
return
parts = args.split(maxsplit=1)
if len(parts) < 2:
await utils.answer(message, self.strings["parts_both_2"])
return
user_id_or_name, reason = parts
try:
if user_id_or_name.isdigit():
user_id = int(user_id_or_name)
else:
user_id = user_id_or_name
user = await self.client.get_entity(user_id)
reporter = await self.client.get_entity(message.sender_id)
report_message = (f"<b>🚨 Report Submitted 🚨</b>\n\n"
f"<b>Reporter:</b> @{reporter.username if reporter.username else 'unknown'} (ID: {reporter.id})\n"
f"<b>Reported User:</b> @{user.username if user.username else 'unknown'} (ID: {user.id})\n"
f"<b>Reason:</b> {reason}")
await self.client.send_message(self.Aurora_Reports, report_message)
await utils.answer(message, self.strings["success"])
except Exception as e:
logger.error(f"Failed to process the report: {str(e)}")
await utils.answer(message, self.strings["fail"])
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: Reports
# Author: dend1yya
# Commands:
# .addadmins | .chaton | .chatoff | .report
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/5131a980bd2f80ad463ad.jpg
__version__ = (1, 0, 0)
from hikkatl.types import Message # type: ignore
from telethon.tl.functions.channels import InviteToChannelRequest # type: ignore
from telethon.tl.functions.users import GetFullUserRequest #type: ignore
from telethon.tl.functions.channels import CreateChannelRequest, InviteToChannelRequest #type: ignore
from telethon.tl.types import ChatAdminRights #type: ignore
from .. import loader, utils
import logging
logger = logging.getLogger(__name__)
@loader.tds
class ReportsMod(loader.Module):
"""Module for sending reports to the administration."""
strings = {
"name": "Reports",
"admin_id": "ADMIN_ID",
"loading": "<b>Loading...</b>",
"group_created": "<b>Report Channel accessed and admin(s) invited if specified.</b>",
"group_error": "<b>Error accessing the report channel.</b>",
"no_admins": "<b>No admins configered to ivnite.</b>",
"reports_enabled": "Report reception enabled in this chat.",
"reports_disabled": "Report reception disabled in this chat.",
"reports_not_enabled": "<b>Reports not enabled in this chat.</b>",
"not_args": "<b>Usage: .report {userID/@username} (reason)</b>",
"parts_both_2": "<b>Please provide both a user and a reason.</b>",
"success": "<b>Report submitted successfully.</b>",
"fail": "<b>Failed to submit the report.</b>",
}
strings_ru = {
"admin_id": "ADMIN_ID",
"loading": "<b>Загрузка...</b>",
"group_created": "<b>Группа для репортов создана, и администраторы были приглашены.</b>",
"group_error": "<b>Ошибка при создании канала с репортами.",
"no_admins": "<b>Нету администраторов которых можно добавить в группу.</b>",
"reports_enabled": "<b>Репорты включены в этом чате</b>",
"reports_disabled": "<b>Репорты выключены в этом чате</b>",
"reports_not_enabled": "<b>Репорты не включены в этом чате.</b>",
"not_args": "<b>Использование: .report{userID/@username} (причина)</b>",
"parts_both_2": "<b>Пожалуйста введите имя пользователя и причину.</b>",
"success": "<b>Репорт успешно отправлен.</b>",
"fail": "<b>Ошибка при отправке репорта.</b>"
}
strings_uz = {
"admin_id": "ADMIN_ID",
"loading": "<b>Yuklanmoqda...</b>",
"group_created": "<b>Hisobot kanali ochildi va agar ko'rsatilgan bo'lsa, administrator(lar) taklif qilindi.</b>",
"group_error": "<b>Hisobot kanaliga kirishda xato yuz berdi.</b>",
"no_admins": "<b>Taklif qilish uchun administratorlar mavjud emas.</b>",
"reports_enabled": "<b>Hisobot qabul qilish ushbu chatda yoqilgan.</b>",
"reports_disabled": "<b>Hisobot qabul qilish ushbu chatda o'chirilgan.</b>",
"reports_not_enabled": "<b>Hisobot ushbu chatda yoqilmagan.</b>",
"not_args": "<b>Foydalanish: .report {userID/@username} (sababi)</b>",
"parts_both_2": "<b>Iltimos, foydalanuvchi va sababni taqdim eting.</b>",
"success": "<b>Hisobot muvaffaqiyatli yuborildi.</b>",
"fail": "<b>Hisobot yuborishda xato yuz berdi.</b>",
}
strings_de = {
"admin_id": "ADMIN_ID",
"loading": "<b>Wird geladen...</b>",
"group_created": "<b>Berichtskanal aufgerufen und Administrator(en) eingeladen, falls angegeben.</b>",
"group_error": "<b>Fehler beim Zugreifen auf den Berichtskanal.</b>",
"no_admins": "<b>Keine Administratoren konfiguriert, um einzuladen.</b>",
"reports_enabled": "<b>Berichtserfassung in diesem Chat aktiviert.</b>",
"reports_disabled": "<b>Berichtserfassung in diesem Chat deaktiviert.</b>",
"reports_not_enabled": "<b>Berichte in diesem Chat nicht aktiviert.</b>",
"not_args": "<b>Verwendung: .report {userID/@username} (Grund)</b>",
"parts_both_2": "<b>Bitte sowohl einen Benutzer als auch einen Grund angeben.</b>",
"success": "<b>Bericht erfolgreich eingereicht.</b>",
"fail": "<b>Fehler beim Einreichen des Berichts.</b>",
}
strings_es = {
"admin_id": "ADMIN_ID",
"loading": "<b>Cargando...</b>",
"group_created": "<b>Canal de informes accedido y administrador(es) invitado(s) si se especificó.</b>",
"group_error": "<b>Error al acceder al canal de informes.</b>",
"no_admins": "<b>No hay administradores configurados para invitar.</b>",
"reports_enabled": "<b>Recepción de informes habilitada en este chat.</b>",
"reports_disabled": "<b>Recepción de informes deshabilitada en este chat.</b>",
"reports_not_enabled": "<b>Los informes no están habilitados en este chat.</b>",
"not_args": "<b>Uso: .report {userID/@username} (razón)</b>",
"parts_both_2": "<b>Por favor, proporcione tanto un usuario como una razón.</b>",
"success": "<b>Informe enviado con éxito.</b>",
"fail": "<b>Error al enviar el informe.</b>",
}
def __init__(self):
self.config = loader.ModuleConfig(
"admin_id",
None,
lambda: self.strings["admin_id"]
)
async def client_ready(self, client, db):
self.client = client
self.db = db
try:
result = await client(CreateChannelRequest(
title="Aurora-Reports",
about="🐬 chat for reports from users",
megagroup=True
))
self.Aurora_Reports = result.chats[0]
except Exception as e:
logger.error(f"Failed to create report group: {str(e)}")
@loader.command(
ru_doc="Добавить администраторов из конфигурации в группу.",
uz_doc="Konfiguratsiyadan administratorlarni guruhga qo'shadi.",
de_doc="Fügt Administratoren aus der Konfiguration zur Gruppe hinzu.",
es_doc="Agrega administradores desde la configuración al grupo.",
)
async def addadmins(self, message):
"""Add administrators from the config to the group"""
await utils.answer(message, self.strings["loading"])
try:
admin_ids = self.config.get("admin_id")
if not admin_ids:
await utils.answer(message, self.strings["no_admins"])
return
if isinstance(admin_ids, list):
for admin_id in admin_ids:
await self.client(InviteToChannelRequest(
channel=self.Aurora_Reports,
users=[admin_id]
))
else:
await self.client(InviteToChannelRequest(
channel=self.Aurora_Reports,
users=[admin_ids]
))
await utils.answer(message, self.strings["group_created"])
except Exception as e:
logger.error(f"Failed to invite admins to the report group: {str(e)}")
await utils.answer(message, self.strings["group_error"])
@loader.command(
ru_doc="Включает чат для репортов.",
uz_doc="Hisobotlar uchun chatni yoqadi.",
de_doc="Aktiviert den Chat für Berichte.",
es_doc="Habilita el chat para informes.",
)
async def chaton(self, message):
"""Enable chat for reports"""
chat_id = str(message.chat_id)
self.db.set("ReportsMod", f"report_active_{chat_id}", True)
await utils.answer(message, self.strings["reports_enabled"])
@loader.command(
ru_doc="Отключает чат для репортов.",
uz_doc="Hisobotlar uchun chatni o'chiradi.",
de_doc="Deaktiviert den Chat für Berichte.",
es_doc="Desactiva el chat para informes.",
)
async def chatoff(self, message):
"""Disable chat for reports"""
chat_id = str(message.chat_id)
self.db.set("ReportsMod", f"report_active_{chat_id}", False)
await utils.answer(message, self.strings["reports_disabled"])
@loader.command(
ru_doc="Отправляет репорт администрации.",
uz_doc="Ma'muriyatga hisobot yuboradi.",
de_doc="Sendet einen Bericht an die Verwaltung.",
es_doc="Envía un informe a la administración.",
)
async def report(self, message):
"""Sends a report to the administration."""
chat_id = str(message.chat_id)
report_active = self.db.get("ReportsMod", f"report_active_{chat_id}", False)
if not report_active:
await utils.answer(message, self.strings["reports_not_enabled"])
return
args = utils.get_args_raw(message)
if not args:
await utils.answer(message, self.strings["not_args"])
return
parts = args.split(maxsplit=1)
if len(parts) < 2:
await utils.answer(message, self.strings["parts_both_2"])
return
user_id_or_name, reason = parts
try:
if user_id_or_name.isdigit():
user_id = int(user_id_or_name)
else:
user_id = user_id_or_name
user = await self.client.get_entity(user_id)
reporter = await self.client.get_entity(message.sender_id)
report_message = (f"<b>🚨 Report Submitted 🚨</b>\n\n"
f"<b>Reporter:</b> @{reporter.username if reporter.username else 'unknown'} (ID: {reporter.id})\n"
f"<b>Reported User:</b> @{user.username if user.username else 'unknown'} (ID: {user.id})\n"
f"<b>Reason:</b> {reason}")
await self.client.send_message(self.Aurora_Reports, report_message)
await utils.answer(message, self.strings["success"])
except Exception as e:
logger.error(f"Failed to process the report: {str(e)}")
await utils.answer(message, self.strings["fail"])

View File

@@ -1,149 +1,149 @@
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: Warpigs
# Author: dend1yya
# Commands:
# .autogrow | .ungrow | .autofight | .unfight | .nameset
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/a37fb86b3a00c03dee661.jpg
from .. import loader, utils
import asyncio
class WarpigsMod(loader.Module):
"""Automates work with @warpigs_bot"""
strings = {
"name": "Warpigs",
"pig_growth_on": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Automatic pig growth: <i>Activated.</i></b>",
"pig_growth_off": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Automatic pig growth: <i>Deactivated.</i></b>",
"pig_fights_on": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Automatic pig fights: <i>Activated.</i></b>",
"pig_fights_off": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Automatic pig fights: <i>Deactivated.</i></b>",
"no_name": "<emoji document_id=5778527486270770928>❌</emoji> <b>Specify a name for the pig.</b>",
"name_set": "<emoji document_id=5774022692642492953>✅</emoji> <b>Your pig's name has been successfully changed!</b>",
"new_name": "<emoji document_id=5316581501360420451>🐷</emoji> <b>New name</b>",
}
strings_ru = {
"pig_growth_on": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Автоматический рост свиней: <i>Включен.</i></b>",
"pig_growth_off": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Автоматический рост свиней: <i>Выключен.</i></b>",
"pig_fights_on": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Автоматические свиные бои: <i>Включены.</i></b>",
"pig_fights_off": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Автоматические свиные бои: <i>Выключены.</i></b>",
"no_name": "<emoji document_id=5778527486270770928>❌</emoji> <b>Укажите имя для свиньи.</b>",
"name_set": "<emoji document_id=5774022692642492953>✅</emoji> <b>Имя вашей свиньи успешно изменено!</b>",
"new_name": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Новое имя</b>",
}
strings_uz = {
"pig_growth_on": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Avtomatik cho'chqa o'sishi: <i>Yoqilgan.</i></b>",
"pig_growth_off": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Avtomatik cho'chqa o'sishi: <i>O'chirilgan.</i></b>",
"pig_fights_on": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Avtomatik cho'chqa janglari: <i>Yoqilgan.</i></b>",
"pig_fights_off": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Avtomatik cho'chqa janglari: <i>O'chirilgan.</i></b>",
"no_name": "<emoji document_id=5778527486270770928>❌</emoji> <b>Cho'chqaga ism kiriting.</b>",
"name_set": "<emoji document_id=5774022692642492953>✅</emoji> <b>Cho'chqangizning ismi muvaffaqiyatli o'zgartirildi!</b>",
"new_name": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Yangi ism</b>",
}
strings_de = {
"pig_growth_on": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Automatisches Schweinewachstum: <i>Aktiviert.</i></b>",
"pig_growth_off": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Automatisches Schweinewachstum: <i>Deaktiviert.</i></b>",
"pig_fights_on": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Automatische Schweinekämpfe: <i>Aktiviert.</i></b>",
"pig_fights_off": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Automatische Schweinekämpfe: <i>Deaktiviert.</i></b>",
"no_name": "<emoji document_id=5778527486270770928>❌</emoji> <b>Geben Sie einen Namen für das Schwein an.</b>",
"name_set": "<emoji document_id=5774022692642492953>✅</emoji> <b>Der Name Ihres Schweins wurde erfolgreich geändert!</b>",
"new_name": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Neuer Name</b>",
}
strings_es = {
"pig_growth_on": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Crecimiento automático de cerdos: <i>Activado.</i></b>",
"pig_growth_off": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Crecimiento automático de cerdos: <i>Desactivado.</i></b>",
"pig_fights_on": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Combates automáticos de cerdos: <i>Activado.</i></b>",
"pig_fights_off": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Combates automáticos de cerdos: <i>Desactivado.</i></b>",
"no_name": "<emoji document_id=5778527486270770928>❌</emoji> <b>Especifica un nombre para el cerdo.</b>",
"name_set": "<emoji document_id=5774022692642492953>✅</emoji> <b>¡El nombre de tu cerdo ha sido cambiado exitosamente!</b>",
"new_name": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Nuevo nombre</b>",
}
@loader.command(
ru_doc="Автоматический рост свиньи.",
uz_doc="Avtomatik cho'chqa o'sishi.",
de_doc="Automatisches Schweinewachstum.",
es_doc="Crecimiento automático de cerdos.",
)
async def autogrow(self, message):
"""Automatic pig growth"""
await message.edit(self.strings("pig_growth_on"))
self.set("grow", True)
while self.get("grow"):
await message.reply("/grow")
await asyncio.sleep(86400)
@loader.command(
ru_doc="Отключить автоматический рост.",
uz_doc="Avtomatik o'sishni o'chirish.",
de_doc="Automatisches Wachstum deaktivieren.",
es_doc="Desactivar el crecimiento automático.",
)
async def ungrow(self,message):
"""Disable automatic growth."""
self.set("grow", False)
await utils.answer(message, self.strings("pig_growth_off"))
@loader.command(
ru_doc="Включить автоматические бои свиней.",
uz_doc="Avtomatik cho'chqa janglarini yoqish.",
de_doc="Automatische Schweinekämpfe aktivieren.",
es_doc="Habilitar peleas automáticas de cerdos.",
)
async def autofight(self,message):
"""Enable automatic pig fights"""
await message.edit(self.strings("pig_fights_on"))
self.set("fight", True)
while self.get("fight"):
await message.reply("/fight")
await asyncio.sleep(86400)
@loader.command(
ru_doc="Отключить автоматические бои свиней.",
uz_doc="Avtomatik cho'chqa janglarini o'chirish.",
de_doc="Automatische Schweinekämpfe deaktivieren.",
es_doc="Deshabilitar peleas automáticas de cerdos.",
)
async def unfight(self,message):
"""Disable automatic pig fights"""
self.set("fight",False)
await utils.answer(message, self.strings("pig_fights_off"))
@loader.command(
ru_doc="[name] - Установить имя вашей свиньи.",
uz_doc="[name] - Cho'chqangizning nomini o'rnatadi.",
de_doc="[name] - Setze den Namen deines Schweins.",
es_doc="[name] - Establece el nombre de tu cerdo.",
)
async def nameset(self,message):
"""[name] - Set the name of your pig"""
args = utils.get_args_raw(message)
if not args:
await utils.answer(message, self.strings("no_name"))
return
name_set = self.strings("name_set")
new_name = self.strings("new_name")
await message.respond(f"/name {args}")
await message.edit(f"{name_set}\n{new_name}: <code>{args}</code>")
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: Warpigs
# Author: dend1yya
# Commands:
# .autogrow | .ungrow | .autofight | .unfight | .nameset
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/a37fb86b3a00c03dee661.jpg
from .. import loader, utils
import asyncio
class WarpigsMod(loader.Module):
"""Automates work with @warpigs_bot"""
strings = {
"name": "Warpigs",
"pig_growth_on": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Automatic pig growth: <i>Activated.</i></b>",
"pig_growth_off": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Automatic pig growth: <i>Deactivated.</i></b>",
"pig_fights_on": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Automatic pig fights: <i>Activated.</i></b>",
"pig_fights_off": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Automatic pig fights: <i>Deactivated.</i></b>",
"no_name": "<emoji document_id=5778527486270770928>❌</emoji> <b>Specify a name for the pig.</b>",
"name_set": "<emoji document_id=5774022692642492953>✅</emoji> <b>Your pig's name has been successfully changed!</b>",
"new_name": "<emoji document_id=5316581501360420451>🐷</emoji> <b>New name</b>",
}
strings_ru = {
"pig_growth_on": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Автоматический рост свиней: <i>Включен.</i></b>",
"pig_growth_off": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Автоматический рост свиней: <i>Выключен.</i></b>",
"pig_fights_on": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Автоматические свиные бои: <i>Включены.</i></b>",
"pig_fights_off": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Автоматические свиные бои: <i>Выключены.</i></b>",
"no_name": "<emoji document_id=5778527486270770928>❌</emoji> <b>Укажите имя для свиньи.</b>",
"name_set": "<emoji document_id=5774022692642492953>✅</emoji> <b>Имя вашей свиньи успешно изменено!</b>",
"new_name": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Новое имя</b>",
}
strings_uz = {
"pig_growth_on": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Avtomatik cho'chqa o'sishi: <i>Yoqilgan.</i></b>",
"pig_growth_off": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Avtomatik cho'chqa o'sishi: <i>O'chirilgan.</i></b>",
"pig_fights_on": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Avtomatik cho'chqa janglari: <i>Yoqilgan.</i></b>",
"pig_fights_off": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Avtomatik cho'chqa janglari: <i>O'chirilgan.</i></b>",
"no_name": "<emoji document_id=5778527486270770928>❌</emoji> <b>Cho'chqaga ism kiriting.</b>",
"name_set": "<emoji document_id=5774022692642492953>✅</emoji> <b>Cho'chqangizning ismi muvaffaqiyatli o'zgartirildi!</b>",
"new_name": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Yangi ism</b>",
}
strings_de = {
"pig_growth_on": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Automatisches Schweinewachstum: <i>Aktiviert.</i></b>",
"pig_growth_off": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Automatisches Schweinewachstum: <i>Deaktiviert.</i></b>",
"pig_fights_on": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Automatische Schweinekämpfe: <i>Aktiviert.</i></b>",
"pig_fights_off": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Automatische Schweinekämpfe: <i>Deaktiviert.</i></b>",
"no_name": "<emoji document_id=5778527486270770928>❌</emoji> <b>Geben Sie einen Namen für das Schwein an.</b>",
"name_set": "<emoji document_id=5774022692642492953>✅</emoji> <b>Der Name Ihres Schweins wurde erfolgreich geändert!</b>",
"new_name": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Neuer Name</b>",
}
strings_es = {
"pig_growth_on": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Crecimiento automático de cerdos: <i>Activado.</i></b>",
"pig_growth_off": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Crecimiento automático de cerdos: <i>Desactivado.</i></b>",
"pig_fights_on": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Combates automáticos de cerdos: <i>Activado.</i></b>",
"pig_fights_off": "<emoji document_id=5316581501360420451>⚔️</emoji> <b>Combates automáticos de cerdos: <i>Desactivado.</i></b>",
"no_name": "<emoji document_id=5778527486270770928>❌</emoji> <b>Especifica un nombre para el cerdo.</b>",
"name_set": "<emoji document_id=5774022692642492953>✅</emoji> <b>¡El nombre de tu cerdo ha sido cambiado exitosamente!</b>",
"new_name": "<emoji document_id=5316581501360420451>🐷</emoji> <b>Nuevo nombre</b>",
}
@loader.command(
ru_doc="Автоматический рост свиньи.",
uz_doc="Avtomatik cho'chqa o'sishi.",
de_doc="Automatisches Schweinewachstum.",
es_doc="Crecimiento automático de cerdos.",
)
async def autogrow(self, message):
"""Automatic pig growth"""
await message.edit(self.strings("pig_growth_on"))
self.set("grow", True)
while self.get("grow"):
await message.reply("/grow")
await asyncio.sleep(86400)
@loader.command(
ru_doc="Отключить автоматический рост.",
uz_doc="Avtomatik o'sishni o'chirish.",
de_doc="Automatisches Wachstum deaktivieren.",
es_doc="Desactivar el crecimiento automático.",
)
async def ungrow(self,message):
"""Disable automatic growth."""
self.set("grow", False)
await utils.answer(message, self.strings("pig_growth_off"))
@loader.command(
ru_doc="Включить автоматические бои свиней.",
uz_doc="Avtomatik cho'chqa janglarini yoqish.",
de_doc="Automatische Schweinekämpfe aktivieren.",
es_doc="Habilitar peleas automáticas de cerdos.",
)
async def autofight(self,message):
"""Enable automatic pig fights"""
await message.edit(self.strings("pig_fights_on"))
self.set("fight", True)
while self.get("fight"):
await message.reply("/fight")
await asyncio.sleep(86400)
@loader.command(
ru_doc="Отключить автоматические бои свиней.",
uz_doc="Avtomatik cho'chqa janglarini o'chirish.",
de_doc="Automatische Schweinekämpfe deaktivieren.",
es_doc="Deshabilitar peleas automáticas de cerdos.",
)
async def unfight(self,message):
"""Disable automatic pig fights"""
self.set("fight",False)
await utils.answer(message, self.strings("pig_fights_off"))
@loader.command(
ru_doc="[name] - Установить имя вашей свиньи.",
uz_doc="[name] - Cho'chqangizning nomini o'rnatadi.",
de_doc="[name] - Setze den Namen deines Schweins.",
es_doc="[name] - Establece el nombre de tu cerdo.",
)
async def nameset(self,message):
"""[name] - Set the name of your pig"""
args = utils.get_args_raw(message)
if not args:
await utils.answer(message, self.strings("no_name"))
return
name_set = self.strings("name_set")
new_name = self.strings("new_name")
await message.respond(f"/name {args}")
await message.edit(f"{name_set}\n{new_name}: <code>{args}</code>")

View File

@@ -1,232 +1,232 @@
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: WordFinder
# Author: Felix?
# Commands:
# .wfind
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/c34c0a11aabd6a1fb6210.jpg
__version__ = (1, 0, 0)
from aiogram.types import Message as AiogramMessage
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from .. import loader, utils
@loader.tds
class WordFinderMod(loader.Module):
"""Universal module for searching for certain words in the text."""
strings = {
"name": "WordFinder",
"status_t": "<emoji document_id=5879785854284599288></emoji> <b>Module status: <i>Works</i></b>",
"status_f": "<emoji document_id=5879785854284599288></emoji> <b>Module status: <i>Does not work</i></b>",
"chat_id_error": "<emoji document_id=5879813604068298387>❗️</emoji> <b>There is no value in the chat_id config or it is incorrect.</b>",
"words_error": "<emoji document_id=5879813604068298387>❗️</emoji> </b>There is no value in the words config or it is incorrect.</b>",
"enabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>The module is enabled.</b>",
"disabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>The module is disabled.</b>",
"incorrect_args": "<emoji document_id=5778527486270770928>❌</emoji> <b>Incorrect arguments have been entered.</b>",
"message_found": "⚠ <b>New message has been found</b> ⚠\n\n<code>{}</code>\n\n<b>The found word: <i>{}</i></b>",
"": "",
"cfg_chat_id": "Enter the id of the chats or channels in which the words from the words config will be searched.",
"cfg_words": "Enter the words separated by commas that will be searched in the chats.",
"cfg_admin_chat_id": "Enter the chat id where notifications will be sent, if the value is None, the chat for notifications will be Word-Finder.",
}
strings_ru = {
"status_t": "<emoji document_id=5879785854284599288></emoji> <b>Статус модуля: <i>Работает</i></b>",
"status_f": "<emoji document_id=5879785854284599288></emoji> <b>Статус модуля: <i>Не работает</i></b>",
"chat_id_error": "<emoji document_id=5879813604068298387>❗️</emoji> <b>В конфиге chat_id нет значения или оно неверное.</b>",
"words_error": "<emoji document_id=5879813604068298387>❗️</emoji> <b>В конфиге words нет значения или оно неверное.</b>",
"enabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>Модуль включен.</b>",
"disabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>Модуль отключен.</b>",
"incorrect_args": "<emoji document_id=5778527486270770928>❌</emoji> <b>Были введены неверные аргументы.</b>",
"message_found": "⚠ <b>Найдено новое сообщение</b> ⚠\n\n<code>{}</code>\n\n<b>Найденное слово: <i>{}</i></b>",
"cfg_chat_id": "Введите id чатов или каналов, в которых будут искаться слова из конфига words.",
"cfg_words": "Введите слова через запятую, которые будут искаться в чатах.",
"cfg_admin_chat_id": "Введите id чата, куда будут присылаться уведомления, если значение None, чатом для уведомлений будет Word-Finder.",
}
strings_uz = {
"status_t": "<emoji document_id=5879785854284599288></emoji> <b>Modul holati: <i>Faol</i></b>",
"status_f": "<emoji document_id=5879785854284599288></emoji> <b>Modul holati: <i>Faol emas</i></b>",
"chat_id_error": "<emoji document_id=5879813604068298387>❗️</emoji> <b>Konfiguratsiyada chat_id qiymati mavjud emas yoki noto'g'ri.</b>",
"words_error": "<emoji document_id=5879813604068298387>❗️</emoji> <b>Konfiguratsiyada words qiymati mavjud emas yoki noto'g'ri.</b>",
"enabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>Modul yoqildi.</b>",
"disabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>Modul o'chirildi.</b>",
"incorrect_args": "<emoji document_id=5778527486270770928>❌</emoji> <b>Noto'g'ri argumentlar kiritildi.</b>",
"message_found": "⚠ <b>Yangi xabar topildi</b> ⚠\n\n<code>{}</code>\n\n<b>Topilgan so'z: <i>{}</i></b>",
"cfg_chat_id": "So'zlar izlanadigan chat yoki kanal idlarini kiriting.",
"cfg_words": "Chatlarda izlanadigan so'zlarni vergul bilan ajratib kiriting.",
"cfg_admin_chat_id": "Bildirishnomalar yuboriladigan chat idini kiriting. Agar None bo'lsa, Word-Finder bildirishnomalar uchun ishlatiladi.",
}
strings_de = {
"status_t": "<emoji document_id=5879785854284599288></emoji> <b>Modulstatus: <i>Aktiv</i></b>",
"status_f": "<emoji document_id=5879785854284599288></emoji> <b>Modulstatus: <i>Inaktiv</i></b>",
"chat_id_error": "<emoji document_id=5879813604068298387>❗️</emoji> <b>Im Konfigurationswert chat_id fehlt oder ist ungültig.</b>",
"words_error": "<emoji document_id=5879813604068298387>❗️</emoji> <b>Im Konfigurationswert words fehlt oder ist ungültig.</b>",
"enabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>Modul aktiviert.</b>",
"disabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>Modul deaktiviert.</b>",
"incorrect_args": "<emoji document_id=5778527486270770928>❌</emoji> <b>Ungültige Argumente eingegeben.</b>",
"message_found": "⚠ <b>Neue Nachricht gefunden</b> ⚠\n\n<code>{}</code>\n\n<b>Gefundenes Wort: <i>{}</i></b>",
"cfg_chat_id": "Geben Sie die IDs der Chats oder Kanäle ein, in denen nach Wörtern aus der Konfiguration gesucht werden soll.",
"cfg_words": "Geben Sie die zu suchenden Wörter in den Chats durch Kommas getrennt ein.",
"cfg_admin_chat_id": "Geben Sie die ID des Chats ein, in dem Benachrichtigungen gesendet werden sollen. Wenn None, wird Word-Finder für Benachrichtigungen verwendet.",
}
strings_es = {
"status_t": "<emoji document_id=5879785854284599288></emoji> <b>Estado del módulo: <i>Activo</i></b>",
"status_f": "<emoji document_id=5879785854284599288></emoji> <b>Estado del módulo: <i>Inactivo</i></b>",
"chat_id_error": "<emoji document_id=5879813604068298387>❗️</emoji> <b>El valor de chat_id en la configuración no está presente o es incorrecto.</b>",
"words_error": "<emoji document_id=5879813604068298387>❗️</emoji> <b>El valor de words en la configuración no está presente o es incorrecto.</b>",
"enabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>Módulo activado.</b>",
"disabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>Módulo desactivado.</b>",
"incorrect_args": "<emoji document_id=5778527486270770928>❌</emoji> <b>Se ingresaron argumentos incorrectos.</b>",
"message_found": "⚠ <b>Se encontró un nuevo mensaje</b> ⚠\n\n<code>{}</code>\n\n<b>Palabra encontrada: <i>{}</i></b>",
"cfg_chat_id": "Ingrese las IDs de los chats o canales donde se buscarán las palabras de la configuración.",
"cfg_words": "Ingrese las palabras a buscar en los chats separadas por comas.",
"cfg_admin_chat_id": "Ingrese la ID del chat donde se enviarán las notificaciones. Si es None, se utilizará Word-Finder para las notificaciones.",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"chat_id",
None,
lambda: self.strings("cfg_chat_id")
),
loader.ConfigValue(
"words",
[],
lambda: self.strings("cfg_words")
),
loader.ConfigValue(
"admin_chat_id",
None,
lambda: self.strings("cfg_admin_chat_id")
),
)
async def client_ready(self, client, db):
self.client = client
self.db = db
self.c, _ = await utils.asset_channel(
self.client,
"Word-Finder",
"Chat for receiving notifications about finding a word in the text.",
silent=True,
invite_bot=True,
)
self.chat = f"-100{self.c.id}"
@loader.command(
ru_doc="<on/off> - установить статус работы модуля",
uz_doc="<on/off> - o'rnatish modulining ish holati",
de_doc="<on/off> - den Betriebsstatus des Moduls festlegen",
es_doc="<on/off> - establecer el estado de funcionamiento del módulo",
)
async def wfind(self, message):
"""<on/off> - set the module operation status"""
args = utils.get_args_raw(message).lower()
chat_id = self.config["chat_id"]
words = self.config["words"]
if not args:
if self.db.get("WordFinder", "status"):
status = self.strings("status_t")
else:
status = self.strings("status_f")
await utils.answer(message, status)
return
if chat_id == None:
await utils.answer(message, self.strings("chat_id_error"))
return
if words is None or words == []:
await utils.answer(message, self.strings("words_error"))
return
if args == "on":
self.db.set("WordFinder", "status", True)
await utils.answer(message, self.strings("enabled"))
return
elif args == "off":
self.db.set("WordFinder", "status", False)
await utils.answer(message, self.strings("disabled"))
return
else:
await utils.answer(message, self.strings("incorrect_args"))
return
async def watcher(self, message: AiogramMessage):
if not self.db.get("WordFinder", "status", False):
return
chat_id = self.config["chat_id"]
words = self.config["words"]
admin_chat_id = self.config["admin_chat_id"]
if isinstance(chat_id, int):
chat_ids = [chat_id]
elif isinstance(chat_id, list):
chat_ids = chat_id
else:
return
if isinstance(words, str):
words = [word.strip() for word in words.split(',')]
if message.chat_id not in chat_ids:
return
if not message.text:
return
if any(word in message.text.lower().split() for word in words):
found_words = [word for word in words if word in message.text.lower()]
if found_words:
found_word = ', '.join(found_words)
if message.is_private:
message_url = f"tg://openmessage?user_id={message.chat_id}"
else:
message_url = f"https://t.me/c/{message.chat.id}/{message.id}"
if self.config["admin_chat_id"] == None:
reply_markup = InlineKeyboardMarkup()
reply_markup.add(InlineKeyboardButton(text="🔗 Link", url=message_url))
await self.inline.bot.send_message(
self.chat,
self.strings("message_found").format(message.text, found_word),
reply_markup=reply_markup
)
else:
await self.inline.form(
message=admin_chat_id,
text=self.strings("message_found").format(message.text, found_word),
reply_markup=[
[
{"text": "🔗 Link", "url": message_url}
],
],
# * _ __ __ _ _
# * / \ _ _ _ __ ___ _ __ __ _| \/ | ___ __| |_ _| | ___ ___
# * / _ \| | | | '__/ _ \| '__/ _` | |\/| |/ _ \ / _` | | | | |/ _ \/ __|
# * / ___ \ |_| | | | (_) | | | (_| | | | | (_) | (_| | |_| | | __/\__ \
# * /_/ \_\__,_|_| \___/|_| \__,_|_| |_|\___/ \__,_|\__,_|_|\___||___/
# *
# * © Copyright 2024
# *
# * https://t.me/AuroraModules
# *
# * 🔒 Code is licensed under GNU AGPLv3
# * 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# * ⛔️ You CANNOT edit this file without direct permission from the author.
# * ⛔️ You CANNOT distribute this file if you have modified it without the direct permission of the author.
# Name: WordFinder
# Author: Felix?
# Commands:
# .wfind
# scope: hikka_only
# meta developer: @AuroraModules
# meta pic: https://i.postimg.cc/Hx3Zm8rB/logo.png
# meta banner: https://te.legra.ph/file/c34c0a11aabd6a1fb6210.jpg
__version__ = (1, 0, 0)
from aiogram.types import Message as AiogramMessage
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from .. import loader, utils
@loader.tds
class WordFinderMod(loader.Module):
"""Universal module for searching for certain words in the text."""
strings = {
"name": "WordFinder",
"status_t": "<emoji document_id=5879785854284599288></emoji> <b>Module status: <i>Works</i></b>",
"status_f": "<emoji document_id=5879785854284599288></emoji> <b>Module status: <i>Does not work</i></b>",
"chat_id_error": "<emoji document_id=5879813604068298387>❗️</emoji> <b>There is no value in the chat_id config or it is incorrect.</b>",
"words_error": "<emoji document_id=5879813604068298387>❗️</emoji> </b>There is no value in the words config or it is incorrect.</b>",
"enabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>The module is enabled.</b>",
"disabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>The module is disabled.</b>",
"incorrect_args": "<emoji document_id=5778527486270770928>❌</emoji> <b>Incorrect arguments have been entered.</b>",
"message_found": "⚠ <b>New message has been found</b> ⚠\n\n<code>{}</code>\n\n<b>The found word: <i>{}</i></b>",
"": "",
"cfg_chat_id": "Enter the id of the chats or channels in which the words from the words config will be searched.",
"cfg_words": "Enter the words separated by commas that will be searched in the chats.",
"cfg_admin_chat_id": "Enter the chat id where notifications will be sent, if the value is None, the chat for notifications will be Word-Finder.",
}
strings_ru = {
"status_t": "<emoji document_id=5879785854284599288></emoji> <b>Статус модуля: <i>Работает</i></b>",
"status_f": "<emoji document_id=5879785854284599288></emoji> <b>Статус модуля: <i>Не работает</i></b>",
"chat_id_error": "<emoji document_id=5879813604068298387>❗️</emoji> <b>В конфиге chat_id нет значения или оно неверное.</b>",
"words_error": "<emoji document_id=5879813604068298387>❗️</emoji> <b>В конфиге words нет значения или оно неверное.</b>",
"enabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>Модуль включен.</b>",
"disabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>Модуль отключен.</b>",
"incorrect_args": "<emoji document_id=5778527486270770928>❌</emoji> <b>Были введены неверные аргументы.</b>",
"message_found": "⚠ <b>Найдено новое сообщение</b> ⚠\n\n<code>{}</code>\n\n<b>Найденное слово: <i>{}</i></b>",
"cfg_chat_id": "Введите id чатов или каналов, в которых будут искаться слова из конфига words.",
"cfg_words": "Введите слова через запятую, которые будут искаться в чатах.",
"cfg_admin_chat_id": "Введите id чата, куда будут присылаться уведомления, если значение None, чатом для уведомлений будет Word-Finder.",
}
strings_uz = {
"status_t": "<emoji document_id=5879785854284599288></emoji> <b>Modul holati: <i>Faol</i></b>",
"status_f": "<emoji document_id=5879785854284599288></emoji> <b>Modul holati: <i>Faol emas</i></b>",
"chat_id_error": "<emoji document_id=5879813604068298387>❗️</emoji> <b>Konfiguratsiyada chat_id qiymati mavjud emas yoki noto'g'ri.</b>",
"words_error": "<emoji document_id=5879813604068298387>❗️</emoji> <b>Konfiguratsiyada words qiymati mavjud emas yoki noto'g'ri.</b>",
"enabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>Modul yoqildi.</b>",
"disabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>Modul o'chirildi.</b>",
"incorrect_args": "<emoji document_id=5778527486270770928>❌</emoji> <b>Noto'g'ri argumentlar kiritildi.</b>",
"message_found": "⚠ <b>Yangi xabar topildi</b> ⚠\n\n<code>{}</code>\n\n<b>Topilgan so'z: <i>{}</i></b>",
"cfg_chat_id": "So'zlar izlanadigan chat yoki kanal idlarini kiriting.",
"cfg_words": "Chatlarda izlanadigan so'zlarni vergul bilan ajratib kiriting.",
"cfg_admin_chat_id": "Bildirishnomalar yuboriladigan chat idini kiriting. Agar None bo'lsa, Word-Finder bildirishnomalar uchun ishlatiladi.",
}
strings_de = {
"status_t": "<emoji document_id=5879785854284599288></emoji> <b>Modulstatus: <i>Aktiv</i></b>",
"status_f": "<emoji document_id=5879785854284599288></emoji> <b>Modulstatus: <i>Inaktiv</i></b>",
"chat_id_error": "<emoji document_id=5879813604068298387>❗️</emoji> <b>Im Konfigurationswert chat_id fehlt oder ist ungültig.</b>",
"words_error": "<emoji document_id=5879813604068298387>❗️</emoji> <b>Im Konfigurationswert words fehlt oder ist ungültig.</b>",
"enabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>Modul aktiviert.</b>",
"disabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>Modul deaktiviert.</b>",
"incorrect_args": "<emoji document_id=5778527486270770928>❌</emoji> <b>Ungültige Argumente eingegeben.</b>",
"message_found": "⚠ <b>Neue Nachricht gefunden</b> ⚠\n\n<code>{}</code>\n\n<b>Gefundenes Wort: <i>{}</i></b>",
"cfg_chat_id": "Geben Sie die IDs der Chats oder Kanäle ein, in denen nach Wörtern aus der Konfiguration gesucht werden soll.",
"cfg_words": "Geben Sie die zu suchenden Wörter in den Chats durch Kommas getrennt ein.",
"cfg_admin_chat_id": "Geben Sie die ID des Chats ein, in dem Benachrichtigungen gesendet werden sollen. Wenn None, wird Word-Finder für Benachrichtigungen verwendet.",
}
strings_es = {
"status_t": "<emoji document_id=5879785854284599288></emoji> <b>Estado del módulo: <i>Activo</i></b>",
"status_f": "<emoji document_id=5879785854284599288></emoji> <b>Estado del módulo: <i>Inactivo</i></b>",
"chat_id_error": "<emoji document_id=5879813604068298387>❗️</emoji> <b>El valor de chat_id en la configuración no está presente o es incorrecto.</b>",
"words_error": "<emoji document_id=5879813604068298387>❗️</emoji> <b>El valor de words en la configuración no está presente o es incorrecto.</b>",
"enabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>Módulo activado.</b>",
"disabled": "<emoji document_id=5776375003280838798>✅</emoji> <b>Módulo desactivado.</b>",
"incorrect_args": "<emoji document_id=5778527486270770928>❌</emoji> <b>Se ingresaron argumentos incorrectos.</b>",
"message_found": "⚠ <b>Se encontró un nuevo mensaje</b> ⚠\n\n<code>{}</code>\n\n<b>Palabra encontrada: <i>{}</i></b>",
"cfg_chat_id": "Ingrese las IDs de los chats o canales donde se buscarán las palabras de la configuración.",
"cfg_words": "Ingrese las palabras a buscar en los chats separadas por comas.",
"cfg_admin_chat_id": "Ingrese la ID del chat donde se enviarán las notificaciones. Si es None, se utilizará Word-Finder para las notificaciones.",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"chat_id",
None,
lambda: self.strings("cfg_chat_id")
),
loader.ConfigValue(
"words",
[],
lambda: self.strings("cfg_words")
),
loader.ConfigValue(
"admin_chat_id",
None,
lambda: self.strings("cfg_admin_chat_id")
),
)
async def client_ready(self, client, db):
self.client = client
self.db = db
self.c, _ = await utils.asset_channel(
self.client,
"Word-Finder",
"Chat for receiving notifications about finding a word in the text.",
silent=True,
invite_bot=True,
)
self.chat = f"-100{self.c.id}"
@loader.command(
ru_doc="<on/off> - установить статус работы модуля",
uz_doc="<on/off> - o'rnatish modulining ish holati",
de_doc="<on/off> - den Betriebsstatus des Moduls festlegen",
es_doc="<on/off> - establecer el estado de funcionamiento del módulo",
)
async def wfind(self, message):
"""<on/off> - set the module operation status"""
args = utils.get_args_raw(message).lower()
chat_id = self.config["chat_id"]
words = self.config["words"]
if not args:
if self.db.get("WordFinder", "status"):
status = self.strings("status_t")
else:
status = self.strings("status_f")
await utils.answer(message, status)
return
if chat_id == None:
await utils.answer(message, self.strings("chat_id_error"))
return
if words is None or words == []:
await utils.answer(message, self.strings("words_error"))
return
if args == "on":
self.db.set("WordFinder", "status", True)
await utils.answer(message, self.strings("enabled"))
return
elif args == "off":
self.db.set("WordFinder", "status", False)
await utils.answer(message, self.strings("disabled"))
return
else:
await utils.answer(message, self.strings("incorrect_args"))
return
async def watcher(self, message: AiogramMessage):
if not self.db.get("WordFinder", "status", False):
return
chat_id = self.config["chat_id"]
words = self.config["words"]
admin_chat_id = self.config["admin_chat_id"]
if isinstance(chat_id, int):
chat_ids = [chat_id]
elif isinstance(chat_id, list):
chat_ids = chat_id
else:
return
if isinstance(words, str):
words = [word.strip() for word in words.split(',')]
if message.chat_id not in chat_ids:
return
if not message.text:
return
if any(word in message.text.lower().split() for word in words):
found_words = [word for word in words if word in message.text.lower()]
if found_words:
found_word = ', '.join(found_words)
if message.is_private:
message_url = f"tg://openmessage?user_id={message.chat_id}"
else:
message_url = f"https://t.me/c/{message.chat.id}/{message.id}"
if self.config["admin_chat_id"] == None:
reply_markup = InlineKeyboardMarkup()
reply_markup.add(InlineKeyboardButton(text="🔗 Link", url=message_url))
await self.inline.bot.send_message(
self.chat,
self.strings("message_found").format(message.text, found_word),
reply_markup=reply_markup
)
else:
await self.inline.form(
message=admin_chat_id,
text=self.strings("message_found").format(message.text, found_word),
reply_markup=[
[
{"text": "🔗 Link", "url": message_url}
],
],
)