Exemplo n.º 1
0
def wait_for_invite(bot):
    while True:
        print(C('Waiting for invite...'))
        try:
            lps = bot['api'].groups.getLongPollServer(group_id=bot['group_id'])
            request = "{}?act=a_check&key={}&ts={}&wait={}".format(
                lps['server'], lps['key'], lps['ts'], LONGPOLLWAIT)
            resp = json.loads(urlreq.urlopen(request).read())
        except Exception as e:
            print(C(e, 'red', attrs=['bold']))
            ans = input('Retry? (Y/n) ')
            if ans in 'Yy':
                continue
            else:
                sys.exit(0)

        lps['ts'], updates = resp['ts'], resp['updates']

        for i in updates:
            if i['type'] == 'message_new' and \
            'action' in i['object']['message'] and \
            i['object']['message']['action']['type'] == 'chat_invite_user' and \
            i['object']['message']['action']['member_id'] == -bot['group_id']:
                bot['peer_id'] = i['object']['message']['peer_id']
                return
Exemplo n.º 2
0
def display(it, args):  # pragma: no cover
    # TODO better name?
    import difflib
    # pylint: disable=import-error
    from termcolor import colored as C  # type: ignore
    from sys import stdout

    for line in it:
        line = line.strip()
        if args.human:
            print('---')
            print(line)
        can = canonify(line)
        # TODO use textual diff?
        sm = difflib.SequenceMatcher(None, line, can)

        org_ = ""
        can_ = ""

        pr = False

        def delete(x):
            nonlocal pr
            if x in (
                    'https://www.',
                    'http://www.',
                    'http://',
                    'https://',
                    'file://',
                    '/',
            ):
                col = None
            else:
                if len(x) > 0:
                    pr = True
                col = 'red'
            return C(x, color=col)

        for what, ff, tt, ff2, tt2 in sm.get_opcodes():
            if what == 'delete':
                fn = delete
            elif what == 'equal':
                fn = lambda x: C(x, color=None)
            else:
                pr = True
                fn = lambda x: C(x, color='cyan')
            # TODO exclude certain items from comparison?

            org_ += fn(line[ff:tt])
            can_ += fn(can[ff2:tt2])
            cl = max(len(org_), len(can_))
            org_ += ' ' * (cl - len(org_))
            can_ += ' ' * (cl - len(can_))

        if pr:
            stdout.write(f'{org_}\n{can_}\n---\n')
Exemplo n.º 3
0
def main():
    if len(sys.argv) < 3:
        print('Usage: ./talk.py [GROUP ID] [ACCESS KEY]', file=sys.stderr)
        sys.exit(1)

    print(
        C('Access key: ', 'green') +
        '{}'.format(sys.argv[2][:4] + '....' + sys.argv[2][-4:]))
    print(C('Group id: ', 'green') + '{}'.format(sys.argv[1]))
    bot = { 'api': vk.API(vk.Session(access_token=sys.argv[2]), v=API_VERSION), \
     'group_id': int(sys.argv[1])}

    wait = True
    if os.path.isfile(PEER_ID_FILE):
        ans = input(
            '{} exists, load peer_id from file? (Y/n) '.format(PEER_ID_FILE))
        if ans in 'Yy':
            bot['peer_id'] = read_peer_id(PEER_ID_FILE)
            wait = False
    if wait:
        wait_for_invite(bot)
        save_peer_id(bot, PEER_ID_FILE)

    talk(bot)
Exemplo n.º 4
0
def talk(bot):
    rnd = 0
    while True:
        try:
            msg = input(C('send', 'cyan') + \
             C('> ', 'white'))
        except EOFError as e:
            print()
            sys.exit(0)

        if len(msg.strip()) == 0:
            print(C('Invalid message: "{}"'.format(msg), 'red',
                    attrs=['bold']))
            continue
        try:
            bot['api'].messages.send(peer_id=bot['peer_id'],
                                     random_id=rnd + 1,
                                     message=msg)
        except vk.exceptions.VkAPIError as e:
            print(e.message, file=sys.stderr)
            continue
        print( C('You sent: ', 'green') + \
         '"{}"'.format(msg))
        rnd ^= 1
Exemplo n.º 5
0
 def delete(x):
     nonlocal pr
     if x in (
             'https://www.',
             'http://www.',
             'http://',
             'https://',
             'file://',
             '/',
     ):
         col = None
     else:
         if len(x) > 0:
             pr = True
         col = 'red'
     return C(x, color=col)
Exemplo n.º 6
0
 def G(msg):
     return C(msg, "green")
Exemplo n.º 7
0
 def R(msg):
     return C(msg, "red")
Exemplo n.º 8
0
    if len(sys.argv) < 3:
        print('Usage: ./talk.py [GROUP ID] [ACCESS KEY]', file=sys.stderr)
        sys.exit(1)

    print(
        C('Access key: ', 'green') +
        '{}'.format(sys.argv[2][:4] + '....' + sys.argv[2][-4:]))
    print(C('Group id: ', 'green') + '{}'.format(sys.argv[1]))
    bot = { 'api': vk.API(vk.Session(access_token=sys.argv[2]), v=API_VERSION), \
     'group_id': int(sys.argv[1])}

    wait = True
    if os.path.isfile(PEER_ID_FILE):
        ans = input(
            '{} exists, load peer_id from file? (Y/n) '.format(PEER_ID_FILE))
        if ans in 'Yy':
            bot['peer_id'] = read_peer_id(PEER_ID_FILE)
            wait = False
    if wait:
        wait_for_invite(bot)
        save_peer_id(bot, PEER_ID_FILE)

    talk(bot)


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print(C('Interrupted', 'red', attrs=['bold']))
        sys.exit(0)
Exemplo n.º 9
0
def main():
    import argparse
    p = argparse.ArgumentParser()
    p.add_argument('input', nargs='?')
    p.add_argument('--human', action='store_true')
    args = p.parse_args()

    it: Iterable[str]
    if args.input is None:
        import sys
        it = sys.stdin
    else:
        it = [args.input]

    for line in it:
        line = line.strip()
        if args.human:
            print('---')
            print(line)
        can = canonify(line)
        # TODO use textual diff?
        import difflib
        sm = difflib.SequenceMatcher(None, line, can)
        from termcolor import colored as C
        from sys import stdout

        org_ = ""
        can_ = ""

        pr = False

        def delete(x):
            nonlocal pr
            if x in (
                    'https://www.',
                    'http://www.',
                    'http://',
                    'https://',
                    'file://',
                    '/',
            ):
                col = None
            else:
                if len(x) > 0:
                    pr = True
                col = 'red'
            return C(x, color=col)

        for what, ff, tt, ff2, tt2 in sm.get_opcodes():
            if what == 'delete':
                fn = delete
            elif what == 'equal':
                fn = lambda x: C(x, color=None)
            else:
                pr = True
                fn = lambda x: C(x, color='cyan')
            # TODO exclude certain items from comparison?

            org_ += fn(line[ff:tt])
            can_ += fn(can[ff2:tt2])
            cl = max(len(org_), len(can_))
            org_ += ' ' * (cl - len(org_))
            can_ += ' ' * (cl - len(can_))

        if pr:
            stdout.write(f'{org_}\n{can_}\n---\n')