Beispiel #1
0
def disableable_dec(command):
    log.debug(f"Adding {command} to the disableable commands...")

    if command not in DISABLABLE_COMMANDS:
        DISABLABLE_COMMANDS.append(command)

    def wrapped(func):
        async def wrapped_1(*args, **kwargs):
            message = args[0]

            chat_id = message.chat.id
            user_id = message.from_user.id
            cmd = command

            with suppress(KeyError):
                if command in (aliases := message.conf["cmds"]):
                    cmd = aliases[0]

            check = await db.disabled.find_one({
                "chat_id": chat_id,
                "cmds": {
                    "$in": [cmd]
                }
            })
            if check and not await is_user_admin(chat_id, user_id):
                return
            return await func(*args, **kwargs)

        return wrapped_1
Beispiel #2
0
async def start(_):
    log.debug("Starting before serving task for all modules...")
    loop.create_task(before_srv_task(loop))

    if not get_bool_key("DEBUG_MODE"):
        log.debug("Waiting 2 seconds...")
        await asyncio.sleep(2)
Beispiel #3
0
async def check_msg(message):
    log.debug("Running check msg for filters function.")
    chat = await get_connected_chat(message, only_groups=True)
    if "err_msg" in chat or message.chat.type == "private":
        return

    chat_id = chat["chat_id"]
    if not (filters := redis.lrange(f"filters_cache_{chat_id}", 0, -1)):
        filters = await update_handlers_cache(chat_id)
Beispiel #4
0
async def __before_serving__(loop):
    log.debug("Adding filters actions")
    for module in LOADED_MODULES:
        if not getattr(module, "__filters__", None):
            continue

        module_name = module.__name__.split(".")[-1]
        log.debug(f"Adding filter action from {module_name} module")
        for data in module.__filters__.items():
            FILTERS_ACTIONS[data[0]] = data[1]
Beispiel #5
0
    async def on_pre_process_message(self, message: Message, _):
        log.debug(
            f"Enforcing flood control on {message.from_user.id} in {message.chat.id}"
        )
        if self.is_message_valid(message):
            if await is_user_admin(message.chat.id, message.from_user.id):
                return self.set_state(message)
            if (database := await get_data(message.chat.id)) is None:
                return

            if await self.enforcer(message, database):
                await message.delete()
                strings = await get_strings(message.chat.id, "antiflood")
                await message.answer(strings["flood_exceeded"].format(
                    action=(strings[database["action"]] if "action" in database
                            else "banned").capitalize(),
                    user=await get_user_link(message.from_user.id),
                ))
                raise CancelHandler
Beispiel #6
0
from RaVaN import OWNER_ID, bot
from RaVaN.services.mongo import mongodb
from RaVaN.utils.logger import log
from RaVaN.versions import DB_STRUCTURE_VER


async def notify_bot_owner(old_ver, new_ver):
    await bot.send_message(
        OWNER_ID,
        f"Daisy database structure was updated from <code>{old_ver}</code> to <code>{new_ver}</code>",
    )


# TODO: Logs channel

log.debug("Checking on database structure update...")

if not (data := mongodb.db_structure.find_one({"db_ver": {"$exists": True}})):
    log.info("Your database is empty! Creating database structure key...")
    mongodb.db_structure.insert_one({"db_ver": DB_STRUCTURE_VER})
    log.info("Database structure version is: " + str(DB_STRUCTURE_VER))
else:
    curr_ver = data["db_ver"]
    log.info("Your database structure version is: " + str(curr_ver))
    if DB_STRUCTURE_VER > curr_ver:
        log.error("Your database is old! Waiting 20 seconds till update...")
        log.info("Press CTRL + C to cancel!")
        time.sleep(20)
        log.debug("Trying to update database structure...")
        log.info("--------------------------------")
        log.info("Your current database structure version: " + str(curr_ver))
Beispiel #7
0
import os

import yaml
from babel.core import Locale

from RaVaN.services.mongo import db
from RaVaN.services.redis import redis
from RaVaN.utils.logger import log

LANGUAGES = {}

log.info("Loading localizations...")

for filename in os.listdir("RaVaN/localization"):
    log.debug("Loading language file " + filename)
    with open("RaVaN/localization/" + filename, "r", encoding="utf8") as f:
        lang = yaml.load(f, Loader=yaml.CLoader)

        lang_code = lang["language_info"]["code"]
        lang["language_info"]["babel"] = Locale(lang_code)

        LANGUAGES[lang_code] = lang

log.info(
    "Languages loaded: {}".format(
        [
            language["language_info"]["babel"].display_name
            for language in LANGUAGES.values()
        ]
    )
Beispiel #8
0
OPERATORS.append(OWNER_ID)
OPERATORS.append(918317361)

# SpamWatch
spamwatch_api = get_str_key("SW_API", required=True)
sw = spamwatch.Client(spamwatch_api)

# Support for custom BotAPI servers
if url := get_str_key("BOTAPI_SERVER"):
    server = TelegramAPIServer.from_base(url)
else:
    server = TELEGRAM_PRODUCTION

# AIOGram
bot = Bot(token=TOKEN, parse_mode=types.ParseMode.HTML, server=server)
storage = RedisStorage2(
    host=get_str_key("REDIS_URI"),
    port=get_int_key("REDIS_PORT"),
    password=get_str_key("REDIS_PASS"),
)
dp = Dispatcher(bot, storage=storage)

loop = asyncio.get_event_loop()
SUPPORT_CHAT = get_str_key("SUPPORT_CHAT", required=True)
log.debug("Getting bot info...")
bot_info = loop.run_until_complete(bot.get_me())
BOT_USERNAME = bot_info.username
BOT_ID = bot_info.id
POSTGRESS_URL = get_str_key("DATABASE_URL", required=True)
TEMP_DOWNLOAD_DIRECTORY = "./"
Beispiel #9
0
DEFAULTS = {
    "LOAD_MODULES": True,
    "DEBUG_MODE": True,
    "REDIS_HOST": "localhost",
    "REDIS_PORT": 6379,
    "REDIS_DB_FSM": 1,
    "MONGODB_URI": "localhost",
    "MONGO_DB": "RaVaN",
    "API_PORT": 8080,
    "JOIN_CONFIRM_DURATION": "30m",
}

CONFIG_PATH = "data/bot_conf.yaml"
if os.name == "nt":
    log.debug("Detected Windows, changing config path...")
    CONFIG_PATH = os.getcwd() + "\\data\\bot_conf.yaml"

if os.path.isfile(CONFIG_PATH):
    log.info(CONFIG_PATH)
    for item in (data := yaml.load(open("data/bot_conf.yaml", "r"),
                                   Loader=yaml.CLoader)):
        DEFAULTS[item.upper()] = data[item]
else:
    log.info("Using env vars")


def get_str_key(name, required=False):
    if name in DEFAULTS:
        default = DEFAULTS[name]
    else:
Beispiel #10
0
async def before_srv_task(loop):
    for module in [
            m for m in LOADED_MODULES if hasattr(m, "__before_serving__")
    ]:
        log.debug("Before serving: " + module.__name__)
        loop.create_task(module.__before_serving__(loop))
Beispiel #11
0
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import asyncio
import os
from importlib import import_module

from aiogram import executor
from aiogram.contrib.middlewares.logging import LoggingMiddleware

from RaVaN import TOKEN, bot, dp
from RaVaN.config import get_bool_key, get_list_key
from RaVaN.modules import ALL_MODULES, LOADED_MODULES, MOD_HELP
from RaVaN.utils.logger import log

if get_bool_key("DEBUG_MODE"):
    log.debug("Enabling logging middleware.")
    dp.middleware.setup(LoggingMiddleware())

LOAD = get_list_key("LOAD")
DONT_LOAD = get_list_key("DONT_LOAD")

if get_bool_key("LOAD_MODULES"):
    if len(LOAD) > 0:
        modules = LOAD
    else:
        modules = ALL_MODULES

    modules = [x for x in modules if x not in DONT_LOAD]

    log.info("Modules to load: %s", str(modules))
    for module_name in modules: