Beispiel #1
0
def makeDateReminder(message, announcement=False):
    if announcement:
        cmd = "announce"
    else:
        cmd = "remind"

    try:
        timeArgs = h.parseArgs(message.content, cmd, 1, 1)
    except errors.Error as e:
        raise e

    duration = h.convertDateTime(timeArgs)
    date = True

    if duration == None:  #Datetime was not parsed correctly
        raise errors.CustomCommandException(cmd, "bad_date")
    elif duration <= 0:  #Datetime is negative
        raise errors.CustomCommandException(cmd, "negative_date")

    if announcement:
        timer = reminder.Announcement(duration=duration, msg=message, dt=True)
    else:
        timer = reminder.Reminder(duration=duration, msg=message, dt=True)

    return timer
Beispiel #2
0
def calc(message):
    toReturn = ""

    #Parse arguments
    try:
        eq = h.parseArgs(message.content, "calc", 1, 1)
        for r in eq:
            eq = r  #Convert to string
    except errors.Error as e:
        raise e

    try:
        answer = ca.calculate(eq)
        toReturn = "Here's what I calculated:" + c.LINE_BREAK
        toReturn = toReturn + "`" + " ".join(eq.split()) + "`\n= %s" % answer

        return toReturn
    except errors.Error as e:
        raise e
    except ZeroDivisionError:
        return "It's not possible to divide by zero. Are you trying to end the world?! %s" % c.RETRY_EQUATION
    except Exception as e:
        if str(e) == "math domain error":  #Probably sqrt of negative
            return "It's not possible to take the square root of a negative number. %s" % c.RETRY_EQUATION
        elif isinstance(e, OverflowError):
            return "Sorry, the answer was too big for me to calculate."
        else:
            if not isinstance(e, IndexError) or not isinstance(e, ValueError):
                h.logException(e)
            return "Sorry, I couldn't finish the calculation. %s" % c.RETRY_EQUATION
Beispiel #3
0
def toBin(message):
    toReturn = ""

    #Parse number, convert it to usable string
    try:
        numbers = h.parseArgs(message.content, "binary", 1,
                              g.props['binary_max_args'])
    except errors.Error as e:
        raise e

    try:
        for q in numbers:
            quotient = int(q)
            remainder = -1
            value = ""

            if quotient == 0:
                value = 0
            elif quotient > 65535 or quotient < 0:
                raise RuntimeError('Invalid number')
            else:
                while quotient != 0:
                    remainder = quotient % 2
                    quotient = int((quotient - remainder) / 2)
                    value = str(remainder) + value

            toReturn = toReturn + "%s in binary is: %s\n" % (q, value)

        return toReturn.rstrip()  #Get rid of newline

    except ValueError:  #Non-integer sent
        raise errors.BadValueException("binary")
    except RuntimeError:  #Non-integer sent or invalid number
        raise errors.BadNumberException("binary")
Beispiel #4
0
def sendHelp(message):
    cmdList = h.getXmlTree('commands')
    toReturn = ""

    #No attempted arguments sent, so send list of commands
    if re.search("\[|\]", message.content) == None:
        toReturn = "Here are my commands:\n"
        info = {"name": "**Information:**", "inline": "true", "value": ""}
        useful = {"name": "**Useful:**", "inline": "true", "value": ""}
        fun = {"name": "**Fun:**", "inline": "true", "value": ""}

        for cmd in cmdList.findall("./function"):
            if not h.isDisabled(cmd.find("command").text):
                if cmd.get("category") == "information":
                    info['value'] = info['value'] + " `{}`\n".format(
                        cmd.find("format").text)
                elif cmd.get("category") == "useful":
                    useful['value'] = useful['value'] + " `{}`\n".format(
                        cmd.find("format").text)
                elif cmd.get("category") == "fun":
                    fun['value'] = fun['value'] + " `{}`\n".format(
                        cmd.find("format").text)

        toReturn = embeddable.Embeddable()
        toReturn.addField(info, useful, fun)
        toReturn.setFooter(c.HELP_REMINDER)

    else:
        try:
            #Specific request
            arg = h.parseArgs(message.content, "help", 1, 1)

            for i in set(arg):
                arg = i.lower()  #Change back to string
            if (arg.startswith("!")):
                arg = arg[1:]

            cmd = cmdList.find("./function/[command='{}']".format(arg))
            if cmd == None:
                raise errors.CustomCommandException("help", "bad_command")
            elif h.isDisabled(cmd.find("command").text):
                toReturn = "Sorry, the command you're trying to find help for is disabled."
            else:
                toReturn = "Here's how to use `!{}`:\n".format(
                    cmd.find("command").text)
                for b in cmd.findall("body"):
                    toReturn = toReturn + "\n" + b.find(
                        "description").text + "\n"
                    for i in b.findall("hint"):
                        toReturn = toReturn + h.blockQuote(
                            "\N{BULLET} " +
                            h.formatProps(cmd.find("command").text, i.text))

            toReturn = embeddable.empty(toReturn)

        except errors.Error as e:
            raise e

    return toReturn
Beispiel #5
0
def choose(message):
    #Parse choices
    try:
        choices = h.parseArgs(message.content, "choose", 2,
                              g.props['choose_max_args'])
    except errors.Error as e:
        raise e

    return "I choose %s!" % random.choice(choices)
Beispiel #6
0
def fetchWiki(message):
    try:
        terms = h.parseArgs(message.content, "wiki", 1, 1)
    except errors.Error as e:
        raise e

    for i in set(terms):
        terms = i  #Convert back to a string

    return wf.fetchArticle(terms)
Beispiel #7
0
def fetchGame(message):
    try:
        terms = h.parseArgs(message.content, "game", 1, 1)
    except errors.Error as e:
        raise e

    for i in set(terms):
        terms = i  #Convert back to a string

    return gf.fetchGame(terms)
Beispiel #8
0
def makePoll(message):
    try:
        options = h.parseArgs(message.content, "poll", 2, 5)
    except errors.Error as e:
        raise e

    question = (re.sub("\[([^\[\]]*)\]",
                       "",
                       message.content.split(' ', 1)[1],
                       flags=re.IGNORECASE))

    return poll.Poll(message, question, options)
Beispiel #9
0
def makeDurationReminder(message):
    try:
        timeArgs = h.parseArgs(message.content, "time", 1, 3)
    except errors.Error as e:
        raise e

    duration = h.convertDurationTime(timeArgs)

    if duration == None:  #Duration was formatted incorrectly
        raise errors.CustomCommandException("time", "bad_duration")
    elif duration > g.props[
            'time_max_duration'] * 86400:  #Duration longer than set property
        raise errors.CustomCommandException("time", "too_long")
    elif duration < 1:  #Duration less than 1 second
        raise errors.CustomCommandException("time", "no_duration")

    timer = reminder.Reminder(duration=duration, msg=message, dt=False)

    return timer
Beispiel #10
0
def rateSomething(message):
    ratings = h.getXmlTree("lists").findall("./list/[@type='ratings']/rating")
    rank = random.choice(ratings)

    #Parse string
    try:
        toRate = h.parseArgs(message.content, "rate", 1, 1)
    except errors.Error as e:
        raise e

    for i in set(toRate):
        toRate = i  #Change back to string

    if toRate.upper() in {"FUNKYBOT", "FUNKY", "YOU", "YOURSELF"}:
        return "I give myself an 11/10. Literally the best ever."
    else:
        if toRate.upper() in {"ME", "MYSELF"}:
            toRate = message.author.display_name
        return ("I give %s a %s out of 10. %s" %
                (toRate, rank.find("rank").text, rank.find("descriptor").text))
Beispiel #11
0
def fetchCard(message):
    toReturn = []

    #Parse card name
    try:
        cards = h.parseArgs(message.content, "magic", 1, 3)
    except errors.Error as e:
        raise e

    for i in cards:
        if i.startswith("|"):
            raise errors.TooFewArgumentsException("magic")
        else:
            result = cf.fetchCard(i)

            if isinstance(result, list):
                toReturn = toReturn + result
            else:
                toReturn.append(result)

    return toReturn
Beispiel #12
0
def rollDice(message):
    ords = [
        'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh',
        'eighth', 'ninth', 'tenth'
    ]
    toReturn = ""
    index = 0
    total = 0

    try:
        numbers = h.parseArgs(message.content, "roll", 1,
                              g.props['roll_max_args'])
    except errors.Error as e:
        raise e

    try:
        for n in numbers:
            number = int(n)

            if number <= 1 or number > 1000:
                raise RuntimeError('Invalid number')
            else:
                if len(numbers) == 1:
                    return "You rolled %s!" % random.randint(1, number)
                else:
                    roll = random.randint(1, number)
                    total = total + roll
                    toReturn = toReturn + "Your %s roll was: %s\n" % (
                        ords[index], roll)
                    index = index + 1

        toReturn = toReturn + "\nYour total roll was %s!" % total
        return toReturn

    except ValueError:  #Non-integer sent
        raise errors.BadValueException("roll")
    except RuntimeError:  #Non-integer sent or invalid number
        raise errors.BadNumberException("roll")
Beispiel #13
0
def playRps(message):
    options = {'rock': 0, 'paper': 1, 'scissors': 2}
    funkyChoice = random.choice(list(options))
    toReturn = "I choose **{}**!\n\n".format(funkyChoice)

    #Parse string
    try:
        playerChoice = h.parseArgs(message.content, "rps", 1, 1)[0]
    except errors.Error as e:
        raise e

    if playerChoice.lower() not in options:
        toReturn = toReturn + "{} beats...hey, you can't pick \"{}\"!".format(
            funkyChoice.capitalize(), playerChoice)
    elif options[playerChoice] == options[funkyChoice]:
        toReturn = toReturn + "It's a draw!"
    elif (options[playerChoice] + 1) % 3 == options[funkyChoice]:
        toReturn = toReturn + "{} beats {}. I win, better luck next time!".format(
            funkyChoice.capitalize(), playerChoice)
    else:
        toReturn = toReturn + "{} beats {}. You win this time!".format(
            playerChoice.capitalize(), funkyChoice)

    return toReturn