Example #1
0
def drop_tables():
    database.connect()
    try:
        database.drop_tables([Pokemon])
        database.commit()
    finally:
        database.close()
Example #2
0
def start_training(message):
    """Command: start training - starts a one hour training."""
    if message.author.id in stop_training_events:
        yield from client.send_message(message.channel,
                                       "You are already training.")
        return
    stop_event = asyncio.Event()
    stop_training_events[message.author.id] = stop_event
    start_time = client.loop.time() - 5
    handler = client.loop.call_later(3600, stop_event.set)
    yield from client.send_message(message.channel, "Training started.")
    yield from stop_event.wait()
    handler.cancel()
    del stop_training_events[message.author.id]
    delta_time = (client.loop.time() - start_time) // 60
    database.connect()
    try:
        team = (Pokemon.select().where((Pokemon.owner_id == message.author.id)
                                       & (Pokemon.storage == TEAM)))
        for pkmn in team:
            pkmn.add_exp(delta_time)
            pkmn.save()
        database.commit()
    finally:
        database.close()
    ensure_future(
        client.send_message(
            message.author,
            "Training finished. You trained for %u minutes." % delta_time))
Example #3
0
def create_tables():
    database.connect()
    try:
        database.create_tables([Pokemon])
        database.commit()
    finally:
        database.close()
Example #4
0
def start_trade(message):
    seller = message.author
    buyer = message.mentions[0]
    channel = message.channel

    tokens = message.content.split()
    pkmn_name = ' '.join(tokens[3:])
    database.connect()
    try:
        seller_pkmn = Pokemon.get(Pokemon.owner_id == seller.id,
                                  Pokemon.name == pkmn_name)
    except Pokemon.DoesNotExist:
        return
    finally:
        database.close()

    # pokemon exists, send invitation to trade
    text = ("{}, {} invites you to trade and offers {}.\n"
            "Enter 'pkmn offer {} <pokemon>' to trade.".format(
                buyer.mention, seller.name, pkmn_name, seller.mention))
    yield from client.send_message(channel, text)

    # wait for buyer to accept trade
    def check(message):
        return message.content.startswith('pkmn offer {}'.format(
            seller.mention))

    response = yield from client.wait_for_message(300,
                                                  channel=channel,
                                                  author=buyer,
                                                  check=check)
    if not response:
        yield from client.send_message(channel, 'Trade cancelled.')
        return
    tokens = response.content.split()
    pkmn_name = ' '.join(tokens[3:])
    database.connect()
    try:
        buyer_pkmn = Pokemon.get(Pokemon.owner_id == buyer.id,
                                 Pokemon.name == pkmn_name)
        buyer_pkmn.owner_id = seller.id
        seller_pkmn.owner_id = buyer.id
        buyer_pkmn.storage = seller_pkmn.storage = BOX
        buyer_pkmn.save()
        seller_pkmn.save()
        database.commit()
    except Pokemon.DoesNotExist:
        return
    except:
        database.rollback()
        raise
    finally:
        database.close()

    yield from client.send_message(channel, 'Trade completed.')
Example #5
0
def gv_to_db(me):
    files = os.listdir(settings.CONVERSATIONS_DIR)
    os.chdir(settings.CONVERSATIONS_DIR)
    files = [f for f in files if f.endswith('html')]

    database.set_autocommit(False)

    print len(files)
    count = 1
    for f in files:
        print str(count) + '. ' + f
        count += 1

        # set name
        name = parse.parse('{} - {}', f).fixed[0]

        soup = BeautifulSoup(open(f))
        chat = soup.find('div', {'class': 'hChatLog hfeed'})
        if not chat:
            continue

        messages = chat.findAll('div', {'class': 'message'})
        for message in messages:
            # time
            t = message.find('abbr', {'class': 'dt'})
            if t.get('title'):
                time = parse.parse('{:ti}', t.get('title')).fixed[0]

            # telephone number
            tel = message.find('a', {'class': 'tel'})
            tel = tel.get('href').split('+')[-1].replace('tel:', '')

            # name
            name_tag = message.find('span', 'fn') or message.find('abbr', 'fn')
            name_tag = name_tag.get('title') or name_tag.string

            text = ' '.join(HTMLParser().unescape(i)
                            for i in message.q.contents
                            if isinstance(i, basestring))

            person = Contact.get_or_create(name=name)
            sms = SMS.get_or_create(text=text, time=time, contact=person)
            if name_tag != me.name:
                phone = Phone.get_or_create(phone=tel, contact=person)
            else:
                sms.from_me = True
            sms.phone = Phone.get(phone=tel)

            person.save()
            sms.save()
            phone.save()

    database.commit()
Example #6
0
def gv_to_db(me):
    files = os.listdir(settings.CONVERSATIONS_DIR)
    os.chdir(settings.CONVERSATIONS_DIR)
    files = [f for f in files if f.endswith('html')]

    database.set_autocommit(False)

    print len(files)
    count = 1
    for f in files:
        print str(count) + '. ' + f
        count += 1

        # set name
        name = parse.parse('{} - {}', f).fixed[0]

        soup = BeautifulSoup(open(f))
        chat = soup.find('div', {'class': 'hChatLog hfeed'})
        if not chat:
            continue

        messages = chat.findAll('div', {'class': 'message'})
        for message in messages:
            # time
            t = message.find('abbr', {'class': 'dt'})
            if t.get('title'):
                time = parse.parse('{:ti}', t.get('title')).fixed[0]

            # telephone number
            tel = message.find('a', {'class': 'tel'})
            tel = tel.get('href').split('+')[-1].replace('tel:', '')

            # name
            name_tag = message.find('span', 'fn') or message.find('abbr', 'fn')
            name_tag = name_tag.get('title') or name_tag.string

            text = ' '.join(HTMLParser().unescape(i) for i in message.q.contents if isinstance(i, basestring))

            person = Contact.get_or_create(name=name)
            sms = SMS.get_or_create(text=text, time=time, contact=person)
            if name_tag != me.name:
                phone = Phone.get_or_create(phone=tel, contact=person)
            else:
                sms.from_me = True
            sms.phone = Phone.get(phone=tel)

            person.save()
            sms.save()
            phone.save()

    database.commit()
Example #7
0
def deposit_pkmn_handler(message):
    tokens = message.content.split()
    pkmn_name = ' '.join(tokens[2:])
    database.connect()
    try:
        pkmn = (
            Pokemon.select().where((Pokemon.storage == TEAM)
                                   & (Pokemon.owner_id == message.author.id)
                                   & (Pokemon.name == pkmn_name)).first())
        pkmn.storage = BOX
        pkmn.save()
    finally:
        database.commit()
        database.close()
    yield from client.send_message(message.channel,
                                   '{} sent to box'.format(pkmn.name))
Example #8
0
def process_changes(path='changes-in-progress.json'):
    """
    Iterate over changes-in-progress.json and process its contents.
    """
    revision_group = time.mktime((datetime.datetime.now(pytz.utc)).timetuple())

    with open(path) as f:
        changes = json.load(f)

    changed_playgrounds = []

    ACTIONS = {
        'update': process_update,
        'insert': process_insert,
        'delete-request': process_delete
    }

    for record in changes:
        action = ACTIONS[record['action']]

        playground, revisions = action(record)
        changed_playgrounds.append(playground)

        timestamp = datetime.datetime.fromtimestamp(
            record['timestamp']).replace(tzinfo=pytz.utc)

        # Assign the request headers to a variable.
        # Need to modify the headers to add the remote IP address which is
        # on the request object but not in the headers area.
        # Why? Because we don't want to add an additional field to the
        # Revisions model because we don't have DB migrations.
        headers = record['request']['headers']
        headers['remote_ip_address'] = record['request'].get(
            'ip_address', None)

        Revision.create(timestamp=timestamp,
                        action=record['action'],
                        playground=playground,
                        log=json.dumps(revisions),
                        headers=json.dumps(headers),
                        cookies=json.dumps(record['request']['cookies']),
                        revision_group=revision_group)

    # Ensure all changes have been written to disk
    database.commit()

    return (changed_playgrounds, revision_group)
Example #9
0
def process_changes(path='changes-in-progress.json'):
    """
    Iterate over changes-in-progress.json and process its contents.
    """
    revision_group = time.mktime((datetime.datetime.now(pytz.utc)).timetuple())

    with open(path) as f:
        changes = json.load(f)

    changed_playgrounds = []

    ACTIONS = {
        'update': process_update,
        'insert': process_insert,
        'delete-request': process_delete
    }

    for record in changes:
        action = ACTIONS[record['action']]

        playground, revisions = action(record)
        changed_playgrounds.append(playground)

        timestamp = datetime.datetime.fromtimestamp(record['timestamp']).replace(tzinfo=pytz.utc)

        # Assign the request headers to a variable.
        # Need to modify the headers to add the remote IP address which is
        # on the request object but not in the headers area.
        # Why? Because we don't want to add an additional field to the
        # Revisions model because we don't have DB migrations.
        headers = record['request']['headers']
        headers['remote_ip_address'] = record['request'].get('ip_address', None)

        Revision.create(
            timestamp=timestamp,
            action=record['action'],
            playground=playground,
            log=json.dumps(revisions),
            headers=json.dumps(headers),
            cookies=json.dumps(record['request']['cookies']),
            revision_group=revision_group
        )

    # Ensure all changes have been written to disk
    database.commit()

    return (changed_playgrounds, revision_group)
Example #10
0
def add_caught_pokemon(user, pkmn, channel):
    """Add caught pokemon to the user's storage.

    Adds the pokemon to the storage and sends a notification about caught
    pokemon to the channel.
    """
    text = ('Congratulations! {} caught {}.'.format(user.mention, pkmn.name))
    pkmn.owner_id = user.id
    database.connect()
    count = (Pokemon.select().where((Pokemon.owner_id == user.id)
                                    & (Pokemon.storage == 1)).count())
    if count < TEAM_SIZE:
        pkmn.storage = TEAM
    else:
        pkmn.storage = BOX
        text += '\nPokemon was added to your box.'
    pkmn.save()
    database.commit()
    database.close()
    ensure_future(client.send_message(channel, text))
Example #11
0
def withdraw_pokemon(message):
    database.connect()
    num = (Pokemon.select().where((Pokemon.storage == TEAM) & (
        Pokemon.owner_id == message.author.id)).count())
    if num >= TEAM_SIZE:
        database.close()
        yield from client.send_message(message.channel, 'Your team is full.')
        return
    try:
        tokens = message.content.split()
        pkmn_name = ' '.join(tokens[2:])
        pkmn = (
            Pokemon.select().where((Pokemon.storage == BOX)
                                   & (Pokemon.owner_id == message.author.id)
                                   & (Pokemon.name == pkmn_name)).first())
        pkmn.storage = TEAM
        pkmn.save()
    finally:
        database.commit()
        database.close()
    yield from client.send_message(message.channel,
                                   '{} withdrawn.'.format(pkmn.name))