Пример #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
Пример #2
0
    async def _set(self, *args: dict, **kwargs: dict):
        key = self.__build_key(*args, **kwargs)

        if bredis.exists(key):
            value = pickle.loads(bredis.get(key))
            return value if type(value) is not _NotSet else value.real_value

        result = await self.func(*args, **kwargs)
        if result is None:
            result = _NotSet()
        asyncio.ensure_future(set_value(key, result, ttl=self.ttl))
        log.debug(f"Cached: writing new data for key - {key}")
        return result if type(result) is not _NotSet else result.real_value
Пример #3
0
        async def new_func(*def_args, **def_kwargs):
            message = def_args[0]

            if cmds:
                message.conf["cmds"] = cmds

            if allow_kwargs is False:
                def_kwargs = dict()

            with configure_scope() as scope:
                parsed_update = parse_update(dict(message))
                scope.set_extra("update", str(parsed_update))

            if DEBUG_MODE:
                # log.debug('[*] Starting {}.'.format(func.__name__))
                # log.debug('Event: \n' + str(message))
                start = time.time()
                await func(*def_args, **def_kwargs)
                log.debug(
                    "[*] {} Time: {} sec.".format(func.__name__, time.time() - start)
                )
            else:
                await func(*def_args, **def_kwargs)
            raise SkipHandler()
Пример #4
0
from SungJinwooRobot import OWNER_ID, bot
from SungJinwooRobot.services.mongo import mongodb
from SungJinwooRobot.utils.logger import log
from SungJinwooRobot.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))
Пример #5
0
    'REDIS_HOST': 'localhost',
    'REDIS_PORT': 6379,
    'REDIS_DB_FSM': 1,

    'MONGODB_URI': 'localhost',
    'MONGO_DB': 'AllMight',

    'API_PORT': 8080,

    'JOIN_CONFIRM_DURATION': '30m',
}

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

if os.path.isfile(CONF_PATH):
    log.info(CONF_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:
        default = None
Пример #6
0
def register(*args, cmds=None, f=None, allow_edited=True, allow_kwargs=False, **kwargs):
    if cmds and type(cmds) is str:
        cmds = [cmds]

    register_kwargs = {}

    if cmds and not f:
        regex = r"\A^{}(".format("[!/]" if ALLOW_COMMANDS_FROM_EXC else "/")

        if "not_forwarded" not in kwargs and ALLOW_F_COMMANDS is False:
            kwargs["not_forwarded"] = True

        if "cmd_not_mono" not in kwargs and CMD_NOT_MONO:
            kwargs["cmd_not_mono"] = True

        for idx, cmd in enumerate(cmds):
            if cmd in REGISTRED_COMMANDS:
                log.warn(f"Duplication of /{cmd} command")
            REGISTRED_COMMANDS.append(cmd)
            regex += cmd

            if not idx == len(cmds) - 1:
                if not cmds[0] in COMMANDS_ALIASES:
                    COMMANDS_ALIASES[cmds[0]] = [cmds[idx + 1]]
                else:
                    COMMANDS_ALIASES[cmds[0]].append(cmds[idx + 1])
                regex += "|"

        if "disable_args" in kwargs:
            del kwargs["disable_args"]
            regex += f")($|@{BOT_USERNAME}$)"
        else:
            regex += f")(|@{BOT_USERNAME})(:? |$)"

        register_kwargs["regexp"] = regex

    elif f == "text":
        register_kwargs["content_types"] = types.ContentTypes.TEXT

    elif f == "welcome":
        register_kwargs["content_types"] = types.ContentTypes.NEW_CHAT_MEMBERS

    elif f == "leave":
        register_kwargs["content_types"] = types.ContentTypes.LEFT_CHAT_MEMBER

    elif f == "service":
        register_kwargs["content_types"] = types.ContentTypes.NEW_CHAT_MEMBERS
    elif f == "any":
        register_kwargs["content_types"] = types.ContentTypes.ANY

    log.debug(f"Registred new handler: <d><n>{str(register_kwargs)}</></>")

    register_kwargs.update(kwargs)

    def decorator(func):
        async def new_func(*def_args, **def_kwargs):
            message = def_args[0]

            if cmds:
                message.conf["cmds"] = cmds

            if allow_kwargs is False:
                def_kwargs = dict()

            with configure_scope() as scope:
                parsed_update = parse_update(dict(message))
                scope.set_extra("update", str(parsed_update))

            if DEBUG_MODE:
                # log.debug('[*] Starting {}.'.format(func.__name__))
                # log.debug('Event: \n' + str(message))
                start = time.time()
                await func(*def_args, **def_kwargs)
                log.debug(
                    "[*] {} Time: {} sec.".format(func.__name__, time.time() - start)
                )
            else:
                await func(*def_args, **def_kwargs)
            raise SkipHandler()

        if f == "cb":
            dp.register_callback_query_handler(new_func, *args, **register_kwargs)
        else:
            dp.register_message_handler(new_func, *args, **register_kwargs)
            if allow_edited is True:
                dp.register_edited_message_handler(new_func, *args, **register_kwargs)

    return decorator
Пример #7
0
from SungJinwooRobot.modules.error import parse_update
from SungJinwooRobot.utils.filters import ALL_FILTERS
from SungJinwooRobot.utils.logger import log

DEBUG_MODE = get_bool_key("DEBUG_MODE")
ALLOW_F_COMMANDS = get_bool_key("ALLOW_FORWARDS_COMMANDS")
ALLOW_COMMANDS_FROM_EXC = get_bool_key("ALLOW_COMMANDS_WITH_!")
CMD_NOT_MONO = get_bool_key("DISALLOW_MONO_CMDS")

REGISTRED_COMMANDS = []
COMMANDS_ALIASES = {}

# Import filters
log.info("Filters to load: %s", str(ALL_FILTERS))
for module_name in ALL_FILTERS:
    log.debug("Importing " + module_name)
    imported_module = import_module("SungJinwooRobot.utils.filters." + module_name)
log.info("Filters loaded!")


def register(*args, cmds=None, f=None, allow_edited=True, allow_kwargs=False, **kwargs):
    if cmds and type(cmds) is str:
        cmds = [cmds]

    register_kwargs = {}

    if cmds and not f:
        regex = r"\A^{}(".format("[!/]" if ALLOW_COMMANDS_FROM_EXC else "/")

        if "not_forwarded" not in kwargs and ALLOW_F_COMMANDS is False:
            kwargs["not_forwarded"] = True
Пример #8
0
    server = TELEGRAM_PRODUCTION
TOKEN = get_str_key("TOKEN", required=True)
OWNER_ID = get_int_key("OWNER_ID", required=True)
LOGS_CHANNEL_ID = get_int_key("LOGS_CHANNEL_ID", required=True)
OPERATORS = list(get_list_key("OPERATORS"))
OPERATORS.append(OWNER_ID)
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

ENV = bool(os.environ.get("ENV", False))

if ENV:
    TOKEN = os.environ.get("TOKEN", None)

    try:
        OWNER_ID = int(os.environ.get("OWNER_ID", None))
    except ValueError:
        raise Exception("Your OWNER_ID env variable is not a valid integer.")

    JOIN_LOGGER = os.environ.get("JOIN_LOGGER", None)
Пример #9
0
import os

import yaml
from babel.core import Locale

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

LANGUAGES = {}

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

for filename in os.listdir("SungJinwooRobot/localization"):
    log.debug("Loading language file " + filename)
    with open("SungJinwooRobot/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()
]))