示例#1
0
def processor(bot, update):
    user = update.message.from_user
    text = update.message.text
    action, params = db_user.get_action(user.id)
    settings = utils.get_settings()
    db_user.update(user)

    # Check if it is group chat
    if update.message.chat.id < 0:
        if text.startswith('/'):
            log_message(
                update.message.reply_text(utils.get_constant('not_chat')))
        return

    # logging
    logger.info('{} {} ({}:@{}): {}'.format(user.first_name, user.last_name,
                                            user.id, user.username, text))

    # Constant behavior
    for button in settings['constant_behavior']:
        if utils.get_constant(button) == text:
            behave(settings['constant_behavior'][button], bot, update)
            return

    # Checking menu
    if action in settings:
        for button in settings[action]['keyboard']:
            if get_button_text(button) == text:
                behave(button, bot, update)
    else:
        action_manager(bot, update, action)
示例#2
0
 async def deck_start(self, ctx: Context, *, description: str):
     literal = literals('deck_start')
     partner_role: Role = discord.utils.get(
         await self.deck_handler.guild.fetch_roles(),
         id=get_constant('partner_role'))
     partner_channel = await self.client.fetch_channel(
         get_constant('partner_channel'))
     if not isinstance(author := ctx.author, Member):
         author = await self.deck_handler.guild.fetch_member(ctx.author.id)
示例#3
0
 async def deck_end(self, ctx: Context, *, deck: DeckConverter = None):
     literal = literals('deck_end')
     partner_role: Role = discord.utils.get(
         await self.deck_handler.guild.fetch_roles(),
         id=get_constant('partner_role'))
     partner_channel = await self.client.fetch_channel(
         get_constant('partner_channel'))
     if deck is None:
         deck = await DeckConverter().convert(ctx, str(ctx.channel.id))
     if not isinstance(author := ctx.author, Member):
         author = await self.deck_handler.guild.fetch_member(ctx.author.id)
示例#4
0
 async def predicate(ctx: Context):
     partner_role_id = get_constant('partner_role')
     shtelo_guild_id = get_constant('shtelo_guild')
     guild = await ctx.bot.fetch_guild(shtelo_guild_id)
     member = None
     if guild is not None:
         member = await guild.fetch_member(ctx.author.id)
     if member is None:
         return False
     role = discord.utils.get(member.roles, id=partner_role_id)
     if role is None:
         return False
     return True
示例#5
0
 async def send_command_help(self, ctx: Context, command: Command):
     literal = literals('send_command_help')
     command_name = command.qualified_name
     default_signature = get_command_default_signature(command)
     footer = get_command_signature(command)
     description = ''
     if command.help is not None:
         description = command.help + '\n'
     elif command.brief is not None:
         description = command.brief + '\n'
     description += f'`{default_signature}`'
     embeds = ChainedEmbed(title=get_constant('default_prefix') + command_name, description=description)
     embeds.set_thumbnail(url=self.client.user.avatar_url)
     if not command.enabled:
         embeds.add_field(name=literal['disabled_name'], value=literal['disabled_value'])
     if isinstance(command, CustomGroup):
         embeds.add_field(name=literal['subcommand'],
                          value=f'\n{brief_group(command)}\n')
     for check in command.checks:
         data = get_check(check.name)
         if data is None:
             continue
         embeds.add_field(name=f'{data["emoji"]} {data["name"]}', value=data["description"])
     if command.cog is not None:
         category = command.cog.qualified_name
         if isinstance(command.cog, CustomCog):
             category = command.cog.emoji + ' ' + category
         footer += ' · ' + category
     embeds.set_footer(text=footer)
     for embed in embeds.to_list():
         await ctx.send(embed=embed)
示例#6
0
async def update_application(member: Member,
                             state: str,
                             remarks: str,
                             on_error=None,
                             keys=None,
                             rows=None):
    sheet = get_constant('application')
    if keys is None or rows is None:
        keys, rows = get_application_sheet()
    result = False
    for i, row in enumerate(rows):
        if str(member) in row and row[APPLICATION_STATE] != state:
            row[APPLICATION_STATE] = state
            if remarks is not None and not row[APPLICATION_REMARKS]:
                row[APPLICATION_REMARKS] = str(remarks).replace('->', '→')
            result = row.copy()
            break
    if not result:
        if on_error is not None:
            await on_error()
        raise BadArgument(f'application not found')
    result[-1] = sheet['active_time_formula'].format(i + 2)
    sheet_write(sheet['sheet_id'], sheet['insert_range'].format(i + 2),
                [result])
    return result
示例#7
0
 def predicate(ctx: Context) -> bool:
     client_permissions: dict = dict(
         ctx.guild.get_member(get_constant('kenken_id')).guild_permissions)
     for perm, value in permissions.items():
         if client_permissions[perm] != value:
             return False
     return True
示例#8
0
 def __init__(self, args: list):
     intents = Intents.default()
     intents.members = True
     super().__init__([get_constant('default_prefix')], intents=intents)
     self.load_all_extensions()
     get_event_loop().run_until_complete(
         self.start(
             config('TOKEN') if 'b' not in args else config('BETA_TOKEN')))
示例#9
0
def get_application_sheet():
    sheet = get_constant('application')
    rows = sheet_read(sheet['sheet_id'], sheet['read_range'])
    keys = rows.pop(0)
    for reply in rows:
        while len(reply) < len(keys):
            reply.append('')
    return keys, rows
示例#10
0
 async def regulation_all(self, ctx: Context):
     literal = literals('regulation_all')
     message = await ctx.send(literal['start'])
     paragraphs = wrap_codeblock(doc_read(
         get_constant('regulation')['doc_id']),
                                 split_paragraph=True)
     await message.edit(content=literal['done'])
     for p in paragraphs:
         await ctx.author.send(p)
示例#11
0
 async def channel_create_voice(self, ctx: Context, *, name: str):
     literal = literals('channel_create_voice')
     deck: Deck = await DeckConverter().convert(ctx, str(ctx.channel.id))
     check_deck_manager(deck, ctx.author)
     tester_role: Role = ctx.guild.get_role(get_constant('tester_role'))
     member_role: Role = ctx.guild.get_role(get_constant('member_role'))
     overwrites = {
         ctx.guild.default_role:
         PermissionOverwrite(view_channel=False, connect=False),
         deck.role:
         PermissionOverwrite(view_channel=True, connect=True),
         tester_role:
         PermissionOverwrite(view_channel=True),
         member_role:
         PermissionOverwrite(view_channel=True)
     }
     channel = await deck.category_channel.create_voice_channel(
         name, overwrites=overwrites)
     await ctx.send(literal['done'] % channel.mention)
示例#12
0
 def fetch_regulation(self):
     if self.regulation is None \
             or self.regulation.data is None:
         paragraphs = wrap_codeblock(doc_read(
             get_constant('regulation')['doc_id']),
                                     split_paragraph=True)
         self.regulation = FreshData(paragraphs, SECOND_PER_HOUR)
     else:
         paragraphs = self.regulation.data
     return paragraphs
示例#13
0
def get_command_signature(command: Command):
    parent = command.full_parent_name
    if len(command.aliases) > 0:
        aliases = '|'.join(command.aliases)
        fmt = '[%s|%s]' % (command.name, aliases)
        if parent:
            fmt = parent + ' ' + fmt
        alias = fmt
    else:
        alias = command.name if not parent else parent + ' ' + command.name
    return ('%s%s %s' % (get_constant('default_prefix'), alias, command.signature)).rstrip()
示例#14
0
 async def application_approve(self,
                               ctx: Context,
                               member: Member,
                               *,
                               remarks: str = None):
     literal = literals('application_approve')
     message = await ctx.send(literal['start'])
     if remarks is None:
         remarks = member.id
     await update_application(member, APPLICATION_APPROVED, remarks,
                              message.delete)
     tester_role = ctx.guild.get_role(get_constant('tester_role'))
     member_role = ctx.guild.get_role(get_constant('member_role'))
     tasks = list()
     if tester_role in member.roles:
         tasks.append(member.remove_roles(tester_role))
     if member_role not in member.roles:
         tasks.append(member.add_roles(member_role))
     tasks.append(message.edit(content=literal['done'] % member.mention))
     await asyncio.wait(tasks)
示例#15
0
def get_student(bot, update):
    action, params = db_user.get_action(update.message.from_user.id)
    user = update.message.from_user
    text = update.message.text

    if action == 'get_student':
        if len(params) > 0:
            # If we have more than one param(it's probably date) then print group's schedule with that param
            date = params[0]
            log_message(
                update.message.reply_text(
                    schedule.get_student(date=date, group=text)))
            default_menu(bot, update)
        else:
            # If we have none params, then we should save date and let user enter group
            date = text.split(',')[0]
            groups = [[KeyboardButton(utils.get_constant('back_to_menu'))]]
            for group in schedule.get_student_groups(date):
                groups.append([KeyboardButton(group['title'])])

            log_message(
                update.message.reply_text(utils.get_constant('enter_group'),
                                          reply_markup=ReplyKeyboardMarkup(
                                              groups, one_time_keyboard=True)))

            db_user.set_action(user_id=user.id,
                               action='get_student/{date}'.format(date=date))

    else:
        # Choose date if action isn't "get_student"
        dates = [[KeyboardButton(utils.get_constant('back_to_menu'))]]
        for date in sorted(schedule.get_student_dates(), reverse=True):
            dates.append(
                [KeyboardButton(date + ', ' + schedule.get_weekday(date))])

        log_message(
            update.message.reply_text(utils.get_constant('enter_date'),
                                      reply_markup=ReplyKeyboardMarkup(
                                          dates, one_time_keyboard=True)))
        db_user.set_action(user_id=user.id, action='get_student')
示例#16
0
 def item_group(self):
     """returns the major item grouping for an item, e.g. mace, armor etc"""
     own_type = self.type.lower()
     for g in ("axes", "bows", "claws", "daggers", "maces", "staves",
               "swords", "wands", "helms", "armors", "gloves", "boots",
               "shields", "belts", "quivers"):
         for k, v in get_constant(g.upper(), as_dict=True).items():
             if k.lower() in own_type:
                 # see if there is a subtype
                 if isinstance(v, str):
                     return g.title()
                 else:
                     return v.get("subtype", g.title())
     raise ValueError("%s is not a recognized item type." % self.type)
示例#17
0
 def item_group(self):
     """returns the major item grouping for an item, e.g. mace, armor etc"""
     own_type = self.type.lower()
     for g in ("axes", "bows", "claws", "daggers", "maces", "staves",
               "swords", "wands", "helms", "armors", "gloves", "boots",
               "shields", "belts", "quivers"):
         for k, v in get_constant(g.upper(), as_dict=True).items():
             if k.lower() in own_type:
                 # see if there is a subtype
                 if isinstance(v, str):
                     return g.title()
                 else:
                     return v.get("subtype", g.title())
     raise ValueError("%s is not a recognized item type." % self.type)
示例#18
0
 def load_all_extensions(self):
     for file_name in listdir(get_path('extensions')):
         if not file_name.endswith('_cog.py') and not file_name.endswith(
                 '_cmd.py'):
             continue
         module = file_name[:-3]
         Log.auto(f'loading extension: {module}')
         try:
             self.load_extension(get_constant('extension_name') % module)
         except ExtensionAlreadyLoaded as e:
             Log.error(f'extension already loaded: {e.name}')
             self.reload_extension(e.name)
         except (ExtensionFailed, NoEntryPointError, ExtensionFailed) as e:
             Log.error(e)
             raise e
示例#19
0
def add_member(member: Member, nickname=None, rows=None):
    sheet = get_constant('member_list')
    if rows is None:
        rows = sheet_read(sheet['sheet_id'], sheet['range'])
    if nickname is None:
        nickname = get_nickname_of(member)
    result = [
        int(rows[-1][0]) + 1, nickname,
        str(member.roles[-1]),
        str(member.id),
        str(to_kst(member.joined_at))
    ]
    rows.append(result.copy())
    if result:
        sheet_write(sheet['sheet_id'], sheet['range'], rows)
    return result
示例#20
0
 async def after_ready(self):
     self.shtelo_guild = self.client.get_guild(get_constant('shtelo_guild'))
     self.partner_channel = self.client.get_channel(
         get_constant('partner_channel'))
     self.member_role = self.shtelo_guild.get_role(
         get_constant('member_role'))
     self.tester_role = self.shtelo_guild.get_role(
         get_constant('tester_role'))
     self.title_div_role = self.shtelo_guild.get_role(
         get_constant('title_div_role'))
     self.deck_div_role = self.shtelo_guild.get_role(
         get_constant('deck_div_role'))
     self.partner_role = self.shtelo_guild.get_role(
         get_constant('partner_role'))
示例#21
0
def edit_member(query: str,
                nickname: Optional[str] = None,
                state: Optional[str] = None,
                rows=None):
    sheet = get_constant('member_list')
    if rows is None:
        rows = sheet_read(sheet['sheet_id'], sheet['range'])
    result = None
    for row in rows:
        if query in row:
            if nickname is not None:
                row[MEMBER_LIST_NICKNAME] = nickname
            if state is not None:
                row[MEMBER_LIST_STATE] = state
            result = row.copy()
            break
    if result:
        sheet_write(sheet['sheet_id'], sheet['range'], rows)
    return result
示例#22
0
def sub_student(bot, update):
    user = update.message.from_user
    action, params = db_user.get_action(user.id)
    text = update.message.text

    if action == 'sub_student':
        if text == utils.get_constant('unsubscribe'):
            text = None
            log_message(
                update.message.reply_text(
                    utils.get_constant('suc_unsubscribe')))
        else:
            log_message(
                update.message.reply_text(
                    utils.get_constant('suc_subscribe_group').format(
                        group=text)))

        db_user.set_sub_student(user_id=user.id, group=text)
        default_menu(bot, update)
    else:
        groups = [[KeyboardButton(utils.get_constant('back_to_menu'))]]
        for group in schedule.get_student_list():
            groups.append([KeyboardButton(group)])

        sub = db_user.get_sub_student(user.id)
        info = utils.get_constant('not_subscribed_info')
        if sub is not None:
            info = utils.get_constant('subscribed_info_group').format(
                group=sub)
            groups[0].append(KeyboardButton(utils.get_constant('unsubscribe')))

        log_message(
            update.message.reply_text(
                utils.get_constant('subscribe_group').format(info=info),
                reply_markup=ReplyKeyboardMarkup(groups,
                                                 one_time_keyboard=True)))

        db_user.set_action(user_id=user.id, action='sub_student')
示例#23
0
 def log(cls, log: str, path: str = '', **kwargs):
     now = datetime.now()
     stack = inspect.stack()
     try:
         class_ = stack[2][0].f_locals["self"].__class__.__name__
     except KeyError:
         class_ = None
     method_ = stack[2][0].f_code.co_name
     context = f'{now} - {class_}.{method_} : {log}'
     print(context)
     if not path:
         return
     message: Message = kwargs.get('message')
     if message is not None:
         if message.guild is not None:
             zer0ken = message.guild.get_member(get_constant('zer0ken_id'))
             if zer0ken is None:
                 print('--not logged : zer0ken not in this guilds')
                 return
         else:
             print('--not logged : DM')
             return
示例#24
0
    async def on_send(self, request: Request):
        literal = literals('on_send')
        key = request.addition.strip()

        async def respond(data_, key_):
            here_request = request.generate_respond(signal=BotProtocol.HERE, addition=key_ + ' ')
            addition_length = MESSAGE_MAX_LENGTH - len(str(here_request)) - 1
            here_request.addition += data_[:addition_length]
            data_ = data_[addition_length:]
            await request.message.channel.send(str(here_request), delete_after=1)
            if data_:
                for d in split_by_length(data_):
                    await request.message.channel.send(d, delete_after=1)
            done_request = request.generate_respond(signal=BotProtocol.DONE, addition=key_)
            await request.message.channel.send(str(done_request), delete_after=1)

        if key == literal['application']:
            data = json.dumps(get_application_sheet(), ensure_ascii=False)
            await respond(data, key)
        if key == literal['regulation']:
            data = doc_read(get_constant('regulation')['doc_id'])
            await respond(data, key)
示例#25
0
    async def receive_automatically(self, message: Message):
        literal = literals('receive_automatically')

        async def failed():
            await self.partner_channel.send(literal['failed'] %
                                            message.author.mention)

        if message.channel.id != get_constant(
                'self_introduction_channel') or len(message.content) < 10:
            return
        keys, rows = get_application_sheet()
        application = get_application_of(message.author, rows)
        if application is None or application[APPLICATION_STATE]:
            return
        trigger_member_name = application[APPLICATION_INVITER]
        trigger_role = self.member_role
        if not trigger_member_name:
            trigger_member_name = application[APPLICATION_SUBACCOUNT]
            trigger_role = None
        try:
            trigger_member = await MemberConverter().convert(
                await self.client.get_context(message), trigger_member_name)
        except BadArgument as e:
            await failed()
            raise e
        if trigger_role is not None and trigger_role not in trigger_member.roles:
            await failed()
            return
        remark = str(message.author.id)
        if not application[APPLICATION_INVITER]:
            remark = literal['subaccount'] % (trigger_member.id, remark)
        await self.receive_application(message.author, remark, None, keys,
                                       rows)
        await message.add_reaction(CONFIRM_EMOJI)
        if application[APPLICATION_INVITER]:
            add_member(message.author, application[APPLICATION_NICKNAME])
        await self.partner_channel.send(
            literal['done'] % (message.author.mention, message.jump_url),
            embed=get_application_embed(application))
示例#26
0
def sub_teacher(bot, update):
    user = update.message.from_user
    action, params = db_user.get_action(user.id)
    text = update.message.text

    if action == 'sub_teacher':
        if text == utils.get_constant('unsubscribe'):
            text = None
            log_message(
                update.message.reply_text(
                    utils.get_constant('suc_unsubscribe')))
        else:
            log_message(
                update.message.reply_text(
                    utils.get_constant('suc_subscribe_teacher').format(
                        teacher=text)))
        db_user.set_sub_teacher(user_id=user.id, name=text)
        default_menu(bot, update)
    else:
        teachers = [[KeyboardButton(utils.get_constant('back_to_menu'))]]
        for teacher in schedule.get_teacher_list():
            teachers.append([KeyboardButton(teacher)])

        sub = db_user.get_sub_teacher(user.id)
        info = utils.get_constant('not_subscribed_info')
        if sub is not None:
            info = utils.get_constant('subscribed_info_teacher').format(
                teacher=sub)
            teachers[0].append(
                KeyboardButton(utils.get_constant('unsubscribe')))

        log_message(
            update.message.reply_text(
                'Выберите или введите преподавателя, на которого вы хотите подписатся\n'
                + info,
                reply_markup=ReplyKeyboardMarkup(teachers,
                                                 one_time_keyboard=True)))

        db_user.set_action(user_id=user.id, action='sub_teacher')
示例#27
0
def action_manager(bot, update, action):
    if action == 'get_student':
        try:
            get_student(bot, update)
        except schedule.ScheduleException as ex:
            if ex.code == 200:
                log_message(
                    update.message.reply_text(
                        utils.get_constant('no_schedule_for_date')))
            elif ex.code == 201:
                log_message(
                    update.message.reply_text(
                        utils.get_constant('no_group_schedule')))
            else:
                log_message(
                    update.message.reply_text(
                        utils.get_constant('unknown_error').format(
                            code=ex.code, message=ex.message)))
    elif action == 'get_teacher':
        try:
            get_teacher(bot, update)
        except schedule.ScheduleException as ex:
            if ex.code == 200:
                log_message(
                    update.message.reply_text(
                        utils.get_constant('no_schedule_for_date')))
            elif ex.code == 201:
                log_message(
                    update.message.reply_text(
                        utils.get_constant('no_teacher_schedule')))
            else:
                log_message(
                    update.message.reply_text(
                        utils.get_constant('unknown_error').format(
                            code=ex.code, message=ex.message)))
    elif action == 'sub_student':
        sub_student(bot, update)
    elif action == 'sub_teacher':
        sub_teacher(bot, update)
    elif action == 'close_keyboard':
        close_keyboard(bot, update)
    elif action == 'default_menu':
        default_menu(bot, update)
    return
示例#28
0
import hashlib

from sqlalchemy import types, true, false
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.databases import postgres

from app import db
import constants
from utils import norm, normfind, get_constant

GEMS = get_constant("GEMS", as_dict=True)


class tsvector(types.TypeDecorator):
    """
    using tsvectors for full text search in sqlalchemy, custom type definition

    http://stackoverflow.com/questions/13837111/
    """
    impl = types.UnicodeText


@compiles(tsvector, 'postgresql')
def compile_tsvector(element, compiler, **kw):
    return 'tsvector'


def in_page_group(group_name):
    premium_pages = Location.query.filter(
        Location.is_premium,
        Location.is_character == false(),
示例#29
0

"""force a fetch of all the constants"""
CONSTANTS = [
    "GEMS",
    "UNIQUES",
    "QUIVERS",
    "BELTS",
    "WANDS",
    "STAVES",
    "DAGGERS",
    "CLAWS",
    "GLOVES",
    "BOOTS",
    "SHIELDS",
    "HELMS",
    "ARMORS",
    "BOWS",
    "AXES",
    "MACES",
    "SWORDS",
    "PREFIXES",
    "SUFFIXES",
    "CURRENCIES",
    "FLASK_SIZES",
    "MISC_FLASKS",
    "QUEST_ITEMS",
]
for c in CONSTANTS:
    get_constant(c)
示例#30
0
from flask import request, render_template
from flask.views import View, MethodView
from jinja2 import contextfilter
from jinja2.filters import do_mark_safe
from sqlalchemy import false, not_, and_

from app import app, db, manager
import constants
from models import (Item, Location, Property, Requirement, Modifier,
                    in_page_group)
from utils import get_constant

#  init constants
CHROMATIC_RE = r"B+G+R+"
GEMS = get_constant("GEMS", as_dict=True)
QUIVERS = get_constant("QUIVERS", as_dict=True)


@app.template_filter('percent')
def percent_filter(x):
    return "%.2f%%" % (x * 100)


@app.template_filter('socket')
def socket_filter(x):
    """outputs nice html for a socket string"""
    out = []
    for c in x:
        if c == "B":
            out.append('<span class="label label-primary">&nbsp;</span>')
示例#31
0
 def predicate(ctx: Context) -> bool:
     return ctx.author.id in (get_constant('zer0ken_id'), )
示例#32
0
 async def on_message(self, message):
     if message.author.id == get_constant('kenken_id'):
         return
     await super().on_message(message)
示例#33
0
            TWO_HANDED_WEAPONS[k] = v
"""
"""force a fetch of all the constants"""
CONSTANTS = [
    "GEMS",
    "UNIQUES",
    "QUIVERS",
    "BELTS",
    "WANDS",
    "STAVES",
    "DAGGERS",
    "CLAWS",
    "GLOVES",
    "BOOTS",
    "SHIELDS",
    "HELMS",
    "ARMORS",
    "BOWS",
    "AXES",
    "MACES",
    "SWORDS",
    "PREFIXES",
    "SUFFIXES",
    "CURRENCIES",
    "FLASK_SIZES",
    "MISC_FLASKS",
    "QUEST_ITEMS",
]
for c in CONSTANTS:
    get_constant(c)
示例#34
0
import hashlib

from sqlalchemy import types, true, false
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.databases import postgres

from app import db
import constants
from utils import norm, normfind, get_constant

GEMS = get_constant("GEMS", as_dict=True)


class tsvector(types.TypeDecorator):
    """
    using tsvectors for full text search in sqlalchemy, custom type definition

    http://stackoverflow.com/questions/13837111/
    """
    impl = types.UnicodeText


@compiles(tsvector, 'postgresql')
def compile_tsvector(element, compiler, **kw):
    return 'tsvector'


def in_page_group(group_name):
    premium_pages = Location.query.filter(
        Location.is_premium,
        Location.is_character == false(),