Esempio n. 1
0
def text2malk(text, prob=0.5):
    if '```' in text:
        return text
    # code style look bad on mobile devices # '`', '**`', '_`', '_`',
    f_set = {
        '**',
        '***',
        '_',
        '_',
    }  # '~~', # italic more often then others
    esc = {
        '*',
        '_',
        '~',
        '`',
        '|',
        '\\',
    }
    dont_touch = {
        '#', '@', '&', '<', '>', '0', '1', '2', '3', '4', '5', '6', '7', '8',
        '9'
    }
    was_esc = False
    last_f = '0'

    new_text = []
    for i, symb in enumerate(text):  # type: int, str
        if symb in string__whitespace or symb in dont_touch:
            new_text.append(symb)
            continue
        elif was_esc and symb in esc:
            was_esc = False
            new_text.append(symb)
            last_f = symb
            continue
        elif symb == '\\':
            next_symb = text[i + 1:]
            if next_symb and next_symb[0] in esc:
                was_esc = True
                new_text.append(symb)
            continue
        elif symb in esc:
            continue

        was_esc = False
        if symb != '.' and other.rand() <= prob:
            prob2 = other.rand()
            new_s = symb.upper() if prob2 <= 0.5 else symb
            if prob2 > 0.1:
                f = other.choice({s for s in f_set if s[0] != last_f[0]})
                last_f = f
                new_text.append(f + new_s + f[::-1])
            else:
                last_f = new_s
                new_text.append(new_s)
        else:
            last_f = symb
            new_text.append(symb)

    return ''.join(new_text)
Esempio n. 2
0
def text2leet(text, prob=0.25):
    new_text = []
    esc = {
        '*',
        '_',
        '~',
        '`',
        '|',
        '\\',
    }
    dont_touch = {
        '#', '@', '&', '<', '>', '0', '1', '2', '3', '4', '5', '6', '7', '8',
        '9'
    }
    for symb in text:
        if symb in data_com.dct_leet and symb not in dont_touch and other.rand(
        ) <= prob:
            new_s = other.choice(data_com.dct_leet[symb])  # type: str
            esc_s = esc.intersection(new_s)
            if esc_s and symb not in esc:
                for s in esc_s:
                    new_s = new_s.replace(s, '\\' + s)
        else:
            new_s = symb
        new_text.append(new_s)
    return ''.join(new_text)
Esempio n. 3
0
def _beckett_m_type(msg)->str:
    yes = 'да' in msg.words
    no = 'не' in msg.words or 'нет' in msg.words
    if msg.words.intersection({'спасибо', 'благодарю'}):  #'спасибо'
        return 'wlc'
    elif msg.words.intersection(data.sm_resp['hi_plus']) or 'доброго времени суток' in msg.text:
        return 'hi_plus'
    elif msg.words.intersection(data.sm_resp['fun_smiles']):
        return 'fun_smiles'
    elif msg.words.intersection(data.sm_resp['bye']):
        return 'bye'
    elif msg.words.intersection(data.sm_resp['bot_dog']):
        if msg.admin or other.rand() > 0.2:
            return 'not_funny'
        else:
            return 'bot_dog'
    elif msg.words.intersection(data.sm_resp['check_love']) and not no:
        return 'love'
    elif msg.words.intersection(data.sm_resp['check_like']) and not no:
        return 'like'
    elif 'любимый клан' in msg.text:
        if other.rand() > 0.09:
            return 'apoliticality'
        else:
            return 'tremer_joke'
    elif msg.words.intersection({'как'}) and msg.words.intersection({'дела', 'делишки', 'ты', 'чё', 'че'}):
        return 'whatsup'
    elif 'shchupalko' in msg.text:
        return 'shchupalko'
    # other questions must be before this
    elif msg.text.rstrip(')(.! ').endswith('?'):
        if (msg.admin or (msg.moder and other.rand() < 0.7) or
                (C.roles['Primogens'] in msg.roles and other.rand() < 0.3) or
                (msg.auid == C.users['aleth_lavellan'] and other.rand() < 0.5)):
            if (yes == no) or yes:
                return 'yes'
            else:
                return 'no'
        elif len(msg.args) > 3:
            return 'question'
    elif msg.words.intersection({'скучал', 'скучала', 'скучаль'}):
        return 'boring'
    elif ('мимими' in msg.text) or len(msg.words) < 4:
        return 'no-response'
    return ''
Esempio n. 4
0
def _check_status_change(user):
    prob = other.rand()
    g_key_check = prob < 0.01
    g_key = people.online_ev(user.id) if (
        g_key_check and user.id not in ram.ignore_users) else False
    if g_key:
        gt_key = {'g_key': g_key, 'g_type': 0}
        phr = com.phrase_gt(gt_key, user.id)
        if phr:
            com.write_msg(C.main_ch, phr)
            people.set_gt(user.id, gt_key['g_key'])
Esempio n. 5
0
def _beckett_ans(m_type, author_id):
    prob = other.rand()
    ans = None
    keys = {'sm_resp'}
    punct = True
    name_phr = False
    if not m_type:
        ans = ''
    elif 'no-response' in m_type:
        ans = 'no-response'
    elif m_type in {'wlc', 'bye', 'yes', 'no', 'hi_plus', 'not_funny', 'fun_smiles'}:
        keys.add(m_type)
        name_phr = True
    elif m_type == 'love':
        if author_id == C.users['Natali']:
            ans = (emj.e_str('a_Toreador_light'), emj.e_str('a_Toreador_wave')) if prob < 0.1 else ':purple_heart:'
        elif author_id == C.users['aleth_lavellan']:
            ans = ('💜', '❤', '💗', '😘', '💙', '♥', '💓', '💚', '💞', '💕', '💛', '💖', '🤗')
        elif author_id == C.users['AyrinSiverna']:
            ans = ('🌹', '🌷', '❤', '♥', '😘', '☺',)
        else:
            ans = (':heart:', ':hearts:', ':kissing_heart:', ':relaxed:')
        ans = other.name_phr(author_id, ans, punct=False)
    elif m_type == 'like':
        ans = 'no-response'
    elif m_type == 'apoliticality':
        keys.add(m_type)
    elif m_type == 'tremer_joke':
        ans = data.tremer_joke
    elif m_type == 'bot_dog':
        ans = com.get_t('threats', name=author_id)
    elif m_type == 'shchupalko':
        ans = f"<@{author_id}> {emj.e(other.choice('s_shchupalko0', 's_shchupalko1', 's_shchupalko3'))}"
    elif m_type in {'whatsup', 'question'}:
        keys = {m_type}
    elif m_type == 'boring':
        ans = other.name_phr(author_id, 'я тоже')
    else:
        ans = ''

    if ans is None:
        text = com.get_t(all_keys=keys)
        punct = punct and text not in data.sm_resp['ans_smiles']
        ans = other.name_phr(author_id, text, punct=punct) if name_phr else text

    return ans
Esempio n. 6
0
async def on_member_update_u(before: C.Types.Member, after: C.Types.Member):
    # it's triggers on changing status, game playing, avatar, nickname or roles
    #
    if after.id == C.users['bot']:
        return

    smth_happend = False
    a_n = other.uname(after) + f' [{after.id}]'

    if before.display_name != after.display_name or before.name != after.name:
        smth_happend = True
        b_n = other.uname(before)
        log.pr_news(f'<on_member_update> {b_n} change nickname to {a_n}.')

    if before.game != after.game:
        smth_happend = True
        if before.game and after.game:
            log.D(
                f'<on_member_update> {a_n} go play from {before.game.name} to {after.game.name}.'
            )
        elif before.game:
            log.D(f'<on_member_update> {a_n} stop play {before.game.name}.')
        elif after.game:
            log.D(f'<on_member_update> {a_n} start play {after.game.name}.')
        else:
            log.D(
                f'<on_member_update> {{???}} {a_n} - game change, but there are no games...'
            )

        if after.id == C.users['Natali']:
            if before.game and C.prm_server.me.game.name == before.game.name:
                await other.set_game('')
            if after.game and not C.prm_server.me.game:
                await other.set_game(after.game.name)

        user_g = user_games.pop(after.id, {'name': '', 'h': 0})
        # degradation
        if False and other.rand() < 0.5 and (
                before.game and before.game.name
                and after.id not in ram.ignore_users and people.was_writing(
                    after.id, 48) and user_g['h'] >= TMR_IN_H):
            phr = com.get_t('game',
                            user=f'<@{after.id}>',
                            game=f"«{user_g['name']}»")
            com.write_msg(C.main_ch, phr)

        if after.game and after.game.name:
            user_games[after.id] = {'name': after.game.name, 'h': 0}

    if before.avatar_url != after.avatar_url:
        smth_happend = True
        urls = []
        for url in (before.avatar_url, after.avatar_url):
            urls.append(' ?'.join(url.split('?', maxsplit=1)))
        b_url, a_url = urls

        if before.avatar_url and after.avatar_url:
            await log.pr_avs(
                f'<on_member_update> {a_n} change avatar from \n{a_url} \nto\n{b_url}'
            )
        elif before.avatar_url:
            await log.pr_avs(
                f'<on_member_update> {a_n} delete avatar: \n{b_url}')
        elif after.avatar_url:
            await log.pr_avs(f'<on_member_update> {a_n} set avatar: \n{a_url}')
        else:
            log.I(
                f'<on_member_update> {{???}} {a_n} - avatar change, but there are no avatar_urls...'
            )

        # small degradation
        if (other.rand() < 0.01 and after.avatar_url
                and after.id not in ram.ignore_users
                and people.was_writing(after.id, 48)):
            phr = com.get_t('new_avatar', user=f'<@{after.id}>')
            com.write_msg(C.main_ch, phr)

    if before.roles != after.roles:
        smth_happend = True
        old_roles = [('@&' + r.name) for r in before.roles
                     if r not in after.roles]
        new_roles = [('@&' + r.name) for r in after.roles
                     if r not in before.roles]
        if old_roles:
            log.pr_news(
                f'<on_member_update> {a_n} lost role(s): {", ".join(old_roles)}.'
            )
        if new_roles:
            log.pr_news(
                f'<on_member_update> {a_n} get role(s): {", ".join(new_roles)}.'
            )
            new_role_ids = {r.id for r in after.roles if r not in before.roles}
            new_clan_roles = C.clan_ids.intersection(new_role_ids)
            has_clan_before = other.has_roles(before, C.clan_ids)
            if after.id not in not_embrace and new_clan_roles and not has_clan_before:
                clan_id = other.choice(new_clan_roles)
                clan_name = C.role_by_id[clan_id]
                log.pr_news(
                    f'<on_member_update> {a_n} get new clan role "{clan_name}" => call do_embrace.'
                )
                manager.just_embrace_say(after, clan_name=clan_name)
                # if sir_id:
                #     if clan_id in C.clan_channels:
                #         clan_ch = C.clan_channels[clan_id]
                #         phr = com.get_t(all_keys=('clan_welcome', clan_ch), user=f'<@{after.id}>', sir=f'<@{sir_id}>')
                #         com.write_msg(clan_ch, phr)

            elif has_clan_before and C.roles['Pander'] in new_clan_roles:
                log.jI(
                    f'<on_member_update> {a_n} go to Pander => delete other clan roles if it\'s exist.'
                )
                del_clans_id = C.clan_ids.difference({C.roles['Pander']})
                rem_roles = {r for r in after.roles if r.id in del_clans_id}
                if rem_roles:
                    other.rem_roles(after, rem_roles, 'on_member_update_u[1]')
                    str_rem_r = f"<@&{'>, <@&'.join(r.id for r in rem_roles)}>"
                    phr = com.get_t('to_Pander',
                                    user=f'<@{after.id}>',
                                    old_clans=str_rem_r,
                                    pander=f"<@&{C.roles['Pander']}>")
                    com.write_msg(C.main_ch, phr)
            elif C.roles['Mortal'] in new_role_ids:
                if has_clan_before:
                    # go to food
                    rem_roles = {
                        r
                        for r in after.roles
                        if r.id not in C.mortal_can_have_roles
                    }
                    other.rem_roles(after, rem_roles, 'go to Mortal(food)')
                    log.pr_news(f'<on_member_update> {a_n} go to food')
                else:
                    # new user
                    await C.client.send_message(C.main_ch,
                                                com.welcome_msg(before.id))
                    log.pr_news(f'<on_member_update> {a_n} welcome')

            if C.roles['Sabbat'] in new_role_ids:
                clan_ch = C.clan_channels[C.roles['Sabbat']]
                phr = com.get_t(all_keys=('clan_welcome', clan_ch),
                                user=f'<@{after.id}>')
                com.write_msg(clan_ch, phr)

    if before.status != after.status or not smth_happend:
        people.online_change(after.id,
                             after.status,
                             force=before.status == after.status)
        # small degradation
        _check_status_change(after)

    if (smth_happend
            or people.is_online(after.id)) and before.roles == after.roles:
        on_user_life_signs(after.id)
Esempio n. 7
0
def get_dices_v5(count=1, diff=0, hung=0, simple=False, short=False):
    text = []
    dices = []
    count_tens = 0
    for i in range(0, count):
        d = other.rand(1, 10)
        dices.append(d)
        count_tens += 1 if d == 10 else 0

    if simple:
        if short:
            text = ['{val}'.format(val=_get_val_v5(dice, short=True)) for dice in dices]
        else:
            text = ['{:02d}d:\t{val}\n'.format(i + 1, val=_get_val_v5(dice)) for i, dice in enumerate(dices)]
    else:
        if short:
            text.append('(')
        was_h1 = False
        was_h10 = False
        res = 0
        crit_tens = int(count_tens/2)*2
        norm_dices = max(count - hung, 0) # other: hung_dices
        for i, dice in enumerate(dices):
            hunger = i >= norm_dices
            succ = dice > 5
            aft = ''
            if succ:
                res += 1
                if dice == 10:
                    if crit_tens > 0:
                        aft = ' (+)'
                        res += 1
                        crit_tens -= 1
                    symb = '!'
                    was_h10 = hunger or was_h10
                else:
                    symb = '+'
            else:
                symb = '•'
                was_h1 = was_h1 or (hunger and dice == 1)
            symb = '-' if hunger else symb
            if short:
                if hunger and i == norm_dices:
                    text.append(r'\|\|')
                frm = '__' if aft else ''
                text.append('{frm}{val}{frm}'.format(val=_get_val_v5(dice, hunger, short=True), frm=frm))
            else:
                text.append('{} {:02d}d:\t{val}{aft}\n'.format(symb, i + 1, val=_get_val_v5(dice, hunger), aft=aft))

        if res >= diff:
            if count_tens > 1:
                conclusion = (('- {}', '**__`{}`__**')[short].format('Messy Critical')
                              if was_h10 else ('! {}', '**__{}__**')[short].format('Critical Win'))
            else:
                conclusion = ('+ {}', '**{}**')[short].format('Success') #'+ Win'
            conclusion = ('{} ({} {})', '{} *({} {})*')[short].format(conclusion, 'margin:', res - diff)
        else:
            if was_h1:
                conclusion = ('- {}', '**`{}`**')[short].format('Bestial Failure')
            elif res > 0:
                conclusion = ('• {} ({} {})', '{} *({} {})*')[short].format('Failure', 'win at a cost:', diff - res)
            else:
                conclusion = ('● {}', '{}')[short].format('Total Failure')

        if short:
            text.append('):')
        text.append(conclusion)
    return text
Esempio n. 8
0
def get_rolles(count=1, dtype=10, par_keys:set='', rel='ge', diff=6,
               sum0=0, sum1=0, d_fail=None, simple=True, short=False, calc_sum=False, _add_d=False):
    text = []
    dices = []
    res = 0
    was_success = False

    for i in range(0, count):
        d = other.rand(1, dtype)
        dices.append(d)

    if simple and not calc_sum:
        if short:
            text = [str(dice+sum0) for dice in dices]
        else:
            text = ['{:02d}d:\t{val}\n'.format(i + 1, val=dice+sum0) for i, dice in enumerate(dices)]
    else:
        if short and not _add_d:
            text.append('(')
        add_dices = 0
        double_ten = False
        for i, dice in enumerate(dices):
            succ = simple or getattr(operator, rel)(dice+sum0, diff)
            aft = ''
            # process one dice
            if succ:
                change_val = (dice + sum0) if calc_sum else +1
                res += change_val
                was_success = True
                if dice == dtype and dtype > 1 and par_keys:
                    if 'sp' in par_keys:
                        res += change_val
                        aft = '(+)'
                    elif 'p' in par_keys:
                        aft = double_ten and '(+)' or ''
                        res += int(double_ten) * change_val
                        double_ten = not double_ten
                    elif 'v' in par_keys:
                        aft = double_ten and '(++)' or ''
                        res += 2 * int(double_ten) * change_val
                        double_ten = not double_ten
                    elif 's' in par_keys:
                        add_dices += 1
                        aft = '(*)'
                change_val = +1
            else:
                change_val = 0
                if d_fail is not None and (dice + sum0) <= d_fail:
                    change_val = -(dice + sum0) if calc_sum else -1
                    res += change_val
                    change_val = -1
            # text format
            if short:
                if calc_sum:
                    if i > 0 or change_val < 0:
                        text.append('+' if change_val >= 0 else '-')
                symb = '' if simple else _get_symb(change_val, True)
                symb2 = '__**' if aft else ''
                text.append('{symb2_1}{symb}{val}{symb}{symb2_2}'.
                            format(symb=symb, val=dice+sum0, symb2_1=symb2, symb2_2=symb2[::-1]))
            else:
                symb = ('!' if aft else '•') if simple else _get_symb(change_val)
                aft = ' ' + aft if aft else ''
                text.append('{} {:02d}d:\t{val}{aft}\n'.format(symb, i+1, val=dice+sum0, aft=aft))
        # process add_dices
        if _add_d:
            return res, text, add_dices
        while add_dices:
            if short:
                text.append(r'\|{}\| \*__{{{}}}__:'.format(r'\|+\|' if calc_sum else '', add_dices))
            else:
                text.append('*** Специализация({}):\n'.format(add_dices))
            (add_res, add_text, add_dices) = get_rolles(add_dices, dtype, par_keys, rel, diff, sum0, sum1, d_fail,
                                                        short=short, simple=simple, calc_sum=calc_sum, _add_d=True)
            res += add_res
            text += add_text
        # total result
        if sum1 != 0:
            res += sum1
            symb = '+' if sum1 > 0 else '-'
            text.append(f') {sum1:+}' if short else f'{symb} add:\t{sum1:+}\n')
        elif short:
            text.append(')')

    return text, res, was_success
Esempio n. 9
0
def _send_reaction(msg:Msg, m_type, text, edit=False):
    if not m_type or not text:
        return

    log.I(('<reaction.edit>' if edit else '<reaction>') + f'[{m_type}]')

    if text == 'no-response' or m_type == 'no-response':
        return

    if (m_type not in ('rand_tableflip', 'unflip', 'shrug') and ':' not in text
            and msg.roles.intersection((C.roles['Nosferatu'], C.roles['Malkavian'])) and other.rand() < 0.1):
        if C.roles['Malkavian'] in msg.roles:
            text = com.text2malk(text, 1)
        elif C.roles['Nosferatu'] in msg.roles:
            text = com.text2leet(text, 0.25)

    save_obj = _data_msgs_add(msg, m_type)
    if text != 'no-response' and m_type != 'no-response':
        _data_tp_add(msg, com.write_msg(msg.channel, text=text, save_obj=save_obj,
            fun=data_tp_del(msg.channel.id, msg.message.id)))
Esempio n. 10
0
def _emj_on_message(msg:Msg, beckett, edit=False):
    message = msg.message
    author = msg.auid

    if author in ram.ignore_users or msg.is_bot:
        return

    pause_and_add, pause_and_rem, e, e_str = emj.pause_and_add, emj.pause_and_rem, emj.e, emj.e_str
    prob = other.rand()

    sm_for_beckett = {
        C.users['Natali']: (*('purple_heart',) * 5, 'relaxed', 'blush',
                                                        'kissing_closed_eyes', 'kissing_heart', 'slight_smile'),
        C.users['Doriana']: ('octopus',),
        C.users['Hadley']: ('a_Toreador_light', 'a_Toreador_wave',),
        C.users['AyrinSiverna']: ('Ankh_Sabbat', 't_torik21', 'Logo_Toreador', 'hearts',),
        C.users['Rainfall']: ('green_heart',),
        C.users['Tony']: ('Logo_Ventrue',),
        C.users['aleth_lavellan']: ('hugging', 'relieved', 'kissing_cat', 'wink', 'flushed'),
    }
    prob_for_beckett = {
        C.users['Natali']: 0.4,
    }
    sm_for_nothing = {
        C.users['Natali']: ('purple_heart', 'heart_eyes', 'heart_eyes_cat'),
        C.users['Doriana']: ('black_heart',),
        C.users['Hadley']: ('Logo_Toreador',),
        C.users['AyrinSiverna']: ('Logo_Toreador',),
        C.users['Rainfall']: ('racehorse',),
        C.users['aleth_lavellan']: ('purple_heart', 'relieved', 'smiley_cat', 'aleth_wink'),
    }
    prob_for_nothing = {
        C.users['Natali']: 0.01,
    }
    sm_by_jiznbol = ('((', 'Т_Т', 'T_T', ':С', ':C', '😭', '😢', '😣', '😖', '😫', '😩', 's_blood_cry')
    sm_by_fun = ('))', ':D', 'XD', '😃', '😁', '😀', '😄', 'm_wafer', 'm_Tilia_fase', '😂', '😆', '😹', '🤣')

    if msg.chid == C.channels['stuff'] and (message.attachments or message.embeds):
        log.jD(f'emj.in_staff, prob = {prob}.')
        if author == C.users['Natali'] and prob < 0.5:
            log.jD('Like Natali in staff')
            pause_and_add(message, ('purple_heart', 'heart_eyes', 'heart_eyes_cat', 'heartpulse'))
        elif author in {C.users['Doriana'], C.users['Tilia'], C.users['Buffy']} and prob < 0.2:
            log.jD('Like Doriana or Tilia or Buffy in staff')
            pause_and_add(message, ('heart', 'hearts', 'heart_eyes', 'black_heart'))
        elif author in {C.users['Hadley'], C.users['cycl0ne'], C.users['Magdavius']} and prob < 0.2:
            log.jD('Like Hadley or cycl0ne or Magdavius in staff')
            pause_and_add(message, ('thumbsup', 'ok_hand', 'heart_eyes_cat'))

    if edit:
        return

    if prob > 0.99:
        if other.s_in_s(sm_by_jiznbol, msg.original):
            pause_and_add(message, ('t_jiznbol1', 't_jiznbol2'))
        elif other.s_in_s(sm_by_fun, msg.original):
            pause_and_add(message, ('smiley', 'slight_smile', 'grin', 'grinning', 'smile', 'upside_down'))

    if beckett and author in sm_for_beckett and prob < prob_for_beckett.get(author, 0.25):
        log.jD(f'Like {C.usernames[author]} for Beckett with chance {prob_for_beckett.get(author, 0.25)}.')
        pause_and_add(message, sm_for_beckett[author])
    elif author in sm_for_nothing and prob < prob_for_nothing.get(author, 0.005):
        log.jD(f'Like {C.usernames[author]} with chance {prob_for_nothing.get(author, 0.005)}.')
        pause_and_add(message, sm_for_nothing[author])
    elif author == C.users['aleth_lavellan'] and other.s_in_s(('папка', 'папа', 'батя'), msg.text):
        pause_and_add(message, ('blush', 'slight_smile', 'cowboy', 'p_beckett1'))

    # Day Events
    if not data.day_events:
        return

    prob = other.rand()
    now = other.get_now()

    # if birthday user is mentioned in msg -> copy emoji from msg under this msg
    if data.day_events.intersection(message.raw_mentions):
        em_in_text = emj.get_em_names(msg.original)
        em_in_text = [emj.e_or_s(em) for em in em_in_text]
        del_em = set()
        for react in msg.message.reactions: # type: C.Types.Reaction
            if react.me and react.count < 2:
                del_em.add(react.emoji)
        common_em = del_em.intersection(em_in_text)
        del_em.difference_update(common_em)
        em_in_text = [em for em in em_in_text if em not in common_em]
        pause_and_rem(message, del_em, t=0, all_=True)
        pause_and_add(message, em_in_text, 1, all_=True)
    # birthday emojis to birthday user
    if author in data.day_events:
        pause_and_add(message, ('🎂', '🍰', '🎈', '🎁', '🎊', '🎉', '💰', '💸', '💵', '💴', '💶', '💷',
                                '🖼', '🌠', '🎇', '🎆', '📯', '🆙', '🎯', '🎰', '🥇', '🏅', '🎖', '🏆', '💛',))

    if C.events['Valentine\'s Day'] in data.day_events and now.hour > 3:
        if (author in {C.users['Natali'], C.users['Hadley']} or
                ((msg.admin or msg.moder or C.roles['Primogens'] in msg.roles) and prob < 0.25)):
            pause_and_add(message, {'❤', '💛', '💙', '💜', '❣', '💕', '💞', '💓', '💗', '💖', '💝', '♥'})
        elif prob < 0.1:
            pause_and_add(message, {'💌', '💟', })

    elif C.events['8 March'] in data.day_events and now.hour > 3:
        if author == C.users['Natali'] and prob < 0.1:
            pause_and_add(message, ('a_Toreador_light', 'a_Toreador_wave'))
        elif C.roles['Tzimisce'] in msg.roles:
            pause_and_add(message, 'wilted_rose')
        elif author in C.female:
            if ((msg.admin or msg.moder or C.roles['Primogens'] in msg.roles) and prob < 0.5) or prob < 0.1:
                pause_and_add(message, ('a_open_flower', 'a_rose_grows', 'a_heart_rose', 'a_rose_pulse',
                                        'a_flower_twink', 'a_color_flower', 'a_water_lily', 'a_flower_chameleon'))
            elif C.roles['Toreador'] in msg.roles and prob < 0.2: # 10%: 0.1-0.2
                pause_and_add(message, 'Logo_Toreador')
            else:
                pause_and_add(message, ('🌺', '🌻', '🌹', '🌷', '🌼', '🌸', '💐'))
Esempio n. 11
0
async def reaction(message, edit=False):
    msg = Msg(message)

    # in vtm open channels, save date of last message
    if msg.is_vtm:
        save = msg.chid == C.channels['flood']
        if not save:
            every_prm = msg.channel.overwrites_for(C.vtm_server.default_role)
            save = every_prm.read_messages is not False
        if save:
            ram.last_vtm_msg = other.get_sec_total()

    if msg.auid == C.users['bot']:
        if msg.original == data.tremer_joke:
            other.later_coro(20, msg.delete('tremer_joke'))
        if msg.auid in data.day_events:
            _emj_on_message(msg, False, edit)
        return

    if msg.torpor:
        await msg.delete('torpor')
        return

    if C.roles['Silence'] in msg.roles:
        await msg.delete('Silence')
        ram.silence_ans[msg.auid] = ram.silence_ans.setdefault(msg.auid, 0) + 1
        if ram.silence_ans[msg.auid] < 4:
            msg.answer(f'Неугодный <@{msg.auid}> пытается нам нечто сказать, но заноза в сердце мешает...')
        return

    # delete messages containing forbidden links
    if not msg.admin:
        if any(link in msg.text for link in data.forbiddenLinks):
            log.I(f'<reaction> forbidden links')
            await msg.delete('forbidden links')
            msg.answer(com.get_t('threats', name=msg.auid))
            return

    # delete double messages for last 60 sec
    if (
        not msg.super and not msg.personal and
        not (msg.text.startswith('!r') or msg.text.startswith('!shuffle')) and
        not edit and
        not (msg.message.attachments or msg.message.embeds)
    ):
        txt_now = (msg.original +
                   ''.join([str(att.get('url', other.rand())) for att in msg.message.attachments]) +
                   ''.join([str(emb.get('url', other.rand())) for emb in msg.message.embeds]))
        get_sec_now = other.get_sec_total()
        new_last_msgs = []
        user_last_msgs = last_msgs.get(msg.auid, [])
        for txt, date in user_last_msgs:
            if (get_sec_now - date) < 60:
                new_last_msgs.append((txt, date))
                if txt == txt_now:
                    await msg.delete('double messages')
                    return

        new_last_msgs.append((txt_now, get_sec_now))
        last_msgs[msg.auid] = new_last_msgs
        # log.D(f'last_msgs["{msg.author.name}"]: {len(last_msgs[msg.auid])}.')
        # log.D(f'txt_now: {txt_now}.')

    if not msg.is_bot:
        # if edit msg with "good_time" or command - do nothing
        resp = _data_msgs_check(msg)
        if edit and resp and (resp['type'].startswith('cmd_') or resp['type'] == 'gt'):
            return

        # if we have !cmd -> doing something
        if msg.text.startswith('!'):
            fun = re.match(r'!\w*', msg.text).group(0)[1:]
            if fun in msg.get_commands():
                msg.prepare(fun)
                log.I(f'<reaction> [cmd] {fun}')
                _data_msgs_add(msg, 'cmd_' + fun)
                await getattr(cmd, fun)(msg)
                return

        m_type, text = _do_reaction(msg, edit)

        if edit:
            old_type = resp['type'] if resp else ''
            if old_type == m_type:
                return

            if old_type and not m_type:
                return

            if m_type and old_type and text:
                log.I(f'<reaction> edit [{old_type}] to [{m_type}]')
                typing = _data_tp_check(msg)
                if typing in com.msg_queue.get(msg.channel.id, ()) or old_type == 'no-response':
                    com.rem_from_queue(msg.channel.id, typing)
                    # and type new mess
                else:
                    for mess in resp['ans']:
                        await C.client.edit_message(mess, new_content=text) # if mess>1, all will be with the same text
                    resp['type'] = m_type
                    return
            # elif m_type and not old_type:
    else:
        m_type, text = _do_reaction(msg, edit)

    _send_reaction(msg, m_type, text, edit)
Esempio n. 12
0
def _do_reaction(msg:Msg, edit=False) -> (str, str):
    m_type = None
    # embrace_or_return = False

    msg.prepare2()
    beckett_reference = bool(C.beckett_refs.intersection(msg.words))
    beckett_mention = bool(C.beckett_names.intersection(msg.words))
    beckett = beckett_reference or beckett_mention or msg.personal
    _emj_on_message(msg, beckett, edit)

    if (ram.mute_channels.intersection({msg.channel.id, 'all'}) or msg.auid in ram.ignore_users or
            msg.channel.id in C.ignore_channels or (msg.channel.id in ram.test_channels and not C.is_test)):
        # # turn off embrace by message
        # if msg.channel.id == C.channels['ask']:
        #     embrace_or_return = True
        # else:
        #     return '', ''
        return '', ''

    if msg.is_bot:
        m_type = 'bot'
        if (beckett_reference or beckett_mention) and other.rand() < 0.05:
            ans_phr = com.get_t(m_type)
            return m_type, ans_phr

        log.jD('Ignore bot')
        return 'no-response', ''

    found_keys = com.check_phrase(msg.text, msg.words)
    prob = other.rand()

    # # embrace # turn off embrace by message
    # if msg.channel.id == C.channels['ask'] and not msg.roles.intersection(C.clan_ids) and not msg.author.bot:
    #     clan_keys = list(C.clan_names.intersection(found_keys))
    #     if clan_keys:
    #         clan = other.choice(clan_keys)
    #         other.later_coro(other.rand(20, 50), manager.do_check_and_embrace(msg.auid, clan_name=clan))
    #         # get 100% to comment of chosen clan
    #         beckett = True
    #         found_keys = clan
    # elif embrace_or_return:
    #     return '', ''

    # if (msg.channel.id == C.channels['gallery'] and msg.auid in (C.users['Hadley'], C.users['Natali']) and
    #         (msg.message.attachments or msg.message.embeds) and prob < 0.2):
    #     log.jI('gallery event')
    #     phr = com.get_t('gallery_picture', user=f'<@{msg.auid}>')
    #     com.write_msg(C.main_ch, phr)

    gt = msg.check_good_time(beckett)
    if gt:
        return 'gt', gt
    elif gt == '':
        m_type = 'was-good-time no-response'

    if found_keys:
        if not beckett and ram.mute_light_channels.intersection({msg.channel.id, 'all'}):
            return '', ''
        response = False

        if msg.channel.id == C.channels['sabbat']:
            if 'Sabbat' in found_keys:
                found_keys.remove('Sabbat')
                found_keys.add('Sabbat2')
            if prob < 0.02 or beckett:
                response = True
        else:
            if prob < 0.2 or beckett:  #beckett_reference or (beckett_mention and (prob < 0.9 or msg.admin)):
                response = True

        if response:
            ans_phr = com.get_text_obj(found_keys)
            if ans_phr['text']:
                t = ans_phr['text']
                if ans_phr['last_key'] == 'Nosferatu' and other.rand() < 0.4:
                    t = com.text2leet(ans_phr['text'], 0.25)
                elif ans_phr['last_key'] == 'Malkavian' and other.rand() < 0.4:
                    t = com.text2malk(ans_phr['text'], 1)

                if ans_phr['last_key'] == 'Tarkin' and prob > 0.05 and not beckett:
                    return '', ''

                return ans_phr['last_key'], t
    else:
        if other.check_fliproll(msg.original):
            if '┻' in msg.original:
                len_table = msg.original.count('━')
                len_wave = msg.original.count('︵')
                if msg.admin:
                    return 'rand_tableflip', other.rand_tableflip(len_wave, len_table)
                elif msg.channel.id == C.channels['bar']:
                    if C.roles['Primogens'] in msg.roles or prob < 0.2:
                        if other.rand() < 0.05:
                            return 'tableflip_phrase', com.get_t('tableflip_phrase')
                        else:
                            return 'rand_tableflip', other.rand_tableflip(len_wave, len_table)
                else:
                    return 'unflip', '┬─┬ ノ( ゜-゜ノ)'
            else:
                dice_count = msg.original.count('dice') + msg.original.count('🎲')
                if dice_count > 0:
                    return 'diceflip', other.rand_diceflip(dice_count)
        elif msg.original[1:].startswith('tableflip') and (msg.admin or msg.channel.id == C.channels['bar']):
            if not C.roles['Primogens'] in msg.roles and not msg.admin and prob < 0.2:
                return 'tableflip_phrase', com.get_t('tableflip_cmd_phrase', user=f'<@{msg.auid}>')
            else:
                return '/tableflip', '* *бросаю за <@{id}>* *\n{table}'.format(id=msg.auid,
                                                                               table=other.rand_tableflip())
        elif msg.original[1:].startswith('shrug'):
            return '/shrug', r'¯\_(ツ)_/¯'

        m_type = m_type or (_beckett_m_type(msg) if beckett else _not_beckett_m_type(msg))
        _emj_by_mtype(msg, m_type)
        ans = _beckett_ans(m_type, msg.auid)
        if ans:
            return m_type, ans

        if beckett: # beckett_reference or (beckett and other.rand() < 0.25):
            if prob < 0.1:
                ans_phr = com.get_t(all_keys=('author_phrases', msg.auid))
                if ans_phr:
                    return msg.auid, ans_phr

            m_type = 'For_Prince' if msg.auid == C.users['Natali'] and prob < 0.4 else 'beckett'
            ans_phr = com.get_t(m_type)
            return m_type, ans_phr

    return '', ''