Exemplo n.º 1
0
 def __init__(self,
              uid,
              name='',
              karma=0,
              status='',
              g_morn=0,
              g_day=0,
              g_ev=0,
              g_n=0,
              last_m=-1,
              last_st=-1,
              online=True,
              prev_st=0):
     self.id = str(uid)
     self.name = name
     self.karma = int(karma)
     self.status = status
     self.g_morn = int(g_morn)
     self.g_day = int(g_day)
     self.g_ev = int(g_ev)
     self.g_n = int(g_n)
     l_m = int(last_m)
     self.last_m = l_m if l_m >= 0 else other.get_sec_total()
     self.online = bool(online)
     l_st = int(last_st)
     self.last_st = l_st if l_st >= 0 else other.get_sec_total(
     )  # when changes last user state
     self.prev_st = int(prev_st)  # length of prev user state
     # Not save data
     self.maybe_invisible = False
     self.prev_inv = False
     self.prev_onl = not online
     self.was_invisible = False
     self.last_force_check = self.last_st
     self.life_signs_t = other.get_sec_total()
Exemplo n.º 2
0
def set_gt(uid, key):
    if key in gt_keys:
        if uid in usrs:
            setattr(usrs[uid], key, other.get_sec_total())
            usrs[uid].status = 'upd'
        else:
            if uid not in other_usrs:
                other_usrs[uid] = {key: 0 for key in gt_keys}
            other_usrs[uid][key] = other.get_sec_total()
Exemplo n.º 3
0
async def silence_on(name, t=1.0, force=False):
    """
    :param name: string
    :param t: float
    :param force: bool
    :rtype: C.Types.Member
    """
    s = C.prm_server
    user = other.find_member(s, name)
    if not user:
        return None

    if user.top_role >= s.me.top_role and not force:
        return 'top_role'

    if other.has_roles(user, C.roles['protege']):
        return 'protege'

    t = max(t, 0.02)
    if user.id in ram.silence_users:
        check = ram.silence_users[user.id]['check']
    else:
        check = await turn_silence(user, turn=True, force=force)
    ram.silence_users[user.id] = {'time': other.get_sec_total() + t * 3600 - 1, 'check': tuple(check)}
    if not C.is_test:
        add_roles = [other.find(s.roles, id=C.roles['Silence'])]
        other.add_roles(user, add_roles, 'silence_on')
    log.I('Silence on for ', user, ' at ', other.t2s(), ' on ', t, 'h.')
    return user
Exemplo n.º 4
0
def print_online_people():
    sec_now = other.get_sec_total()
    info = {}
    for uid in users_online:
        inf = get_online_info(uid, sec_now)
        if not inf:
            continue
        info[usrs[uid].name] = inf

    return [info[key] for key in sorted(info)]
Exemplo n.º 5
0
    def add(memb, status=''):
        """

        :param C.Types.Member memb:
        :param str status:
        :return Usr:
        """
        return Usr(memb.id,
                   name=other.uname(memb),
                   status=status,
                   last_m=other.get_sec_total())
Exemplo n.º 6
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)
Exemplo n.º 7
0
async def voting(channel, text='', timeout=60, votes=None, count=3):
    votes = votes or set()
    text = text + '\n*(для согласия введите за/y/yes/ok//д/да/+/1/:ok_hand:/:thumbsup:)*'
    yes = {'за', '1', 'y', 'yes', 'д', 'да', 'ок', 'у', '+', 't_d_', 'ok_hand', 'ok', 'thumbsup', '+1', 'thumbup'}
    await C.client.send_message(channel, text)
    time_end = other.get_sec_total() + timeout

    def check(msg):
        return (msg.author.id not in votes.union({C.users['bot']}) and
                    yes.intersection(emj.em2text(msg.content).lower().replace('.', '').replace(':', ' ').split()))

    while len(votes) < count:
        time_left = time_end - other.get_sec_total()
        log.I('<voting> We have {0}/{1} votes, wait more for {2} sec.'.format(len(votes), count, time_left))
        ans = await C.client.wait_for_message(timeout=time_left, channel=channel, check=check)
        if ans:
                votes.add(ans.author.id)
                other.later_coro(0, C.client.add_reaction(ans, emj.e('ok_hand')))
        else:
            break
    else:
        return votes

    return False
Exemplo n.º 8
0
def get_online_info(uid, t_now=None):
    if uid not in usrs or uid not in users_online:
        return ''

    usr = usrs[uid]
    sec_now = t_now if t_now is not None else other.get_sec_total()
    frm = '[%d.%m.%y]%H:%M:%S' if (sec_now -
                                   usr.last_st) >= 86400 else '%H:%M:%S'
    s_now = other.sec2ts(sec_now, frm)
    usr_online = other.deepcopy(users_online[uid])
    if usr.online:
        usr_online[-1].append(f'~{s_now}~')
    elif usr.maybe_invisible:
        usr_online[-1].append(f'~{{{s_now}}}~')

    return f'''{usr.name}: {', '.join((f'({" - ".join(ls)})' if len(ls) > 1 else ls[0]) for ls in usr_online)}'''
Exemplo n.º 9
0
 def __init__(self,
              gid,
              name='',
              karma=0,
              status='',
              last=None,
              role='0',
              ban=None):
     global bans_id
     t = last or other.get_sec_total()
     self.id = gid
     self.name = name
     self.karma = int(karma)
     self.status = status
     self.ban = ban if ban is not None else gid in bans_id
     self.last = int(t)
     self.role = str(role)
Exemplo n.º 10
0
async def on_member_join_u(member):
    uid = member.id

    if uid in ram.silence_users:
        t = ram.silence_users[uid]['time'] - other.get_sec_total()
        if t > 0:
            log.I(member, ' come, but Silence is on.')
            await manager.silence_on(uid, t / 3600)
            timer_quarter_h()

    if people.Usr.check_new(member):
        not_embrace.add(uid)
        log.pr_news('{0} ({0.mention}) comeback!'.format(member))
        await C.client.send_message(
            C.main_ch,
            com.comeback_msg(uid, people.time_out(uid), people.clan(uid)))
    else:
        log.pr_news('{0} ({0.mention}) new!'.format(member))
Exemplo n.º 11
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))))
Exemplo n.º 12
0
 def comeback(self, memb=None, res=False):
     global usrs
     nm = self.name
     m = memb or other.find_member(C.vtm_server, self.id)
     if m:
         nm = other.uname(m)
         # if self.role != '0':
         #     role = other.find(C.vtm_server.roles, id=self.role)
         #     if role:
         #         other.add_roles(m, role, 'comeback', 5)
     self.status = 'del'
     usr = Usr(self.id,
               name=nm,
               karma=self.karma,
               status='add',
               last_m=other.get_sec_total())
     if res:
         return usr
     else:
         usrs[self.id] = usr
Exemplo n.º 13
0
async def sync():
    # scan chat and get users array from messages in history
    log.I('+ Sync Start')
    count = 0
    # print('[{0}] TEST'.format(other.t2s()))
    for mem in C.client.get_all_members():
        distribute(mem)

    async for message in C.client.logs_from(C.main_ch, limit=1000000):
        distribute(message.author, other.get_sec_total(message.timestamp))
        count += 1
        if count % 10000 == 0:
            log.D('<sync> Check message: ', count)
        # for i in message.raw_mentions:
        #     distribute(await C.client.get_user_info(i), message.timestamp)

    for usr in bans:
        distribute(usr)
    log.D('<sync> MESS COUNT = {0}'.format(str(count)))
    rewrite()
    log.I('+ Sync End')
Exemplo n.º 14
0
 def time_out(self):
     return other.get_sec_total() - self.last
Exemplo n.º 15
0
 def offtime(self):
     return other.get_sec_total() - self.last_m
Exemplo n.º 16
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)
Exemplo n.º 17
0
def online_change(uid, status, force=False, st_now=''):
    if uid not in usrs:
        return False

    usr = usrs[uid]
    online_now = str(status) != 'offline'

    if not (usr.online != online_now or force):
        return True

    usr_online = users_online.setdefault(uid, [['!']])
    t_now = other.get_now()
    sec_now = other.get_sec_total(t_now)
    frm = '[%d.%m.%y]%H:%M:%S' if (sec_now -
                                   usr.last_st) >= 86400 else '%H:%M:%S'
    s_now = st_now or f'{other.t2s(t_now, frm)}'

    if force:
        ''' if offline -> offline - it can be go in/out invisible user
            if online -> online - open app with open tab in browser
        '''
        if not online_now:  # offline -> offline
            if usr.maybe_invisible:
                usr_online[-1].append(f'{{{s_now}}}')
            else:
                usr_online.append([f'{{{s_now}}}'])

            if usr.was_invisible:
                usr.set_invisible(not usr.maybe_invisible, True)
            else:
                usr.set_invisible(False, False)
            usr.prev_onl = False

        usr.last_force_check = sec_now

    elif online_now:
        if usr.maybe_invisible:
            usr_online[-1].append(f'{s_now}')
        else:
            usr_online.append([f'{s_now}'])
    else:
        usr_online[-1].append(f'{s_now}')

    if not force:
        usr.prev_onl = usr.online
        usr.set_invisible(False)

    if usr.online != online_now or usr.maybe_invisible != usr.prev_inv:
        usr.prev_st = sec_now - usr.last_st
        usr.last_st = sec_now
        # log.jI(f"{usr.name} is {('offline', 'online')[online_now]} now after {other.s2s(usr.prev_st)}")
        usr.online = online_now
        usr.status = 'upd'
        get_for_now = False
    else:
        get_for_now = force and not online_now

    if uid in {
            C.users[usr]
            for usr in ('Dummy', 'Tilia', 'Natali', 'Doriana', 'cycl0ne')
    }:
        log_f = log.jI if st_now else log.I
        log_f('<on_status_update> ' +
              get_online_info_now(uid, get_for_now=get_for_now))

    return True
Exemplo n.º 18
0
def set_last_m(uid):
    if uid in usrs:
        usrs[uid].set(last_m=other.get_sec_total(), status='upd')
Exemplo n.º 19
0
 def stable_for(self):
     return other.get_sec_total() - self.last_st
Exemplo n.º 20
0
    def gt_passed_for(self, key, h: [float, int] = 1):
        if key not in {'g_morn', 'g_day', 'g_ev', 'g_n'}:
            return False

        t = other.get_sec_total() - getattr(self, key)
        return t > (h * 3600 - 1)
Exemplo n.º 21
0
def _timer_check_silence_in_chat():
    if ram.last_vtm_msg and (
        (other.get_sec_total() - ram.last_vtm_msg) > 25200):  # 7 hours
        log.I('<timer_quarter_h> silence event!')
        phr = com.get_t('silence', )
        com.write_msg(C.main_ch, phr)
Exemplo n.º 22
0
async def check_now():
    log.I('- start check people')
    s_mems = set()
    # noinspection PyTypeChecker
    for mem in C.vtm_server.members:  # type: C.Types.Member
        s_mems.add(mem.id)
        uname = other.uname(mem)
        if mem.id not in usrs:
            if Usr.check_new(mem):
                if gone[mem.id].ban:
                    log.pr_news(f'New user {uname} from ban!')
                else:
                    log.pr_news(f'New user {uname} from gone!')
            else:
                log.pr_news(f'New user {uname}!')
        elif usrs[mem.id].name != uname:
            usrs[mem.id].set(name=uname, status='upd')

        online_now = str(mem.status) != 'offline'
        sec_now = other.get_sec_total()
        frm = '[%d.%m.%y]%H:%M:%S' if (
            sec_now - usrs[mem.id].last_st) >= 86400 else '%H:%M:%S'
        s_now = f'~{other.sec2ts(sec_now, frm=frm)}~'

        if usrs[mem.id].online and online_now:
            users_online[mem.id] = [[
                other.sec2ts(usrs[mem.id].last_st, frm=frm), s_now
            ]]
        elif online_now:
            users_online[mem.id] = []
        elif usrs[mem.id].online:
            users_online[mem.id] = [[
                other.sec2ts(usrs[mem.id].last_st, frm=frm)
            ]]
        else:
            users_online[mem.id] = [[f'{{{s_now}}}']]

        online_change(mem.id, status=str(mem.status), st_now=s_now)

    for usr in usrs:
        if usr not in s_mems:
            usrs[usr].go()
            log.pr_news('User ' + usrs[usr].name + ' disappeared! [Ban: ' +
                        str(gone[usr].ban) + ']')

    for u_ban in bans:
        if u_ban.id not in gone:
            if Gn.check_new(u_ban):
                log.pr_news('New ban user ' + gone[u_ban.id].name +
                            ' from users!')
            else:
                log.pr_news('New ban user ' + gone[u_ban.id].name +
                            ' from somewhere!')
        else:
            if gone[u_ban.id].toban(True):
                log.pr_news('New ban user ' + gone[u_ban.id].name +
                            ' from gone!')

    if bans_id:
        for gn in gone:
            if gn not in bans_id:
                if gone[gn].toban(False):
                    log.pr_news('User ' + gone[gn].name + ' not in ban now!')

    log.I('+ finished check people')
Exemplo n.º 23
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)