예제 #1
0
    async def new_fun(*args):
        if not C.Ready:
            print('Not C.Ready, abort ', name, '()')
            return

        server = await fun(*args)
        if server.id == C.prm_server.id:
            log.jD('Call Ev_u ', name)
            await globals()[name + '_u'](*args)
        elif server.id != C.vtm_server.id:
            log.jD('Call Ev_o ', name)
            await globals()[name + '_o'](server, *args)
예제 #2
0
async def time_sync():
    # scan chat and get users time of last_message from history
    log.I('+ Time_sync start')
    t = {}
    mems = [mem.id for mem in C.vtm_server.members]
    for ch in C.vtm_server.channels:
        if str(ch.type) == 'text':
            t[ch.position] = ch
    channels = [t[k] for k in sorted(t)]
    log.D('- {0} channels prepare to scan:'.format(len(channels)))
    for i, ch in enumerate(channels):
        pr = ch.permissions_for(ch.server.me)
        if pr.read_message_history:
            log.D('+ {0}) {1} - check'.format(i + 1, ch.name))
            mems_i = set(mems)
            count = 0
            messes = []
            async for mess in C.client.logs_from(ch, limit=1000000):
                messes.append(mess)

            for mess in messes:
                aid = mess.author.id
                if aid in mems_i:
                    ts = other.get_sec_total(mess.timestamp)
                    if ts > usrs[aid].last_m:
                        usrs[aid].last_m = ts
                        usrs[aid].status = 'upd'

                    mems_i.remove(aid)
                    if len(mems_i) < 1:
                        break
                count += 1
                if count % 10000 == 0:
                    log.D('- - <time_sync> check messages: ', count,
                          ', mems_i: ', len(mems_i))
            log.D('+ {0}) {1} - done'.format(i + 1, ch.name))
        else:
            log.D('-- {0}) {1} - not permissions for reading'.format(
                i + 1, ch.name))
    log.I('+ Time_sync end')
    log.jD('Test results:')
    for mem in C.vtm_server.members:
        log.jD('{0} \t-\t {1}'.format(mem, other.sec2str(offtime(mem.id))))
예제 #3
0
async def _timer_check_stuff():
    log.jD('timer_check_stuff!')
    msg2del = []  #set()
    now = other.get_sec_total()
    for ch_id in (C.channels['stuff'], C.channels['music']):
        async for msg in C.client.logs_from(
                other.get_channel(ch_id),
                limit=1000000):  #type: C.Types.Message
            msg_time = other.get_sec_total(msg.timestamp)
            if False and now - msg_time > C.h48:
                log.jI(f'break:\n{msg.content}')
                break
            elif now - msg_time > C.h24:
                if not (msg.attachments or msg.embeds or msg.pinned
                        or other.s_in_s(('http://', 'https://', 'www.', '```'),
                                        msg.content)):
                    # msg2del.add(msg)
                    msg2del.append(msg)
    msg2del.reverse()
    for msg in msg2del:
        txt = await log.format_mess(msg)
        log.p(txt)
예제 #4
0
async def on_ready():
    ram.debug = C.is_test
    await other.busy()
    log.I(
        f'Logged in as {C.client.user} (id: {C.client.user.id}, Test: {C.is_test})'
    )
    prepare_const2()
    emj.prepare()
    await ev.load()
    ram.debug = ram.debug or C.is_test
    if not discord__opus.is_loaded():
        lb = find_library("opus")
        log.jD('opus lib: ', lb)  # i can't find it on heroku
        if lb:
            discord__opus.load_opus(lb)
        else:
            log.jI('opus lib not load!')
    ev.start_timers()
    log.I('Beckett ready for work now, after starting at ',
          ram.t_start.strftime('[%d/%m/%y %T]'))
    log.p('======= ' * 10)
    await test_fun()  # for debugging an testing
    C.Ready = True
    await other.test_status(ram.game)
예제 #5
0
async def cmd_people_time_sync():
    await people.time_sync()
    log.jD('- people.time_sync done, save mem')
    save_mem()
예제 #6
0
def upd():
    t = load(res=True)
    log.D('- start upd people tables')
    log_upd = {
        'change_usrs': {
            'add': [],
            'upd': [],
            'del': []
        },
        'change_gone': {
            'add': [],
            'upd': [],
            'del': []
        }
    }
    change_usrs = {'add': [], 'upd': [], 'del': []}
    for uid in list(usrs.keys()):
        usr = usrs[uid]
        if usr.status == 'add' or usr.status == 'upd':
            if uid in t['usrs']:
                change_usrs['upd'].append(usr.row_upd())
                log_upd['change_usrs']['upd'].append(usr.name)
            else:
                change_usrs['add'].append(usr.row_add())
                log_upd['change_usrs']['add'].append(usr.name)
            usr.status = ''
        elif usr.status == 'del':
            if uid in t['usrs']:
                change_usrs['del'].append([uid])
                log_upd['change_usrs']['del'].append(usr.name)
            usrs.pop(uid)

    change_gone = {'add': [], 'upd': [], 'del': []}
    for uid in list(gone.keys()):
        gn = gone[uid]
        if gn.status == 'add' or gn.status == 'upd':
            if uid in t['gone']:
                change_gone['upd'].append(gn.row_upd())
                log_upd['change_gone']['upd'].append(gn.name)
            else:
                change_gone['add'].append(gn.row_add())
                log_upd['change_gone']['add'].append(gn.name)
            gn.status = ''
        elif gn.status == 'del':
            if uid in t['gone']:
                change_gone['del'].append([uid])
                log_upd['change_gone']['del'].append(gn.name)
            gone.pop(uid)

    if log.debug():
        if C.is_test:
            log.D("- it's Test mode, print results and return")
        log_upd = {'change_usrs': change_usrs, 'change_gone': change_gone}
        log.jD(
            'subjects were updated:\n', '\n'.join([
                cat + ':\n\t' + '\n'.join([
                    tp + '[{0}]:\n\t\t'.format(len(u_s)) +
                    ',\n\t\t'.join(str(u) for u in u_s)
                    for tp, u_s in ls.items() if u_s
                ]) for cat, ls in log_upd.items() if ls
            ]))
        # log.p('--------------------------------------------------------')
        if C.is_test:
            return

    conn = None
    log.D('- update people tables')
    try:
        ch_usrs_par = ', '.join(Usr.upd_props)
        ch_usrs_par_s = ', '.join(('%s', ) * len(Usr.upd_props))
        ch_gone_par = ', '.join(Gn.upd_props)
        ch_gone_par_s = ', '.join(('%s', ) * len(Gn.upd_props))
        conn = psycopg2.connect(C.DATABASE_URL, sslmode='require')
        cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        if change_usrs['add']:
            query = f'''INSERT INTO members (id, {ch_usrs_par})
                                            VALUES (%s, {ch_usrs_par_s})'''
            cur.executemany(query, change_usrs['add'])
            conn.commit()

        if change_gone['add']:
            query = f'''INSERT INTO users_gone (id, {ch_gone_par}) 
                                                        VALUES (%s, {ch_gone_par_s})'''
            cur.executemany(query, change_gone['add'])
            conn.commit()

        if change_usrs['upd']:
            query = f'''UPDATE members SET ({ch_usrs_par}) = 
                                                          ({ch_usrs_par_s}) WHERE id = %s'''
            cur.executemany(query, change_usrs['upd'])
            conn.commit()

        if change_gone['upd']:
            query = f'''UPDATE users_gone SET ({ch_gone_par}) = ({ch_gone_par_s}) WHERE id = %s'''
            cur.executemany(query, change_gone['upd'])
            conn.commit()

        if change_usrs['del']:
            query = '''DELETE FROM members WHERE id = %s'''
            cur.executemany(query, change_usrs['del'])
            conn.commit()

        if change_gone['del']:
            query = '''DELETE FROM users_gone WHERE id = %s'''
            cur.executemany(query, change_gone['del'])
            conn.commit()

    except psycopg2.DatabaseError as e:
        log.E('DatabaseError %s' % e)
        sys.exit(1)
    else:
        log.D('+ people tables updated successfully')
        log.jD(
            'subjects were updated:\n', '\n'.join([
                cat + ':\n\t' + '\n'.join([
                    tp + '[{0}]:\n\t\t'.format(len(u_s)) +
                    ',\n\t\t'.join(str(u) for u in u_s)
                    for tp, u_s in ls.items() if u_s
                ]) for cat, ls in log_upd.items() if ls
            ]))
    finally:
        if conn:
            conn.close()
예제 #7
0
 def life_signs(self):
     self.life_signs_t = other.get_sec_total()
     if not (self.online or self.maybe_invisible):
         log.jD(f' ~ think {self.name} in invisible')
         self.set_invisible(True)
예제 #8
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, ('🌺', '🌻', '🌹', '🌷', '🌼', '🌸', '💐'))
예제 #9
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 '', ''