Example #1
0
def tmw_price(client, nick, crawler):
    """
    .tmw-price ["for"] <some item> -- get the TMW server price for an item, 
    based on the ~600,000 item online history of the ManaMarket bot.
    """
    if crawler.normal(False).lower() == 'for':
        # Consume it
        crawler.normal()
    
    item = crawler.chain.title()
    if not item:
        return '`tmw-price` requires an item argument!'
    
    cheap = expensive = total = items = records = 0
   
    for record in Price.filter(item=item):
        if not cheap or record.price < cheap:
            cheap = record.price
        if record.price > expensive:
            expensive = record.price
        total += record.quantity * record.price
        items += record.quantity
        records += 1
    
    close_connection()
    
    if not records:
        return 'I see no %s in the records.' % item
    
    average = total // items
    reps = (items, records, cheap, expensive)
    insert = 'over %s items in %s records, min %s, max %s' % reps
    return 'price for %s: %sgp (%s)' % (item, average, insert)
Example #2
0
def tell_cb(client):
    if Message.count():
        for player in client.online_players:
            for msg in Message.filter(recipient=player):
                client.whisper(player, msg.text)
                msg.remove()
        get_connection().commit()

    close_connection()
Example #3
0
def format_listing(listing, tell_more=False):
    t_count = Listing.count()
    s_count = len(listing)
    if t_count > s_count and tell_more:
        msg = '(Showing %s results out of %s)\n' % (s_count, len(t_count))
    else:
        msg = ''
    msg += ' | '.join(l_disp % i for i in listing)
    
    close_connection()
    return msg or 'There are no items listed!'
Example #4
0
def rebuild(local=False):
    opened = False
    try:
        start = time.time()
        Price.clear_table()
        
        if local:
            f = open('manamarket.html')
        else:
            f = urllib.urlopen('http://manamarket.sagdas.net/manamarket.html')
        opened = True
        
        for L in f:
            L = L.strip()
            if L == '</table>':
                # We're done :)
                break
            # In the name of speed... (rather than .startswith())
            elif L[:4] != '<tr>':
                continue
            
            # chop off the "<tr> <td>" (9 chars) at the beginning, split at the 
            # cell borders ("</td> <td>"), and keep the first 3 rows, which 
            # will be completely de-HTMLed :)
            keep = L[9:].split('</td> <td>')[:3]
            
            # Create and add the entry
            Price({'item': keep[0], 
                   'quantity': int(keep[1].replace(',', '')), 
                   'price': int(keep[2].replace(',', ''))
                  }).add()
    
    except Exception:
        # Output the error
        sys.excepthook(*sys.exc_info())
        w, success = 'failed', False
        get_connection().rollback()
    else:
        w, success = 'has been completed', False
        get_connection().commit()
    
    if opened:
        f.close()
    
    taken = time.time() - start
    print 'Rebuilding the TMW price database %s after %s seconds.' % (w, taken)
    close_connection()
    return success
Example #5
0
def sub_add(client, nick, *args):
    if len(args) < 4 or not (args[0].isdigit() and args[-1].isdigit()):
        return ('Bad arguments! See the sub-command "help".')
    
    if Listing.count(seller=nick) >= client.mod_conf['listing']['max']:
        close_connection()
        return ('You have too many items listed! Use the "remove" sub-command '
                'alongside "show mine" to remove an item first.')
    
    p = int(args[-1])
    n = int(args[0])
    t = ' '.join(args[1:-2])
    w = args[-2]
    Listing(dict(seller=nick, quantity=n, price=p, item=t.lower(), word=w)
            ).add()
    close_connection()
Example #6
0
def seen(client, nick, crawler):
    """
    `.seen <player>|(most [num:5])` -- get the last time the given player was 
    seen, or a list of the most seen players.
    """
    if crawler.chain:
        pl = crawler.quoted()
        a0 = pl.lower()
    else:
        a0 = 'most'
    
    if _is_bot(a0):
        return 'That isn\'t important!'
    
    ticks = int(SingleStat.get(ref='mod_online.count').data)
    
    if a0 == 'most':
        arg = crawler.chain.strip()
        top = int(arg) if (arg and arg.isdigit()) else 5
        # Show max of ten entries
        top = min(top, 10)
        
        # Inefficient -_-
        L = list(Sighting.all())
        L.sort(key=lambda sighting: sighting.count, reverse=True)
        
        msg = ''
        new = True
        for s in L[:top]:
            pl = s.player
            msg += ('Last seen %s, ' % time_msg(s.time, client, pl) + 
                    '%s was seen %s;' % (pl, count_msg(s.count, ticks)) + 
                    (' ' if new else '\n'))
            
            new = not new
        
    else:
        s = Sighting.get(player=a0)
        if not s:
            return 'Sorry, but I haven\'t ever seen %s.' % pl
        msg = 'I last saw %s %s. ' % (pl, time_msg(s.time, client, a0))
        msg += 'I saw %s %s. ' % (pl, count_msg(s.count, ticks))
    
    close_connection()
    return msg
Example #7
0
def listing(client, nick, crawler):
    """
    Classifieds for LoF. See the "help" sub-command for more information.
    """
    args = crawler.chain.split()
    try:
        cmd = args.pop(0).lower()
    except IndexError:
        cmd = 'show'
    
    if cmd == 'show':
        return sub_show(client, nick, *args)
    
    elif cmd == 'add':
        return sub_add(client, nick, *args)
    
    elif cmd == 'remove':
        if len(args) != 1 or not args[0].isdigit():
            return 'The "remove" sub-command requires a numeric id!'
        
        item = int(args[0])
        # one or zero matches
        match = Listing.get(seller=nick, id=item)
        if not match:
            return 'You don\'t have an item with that id!'
        match.remove()
        close_connection()
    
    elif cmd == 'help':
        return ('Use: '
                '`show [<page> | only <item name> | mine | all]` '
                 'to display a page of listings, whether a certain '
                 '(defaults to the first) page of all of results, '
                 'all items of a certain type, all of your own items, '
                 'or every single item;\n'
                
                '`add <number> <item name>` at <price>'
                 'to add an item to the listings;\n'
                
                '`remove` <id> to remove one of your items.')
    
    else:
        return ('`%s` is not a valid sub-command; '
                'see the `help` sub-command for more details.') % cmd
Example #8
0
def recent(client, nick, crawler):
    """
    `.recently-seen [number:5]` -- get a list of the most recently seen players.
    """
    number = int(crawler.chain) if crawler.chain else 5
    number = min(number, 20)    # Need a maximum!
    L = list(Sighting.all())
    L.sort(key=lambda sighting: sighting.time, reverse=True)
    
    msg = ''
    new = True
    for s in L[:number]:
        pl = s.player
        msg += '%s was last seen %s' % (pl, time_msg(s.time, client, pl))
        msg += ', ' if new else ';\n'
        
        new = not new
    
    close_connection()
    return msg[:-2] + '.'
Example #9
0
def listen(client, nick, crawler):
    """
    .listen [true|false|yes|no] -- Set/get your listening status.
    """
    text = crawler.chain
    do_listen = text[0].lower() in 'yt' if text else None
    
    listener = Listener.get(listener=nick)
    if not listener:
        do_listen = False if do_listen is False else True
        Listener(dict(listener=nick, listening=do_listen)).add()
    elif do_listen is None:
        do_listen = listener.listening
    else:
        listener.listening = do_listen
    
    get_connection().commit()
    close_connection()
    
    return 'You are%s listening.' % ('' if do_listen else 'n\'t')
Example #10
0
def tell(client, nick, crawler):
    """
    `.tell <nick>|all <some thing>` -- send a message to a possibly 
    offline player, or to everyone listening.
    """
    try:
        rec = crawler.quoted().lower()
        msg = crawler.chain
    except ValueError:
        return "You must specify a recipient and a message."

    # Check for broadcast, which requires mod_listen. As a very optional
    # feature, though

    if rec in ["*", "all"]:
        lmod = client.installed_mods.get("listen")
        if lmod:
            return lmod.forward(nick, msg)
        else:
            return "This feature requires mod_listen, which is not available."

    # Check for sym-nick
    rec = t_sym_nicks.get(rec, rec)

    # Refresh the playerlist to avoid droppage
    client.installed_mods["online"].get_playerlist(client)
    if rec in client.online_players:
        client.whisper(rec, '%s says to tell you: "%s"' % (nick, msg))
        return "Sent."

    text = time.strftime("At %H:%M:%S on %d %B %Y, ", time.gmtime()) + '%s said to tell you: "%s"' % (nick, msg)

    Message(dict(text=text, recipient=rec)).add()
    get_connection().commit()
    close_connection()

    return "Saved.       If you're wondering what that means, it means the person you are trying to send a message to is offline and the message will be saved until they come online again."