Example #1
0
async def withdraw(Bot, msg):
    if msg.author.id in bot_data['user_data'] and "bank" in bot_data[
            'user_data'][msg.author.id]:
        try:
            amount = round(float(strutils.strip_command(msg.content)) * 100)
        except ValueError:
            if strutils.strip_command(msg.content) == 'all':
                amount = bot_data['user_data'][msg.author.id]["bank"]
            else:
                await Bot.send_message(
                    msg.channel,
                    "Your input was invalid! Please input a number.")
                return
        if amount <= bot_data['user_data'][msg.author.id]["bank"]:
            bot_data['user_data'][msg.author.id]["bank"] -= amount
            bot_data['user_data'][msg.author.id]["money"] += amount
            await Bot.send_message(
                msg.channel, "Withdrew " + '{0:.2f}'.format(amount / 100) +
                " from your Bovine Bank account.\nYour new bank balance is " +
                '{0:.2f}'.format(
                    bot_data['user_data'][msg.author.id]["bank"] / 100) + ".")
        else:
            await Bot.send_message(
                msg.channel,
                "You can't withdraw that much money, you only have `" +
                '{0:.2f}'.format(bot_data['user_data'][msg.author.id]["bank"] /
                                 100) + '` in your bank!')
    else:
        await Bot.send_message(
            msg.channel,
            "You have no Mooney to withdraw! Try depositing mooney first")
Example #2
0
async def quiz(Bot, msg):
    if not msg.server.id in bot_data['quiz_data']:
        bot_data['quiz_data'][msg.server.id] = [None, {}]
    else:
        for k in bot_data['quiz_data'][msg.server.id][1].keys():
            if not bot_data['quiz_data'][msg.server.id][1][k]:
                del bot_data['quiz_data'][msg.server.id][1][k]
    try:
        newmsg = strutils.strip_command(msg.content).split(" ")
    except IndexError:
        em = Embed(title="Missing subcommand", description=strutils.format_response("You must specify a subcommand!\nValid options include `cow quiz add` and `cow quiz take`.", _msg=msg), colour=0xff7830)
        await msgutils.send_embed(Bot, msg, em)
        return
    try:
        if not msg.author.id in quiz_users:
            quiz_users.append(msg.author.id)
            try:
                await quiz_handlers[newmsg[0]](Bot, msg)
            except KeyError:
                raise
            finally:
                quiz_users.remove(msg.author.id)
        else:
            await Bot.send_message(msg.channel, "You already have a quiz running!\nPlease cancel that command first.")
    except KeyError:
        em = Embed(title="ERROR", description="Unknown subcommand **%s**." % newmsg[0], colour=0xd32323)
        await Bot.send_message(msg.channel, embed=em)
Example #3
0
async def transfer(Bot, msg):
    try:
        amt = int(
            float(strutils.strip_command(msg.content).split(' ', 1)[0]) * 100)
        if amt <= bot_data['user_data'][msg.author.id]["money"]:
            give(amt, msg.mentions[0].id)
            give(-1 * amt, msg.author.id)
            em = Embed(title="Money Transfer",
                       description='{0:.2f}'.format(amt / 100) +
                       " mooney given to " + msg.mentions[0].mention,
                       colour=0xffd747)
            await msgutils.send_embed(Bot, msg, em)
        else:
            await Bot.send_message(
                msg.channel, "You don't have that much money to transfer!")
    except (ValueError, TypeError):
        em = Embed(title="Invalid Amount",
                   description="Mooney to give must be a number.",
                   colour=0xd32323)
        await msgutils.send_embed(Bot, msg, em)
    except IndexError:
        em = Embed(title="Missing User",
                   description="You must specify the user to give mooney to.",
                   colour=0xd32323)
        await msgutils.send_embed(Bot, msg, em)
Example #4
0
async def slots(Bot, msg):
    bet = int(float(strutils.strip_command(msg.content)) * 100)
    if msg.author.id in bot_data['user_data']:
        if bet > bot_data['user_data'][msg.author.id]["money"]:
            await Bot.send_message(msg.channel,
                                   "You don't have that much to bet, silly!")
        else:
            moneychange = randint(-1 * bet, bet)
            if moneychange >= 0:
                await Bot.send_message(
                    msg.channel, msg.author.mention + " won " +
                    '{0:.2f}'.format(moneychange / 100) + " Mooney. Nice job!")
            else:
                await Bot.send_message(
                    msg.channel, msg.author.mention + " lost " +
                    '{0:.2f}'.format(-1 * moneychange / 100) +
                    " Mooney. Better luck next time!")
            datautils.nested_addition(moneychange,
                                      'user_data',
                                      msg.author.id,
                                      'money',
                                      default=0)
    else:
        await Bot.send_message(
            msg.channel,
            "You have no mooney yet! Do `cow daily` to recieve your daily reward."
        )
Example #5
0
async def addMooney(Bot, msg):
    if msg.author.id == "418827664304898048":
        try:
            amt = int(
                float(strutils.strip_command(msg.content).split(' ', 1)[0]) *
                100)
            give(amt, msg.mentions[0].id)
            em = Embed(title="Money Added",
                       description='{0:.2f}'.format(amt / 100) +
                       " mooney given to " + msg.mentions[0].mention,
                       colour=0xffd747)
            await msgutils.send_embed(Bot, msg, em)
        except (ValueError, TypeError):
            em = Embed(title="Invalid Amount",
                       description="Mooney to give must be a number.",
                       colour=0xd32323)
            await msgutils.send_embed(Bot, msg, em)
        except IndexError:
            em = Embed(
                title="Missing User",
                description="You must specify the user to give mooney to.",
                colour=0xd32323)
            await msgutils.send_embed(Bot, msg, em)
    else:
        em = Embed(
            title="Insufficient Permissions",
            description=strutils.format_response(
                "{_mention} does not have sufficient permissions to perform this task.",
                _msg=msg),
            colour=0xd32323)
        await msgutils.send_embed(Bot, msg, em)
Example #6
0
async def trivia(Bot, msg):
    cont = strutils.strip_command(msg.content)
    cont = (cont.split(' ') if ' ' in cont else [cont])
    diff = None
    cat = None
    if cont[0].lower() in Data.difficulties.value:
        diff = Data.difficulties.value[cont.pop(0).lower()]
    elif cont[-1].lower() in Data.difficulties.value:
        diff = Data.difficulties.value[cont.pop().lower()]
    cont = ' '.join(cont)
    if not cont.isspace():
        if cont.lower() in Data.categories.value:
            cat = Data.categories.value[cont.lower()]
        else:
            em = Embed(
                title="Unknown Category",
                description=
                "Could not find the specified category. Valid categories include:\n\n"
                + '\n'.join(Data.categories.value.keys()),
                colour=0xff7830)
            await Bot.send_message(msg.channel, embed=em)
            return
    question = triviaAPI.getquestion(category=cat, difficulty=diff)[0]
    options = {question["correct_answer"]: True}
    options.update({(k, False) for k in question["incorrect_answers"]})
    questionOBJ = Question(question['question'], options, True)
    questionOBJ.optshuf()
    em = Embed(title="Trivia Question",
               description=questionOBJ.getstr(),
               colour=0xff7830)
    msgEmbed = await Bot.send_message(msg.channel, embed=em)

    def check(s):
        return len(s.content) == 1 and 0 <= ord(
            s.content.lower()) - ord('a') < len(options)

    response = await Bot.wait_for_message(timeout=600,
                                          author=msg.author,
                                          channel=msg.channel,
                                          check=check)
    selection = ord(response.content.lower()) - ord('a')
    em.description = questionOBJ.getstr(selected=selection, showCorrect=True)
    if list(questionOBJ.options.values())[selection] == True:
        increment(msg.author.id, "answerstreak", 1)
        reward = randint(
            0, 250 * bot_data['user_data'][msg.author.id]['answerstreak'] *
            (['easy', 'medium', 'hard'].index(question['difficulty']) + 1))
        give(reward, msg.author.id)
        em.description += '\n\nYou answered correctly! Your answer streak is now `' + str(
            bot_data['user_data'][msg.author.id]
            ['answerstreak']) + '` and you have recieved ' + '{0:.2f}'.format(
                reward / 100) + ' Mooney!\nYou now have ' + '{0:.2f}'.format(
                    bot_data['user_data'][msg.author.id]["money"] /
                    100) + ' Mooney.'
    else:
        set_element(msg.author.id, "answerstreak", 0)
        em.description += '\n\nYour answer was incorrect! Your answer streak is now `0`.'
    await msgutils.edit_embed(Bot, msgEmbed, em)
Example #7
0
async def settings(Bot, msg):
    perms = msg.channel.permissions_for(msg.author)
    if perms.manage_server:
        newmsg = strutils.strip_command(msg.content).split(" ")
        try:
            await settings_handlers[newmsg[0]](Bot, msg, newmsg)
        except KeyError:
            em = Embed(title="ERROR",
                       description="Unknown subcommand **%s**." % newmsg[0],
                       colour=0xd32323)
            await Bot.send_message(msg.channel, embed=em)
Example #8
0
async def deposit(Bot, msg):
    if msg.author.id in bot_data['user_data']:
        try:
            amount = round(float(strutils.strip_command(msg.content)) * 100)
        except ValueError:
            if strutils.strip_command(msg.content) == 'all':
                amount = bot_data['user_data'][msg.author.id]["money"]
            else:
                await Bot.send_message(
                    msg.channel,
                    "Your input was invalid! Please input a number.")
                return
        if amount <= bot_data['user_data'][msg.author.id]["money"]:
            datautils.nested_addition(amount,
                                      'user_data',
                                      msg.author.id,
                                      'bank',
                                      default=0)
            bot_data['user_data'][msg.author.id]["money"] -= amount
            await Bot.send_message(
                msg.channel, "Deposited `" + '{0:.2f}'.format(amount / 100) +
                "` Mooney to your Bovine Bank account.\nYour new bank balance is `"
                + '{0:.2f}'.format(
                    bot_data['user_data'][msg.author.id]["bank"] / 100) +
                "` Mooney.")
        else:
            await Bot.send_message(
                msg.channel,
                "You can't deposit that much money, you only have `" +
                '{0:.2f}'.format(
                    bot_data['user_data'][msg.author.id]["money"] / 100) +
                '`!')
    else:
        await Bot.send_message(
            msg.channel,
            "You have no Mooney to deposit! Try using `cow work` or `cow daily` first."
        )
Example #9
0
async def add(Bot, msg):
    if (bot_data['quiz_data'][msg.server.id][0] and bot_data['quiz_data'][msg.server.id][0] not in msg.author.roles) and not msg.channel.permissions_for(msg.author).manage_messages:
        em = Embed(title="Insufficient Permissions", description=strutils.format_response("{_mention} does not have sufficient permissions to perform this task.", _msg=msg), colour=0xd32323)
        await msgutils.send_embed(Bot, msg, em)
        return
    question = strutils.strip_command(msg.content).split(" ", 1)[1]
    em = Embed(title="Add Quiz Question", description="Question:\n"+question, colour=0xff7830)
    desc = ''
    if len(bot_data['quiz_data'][msg.server.id][1]) > 0:
        for k,v in bot_data['quiz_data'][msg.server.id][1].items():
            desc+='\n'+k
    else:
        desc = '\nNone'
    em.add_field(name="Question Category", value="Available Categories:"+desc+"\n\nIf your desired category is not listed, you may add one below.\n\nIf you want to cancel, type `cancel`.", inline=False)
    qmsg = await msgutils.send_embed(Bot, msg, em)

    cat = await getquestioncategory(Bot, msg, qmsg, em, add=True)
    if not cat:
        return
    em.set_field_at(0, name="Question Category", value=cat, inline=False)
    quest = await editquestion(Bot, msg, qmsg, em, cat, question)
    bot_data['quiz_data'][msg.server.id][1][cat].append(quest)
Example #10
0
async def query(Bot, msg):

    question = strutils.strip_command(msg.content)
    em = Embed(title=question, description="Requesting Data", colour=0xe4671b)
    oldem = await msgutils.send_embed(Bot, msg, em)
    res = wa_client.query(question)

    if "@pods" not in res:
        try:
            resp = urllib.request.urlopen(res["@recalculate"])
            assert resp.headers.get_content_type() == 'text/xml'
            assert resp.headers.get_param('charset') == 'utf-8'
            res = wolframalpha.Result(resp)
        except ValueError:
            pass

    titles = []
    images = []

    try:

        for pod in res.pods:
            titles.append(textwrap.wrap(pod.title, width=50))
            subimgs = []
            for sub in pod.subpods:
                subimgs.append(
                    Image.open(
                        BytesIO(requests.get(sub['img']['@src']).content)))
            images.append(subimgs)
    except AttributeError:
        em = Embed(title=question, description="No results", colour=0xe4671b)
        await msgutils.edit_embed(Bot, oldem, em)
        return

    chained_imgs = list(itertools.chain.from_iterable(images))

    widths, heights = zip(*(i.size for i in chained_imgs))

    item_padding = 20
    font_size = 15
    font_padding = 3

    max_width = max(widths) + 2 * item_padding
    total_height = sum(heights) + item_padding * (len(chained_imgs) + 2 + len(
        titles)) + (font_padding + font_size) * len(
            list(itertools.chain.from_iterable(titles)))

    new_im = imgutils.round_rectangle((max_width, total_height), item_padding,
                                      "white")

    font = ImageFont.truetype("Data/Roboto-Regular.ttf", font_size)

    total_pods = 0

    draw = ImageDraw.Draw(new_im)
    y_offset = item_padding
    for i in range(len(titles)):
        pod = images[i]
        for line in titles[i]:
            draw.text((item_padding, y_offset),
                      line,
                      fill=(119, 165, 182),
                      font=font)
            y_offset += font_size + font_padding

        y_offset += item_padding
        for im in pod:
            total_pods += 1
            new_im.paste(im, (item_padding, y_offset))
            y_offset += im.size[1] + item_padding
            if (total_pods < len(chained_imgs)):
                draw.line((0, y_offset - item_padding / 2, max_width,
                           y_offset - item_padding / 2),
                          fill=(233, 233, 233),
                          width=1)

    new_im.save("Data/wa_save.png")

    res_img = imgur_client.upload_image("Data/wa_save.png", title=question)

    em = Embed(title=question, url=res_img.link, colour=0xe4671b)
    em.set_image(url=res_img.link)
    await msgutils.edit_embed(Bot, oldem, em)
Example #11
0
async def thesaurus(Bot, msg):
    #Taken from https://stackoverflow.com/questions/19790188/expanding-english-language-contractions-in-python
    contractions = {
        "ain't": ["am not", "are not", "is not", "has not", "have not"],
        "aren't": ["are not", "am not"],
        "can't": ["cannot"],
        "can't've": ["cannot have"],
        "'cause": ["because"],
        "could've": ["could have"],
        "couldn't": ["could not"],
        "couldn't've": ["could not have"],
        "didn't": ["did not"],
        "doesn't": ["does not"],
        "don't": ["do not"],
        "hadn't": ["had not"],
        "hadn't've": ["had not have"],
        "hasn't": ["has not"],
        "haven't": ["have not"],
        "he'd": ["he had", "he would"],
        "he'd've": ["he would have"],
        "he'll": ["he shall: [he will"],
        "he'll've": ["he shall have", "he will have"],
        "he's": ["he has", "he is"],
        "how'd": ["how did"],
        "how'd'y": ["how do you"],
        "how'll": ["how will"],
        "how's": ["how has", "how is", "how does"],
        "I'd": ["I had", "I would"],
        "I'd've": ["I would have"],
        "I'll": ["I shall", "I will"],
        "I'll've": ["I shall have", "I will have"],
        "I'm": ["I am"],
        "I've": ["I have"],
        "isn't": ["is not"],
        "it'd": ["it had", "it would"],
        "it'd've": ["it would have"],
        "it'll": ["it shall", "it will"],
        "it'll've": ["it shall have", "it will have"],
        "it's": ["it has", "it is"],
        "let's": ["let us"],
        "ma'am": ["madam"],
        "mayn't": ["may not"],
        "might've": ["might have"],
        "mightn't": ["might not"],
        "mightn't've": ["might not have"],
        "must've": ["must have"],
        "mustn't": ["must not"],
        "mustn't've": ["must not have"],
        "needn't": ["need not"],
        "needn't've": ["need not have"],
        "o'clock": ["of the clock"],
        "oughtn't": ["ought not"],
        "oughtn't've": ["ought not have"],
        "shan't": ["shall not"],
        "sha'n't": ["shall not"],
        "shan't've": ["shall not have"],
        "she'd": ["she had", "she would"],
        "she'd've": ["she would have"],
        "she'll": ["she shall", "she will"],
        "she'll've": ["she shall have", "she will have"],
        "she's": ["she has", "she is"],
        "should've": ["should have"],
        "shouldn't": ["should not"],
        "shouldn't've": ["should not have"],
        "so've": ["so have"],
        "so's": ["so as", "so is"],
        "that'd": ["that would", "that had"],
        "that'd've": ["that would have"],
        "that's": ["that has", "that is"],
        "there'd": ["there had", "there would"],
        "there'd've": ["there would have"],
        "there's": ["there has", "there is"],
        "they'd": ["they had", "they would"],
        "they'd've": ["they would have"],
        "they'll": ["they shall", "they will"],
        "they'll've": ["they shall have", "they will have"],
        "they're": ["they are"],
        "they've": ["they have"],
        "to've": ["to have"],
        "wasn't": ["was not"],
        "we'd": ["we had", "we would"],
        "we'd've": ["we would have"],
        "we'll": ["we will"],
        "we'll've": ["we will have"],
        "we're": ["we are"],
        "we've": ["we have"],
        "weren't": ["were not"],
        "what'll": ["what shall", "what will"],
        "what'll've": ["what shall have", "what will have"],
        "what're": ["what are"],
        "what's": ["what has", "what is"],
        "what've": ["what have"],
        "when's": ["when has", "when is"],
        "when've": ["when have"],
        "where'd": ["where did"],
        "where's": ["where has", "where is"],
        "where've": ["where have"],
        "who'll": ["who shall", "who will"],
        "who'll've": ["who shall have", "who will have"],
        "who's": ["who has", "who is"],
        "who've": ["who have"],
        "why's": ["why has", "why is"],
        "why've": ["why have"],
        "will've": ["will have"],
        "won't": ["will not"],
        "won't've": ["will not have"],
        "would've": ["would have"],
        "wouldn't": ["would not"],
        "wouldn't've": ["would not have"],
        "y'all": ["you all"],
        "y'all'd": ["you all would"],
        "y'all'd've": ["you all would have"],
        "y'all're": ["you all are"],
        "y'all've": ["you all have"],
        "you'd": ["you had", "you would"],
        "you'd've": ["you would have"],
        "you'll": ["you shall", "you will"],
        "you'll've": ["you shall have", "you will have"],
        "you're": ["you are"],
        "you've": ["you have"]
    }

    link = "http://www.thesaurus.com/browse/"

    sentence = strutils.strip_command(msg.content)
    em = Embed(
        title="Thesaurus-ifier",
        description=
        "Completely overuses the thesaurus on a sentence.\nCheck out the program at [Thesaurus-er](https://github.com/UnsignedByte/Thesaurus-er) by [UnsignedByte](https://github.com/UnsignedByte)!",
        colour=0x4e91fc)
    em.add_field(name="Input Sentence", value=sentence, inline=False)
    em.add_field(name="Output Sentence", value="Converting...", inline=False)

    m = await msgutils.send_embed(Bot, msg, em)

    for k in sorted(contractions, key=len,
                    reverse=True):  # Through keys sorted by length
        sentence = sentence.replace(k, choice(contractions[k]))
    sentence = sentence.split()

    newsentence = []
    for a in sentence:
        newa = a.strip(string.punctuation)
        punc = a.split(newa)
        #From https://stackoverflow.com/questions/367155/splitting-a-string-into-words-and-punctuation
        newa = [
            item for item in map(str.strip, re.split("(\W+)", newa))
            if len(item) > 0
        ]

        lets = []
        for xi in range(0, len(newa)):
            x = newa[xi]
            if xi % 2 == 0:
                try:
                    response = req.get(link + x)
                    response.raise_for_status()
                    html_doc = response.text
                    soup = BeautifulSoup(html_doc, 'html.parser')
                    chosenone = choice(
                        list(
                            map(lambda x: x.decode_contents(formatter="html"),
                                soup.findAll("span", 'text'))))
                    if x[0].isupper():
                        chosenone = chosenone.title()
                    lets.append(chosenone)
                except (req.exceptions.HTTPError, IndexError):
                    lets.append(x)
            else:
                lets.append(x)

        lets = punc[0] + ''.join(lets) + punc[1]
        newsentence.append(lets)

    em.set_field_at(1,
                    name="Output Sentence",
                    value=' '.join(newsentence),
                    inline=False)
    await msgutils.edit_embed(Bot, m, em)
Example #12
0
async def take(Bot, msg):
    try:
        cat = strutils.strip_command(msg.content).split(" ", 1)[1].title()
        questions = bot_data['quiz_data'][msg.server.id][1][cat]
    except (KeyError, IndexError):
        em = Embed(title="Available Categories", colour=0xff7830)
        desc = 'We could not find the specified category in this server. Please choose one of the available options listed below.\n'
        if len(bot_data['quiz_data'][msg.server.id][1]) > 0:
            for k,v in bot_data['quiz_data'][msg.server.id][1].items():
                desc+='\n'+k
        else:
            desc += '\nNone'
        em.description = desc
        qmsg = await msgutils.send_embed(Bot, msg, em)
        def check(s):
            return s.content.title() in bot_data['quiz_data'][msg.server.id][1] or s.content.lower() == 'cancel'
        newm = await Bot.wait_for_message(timeout=600, author=msg.author, channel=msg.channel, check=check)
        if not newm or newm.content.lower() == 'cancel':
            em = Embed(title="Question Wizard", description='*Operation Cancelled*', colour=0xff7830)
            await msgutils.edit_embed(Bot, qmsg, em)
            await Bot.delete_message(newm)
            return
        cat = newm.content.title()
        questions = bot_data['quiz_data'][msg.server.id][1][cat]
        await Bot.delete_messages([qmsg, newm])

    def formatDesc(cat="Unknown", ql="Unknown", score=100):
        return "Category: "+cat+"\nQuestions Left: "+str(ql)+"\nPercent Correct: "+'{0:.2f}'.format(score)+"%"

    em = Embed(title="Quiz", description=formatDesc(cat=cat)+"\n\nHow many questions do you want in your quiz? There "+("is" if len(questions) == 1 else "are")+" "+str(len(questions))+" question"+("s" if len(questions) == 1 else "")+" in total to choose from.\nType a number, or type `all` to get all questions in the category.", colour=0xff7830)
    qmsg = await msgutils.send_embed(Bot, msg, em)
    def check(s):
        return (objutils.integer(s.content) and 0<int(s.content)<=len(questions)) or s.content == 'all'
    nm = await Bot.wait_for_message(timeout=600, author=msg.author, channel=msg.channel, check=check)
    if not nm:
        return
    if nm.content != 'all':
        shuffle(questions)
        questions = questions[0:int(nm.content)]
    await Bot.delete_message(nm)
    em.add_field(name="Question", value="NULL")

    totalscore = 0

    em.description=formatDesc(cat=cat, ql=len(questions), score=100.0)
    for a in range(len(questions)):
        questions[a].optshuf()
        em.set_field_at(0, name="Question "+str(a+1), value=questions[a].getstr()+"\n\nTo select your answer, type in the option letter (from A to "+chr(len(questions[a].options)+64)+").\nIf you don't know the answer, you can always guess!")
        qmsg = await msgutils.edit_embed(Bot, qmsg, em)
        def check(s):
            return len(s.content)==1 and 1<=ord(s.content.upper())-64<=len(questions[a].options)
        def yesnocheck(s):
            return s.content in ['y', 'n', 'yes', 'no']
        def confirmcheck(s):
            return check(s) or s.content in ['n', 'next']
        select = await Bot.wait_for_message(timeout=600, author=msg.author, channel=msg.channel, check=check)
        select.content = str(ord(select.content.upper())-64)
        await Bot.delete_message(select)
        while True:
            em.set_field_at(0, name="Question "+str(a+1), value=questions[a].getstr(selected=int(select.content)-1)+"\n\nTo select another answer, type in the option letter (from A to "+chr(len(questions[a].options)+64)+").\nWhen you are ready to move on, type `next (n)`.\nIf you don't know the answer, you can always guess!")
            qmsg = await msgutils.edit_embed(Bot, qmsg, em)
            newselect = await Bot.wait_for_message(timeout=600, author=msg.author, channel=msg.channel, check=confirmcheck)
            await Bot.delete_message(newselect)
            if newselect.content in ['n', 'next']:
                if questions[a].isCorrect(int(select.content)):
                    totalscore += 1
                em.set_field_at(0, name="Question "+str(a+1), value=questions[a].getstr(selected=int(select.content)-1, showCorrect=True)+'\n\nWhen you are done viewing answers, type `next (n)` to move on.')
                em.description = formatDesc(cat=cat, ql=len(questions)-a-1, score=100*totalscore/(a+1))
                await msgutils.edit_embed(Bot, qmsg, em)
                def moveoncheck(s):
                    return s.content in ['n', 'next']
                moveon = await Bot.wait_for_message(timeout=600, author=msg.author, channel=msg.channel, check=moveoncheck)
                await Bot.delete_message(moveon)
                break
            else:
                newselect.content = str(ord(newselect.content.upper())-64)
                select = newselect

    em.remove_field(0)
    moneyrecieved = randint(round(totalscore/2)*100, round(totalscore*2)*100)
    em.title = 'Quiz Completed!'
    em.description = 'Congratulations! You completed a quiz in the '+cat+' category with '+str(len(questions))+' questions.\nYou recieved a score of '+'{0:.2f}'.format(100*totalscore/len(questions))+'%, or '+str(totalscore)+' out of '+str(len(questions))+'!\nAs you answered '+str(totalscore)+' questions correctly, you have recieved $'+str(moneyrecieved/100)+'!'
    await msgutils.edit_embed(Bot, qmsg, em)
    give(moneyrecieved, msg.author.id)
Example #13
0
async def stock(Bot, msg):
    subcomms = {
        "get": "get",
        "info": "get",
        "sell": "sell",
        "invest": "buy",
        "buy": "buy"
    }

    em = Embed(title="Stock information",
               description="Retrieving data...",
               colour=0xffd747)
    stockmsg = await msgutils.send_embed(Bot, msg, em)
    try:
        cont = strutils.strip_command(msg.content)
    except IndexError:
        em = Embed(title="Missing Inputs",
                   description="Not enough inputs provided for **stock**.",
                   colour=0xd32323)
        await msgutils.edit_embed(Bot, stockmsg, em)
        return
    minfo = cont.split(' ')
    if len(minfo) > 2:
        em = Embed(title="Invalid Input",
                   description="Stock Name cannot contain whitespace",
                   colour=0xd32323)
        stockmsg = await msgutils.edit_embed(Bot, stockmsg, embed=em)
        return
    if len(minfo) == 1:
        cont = minfo[0]
        commtype = "get"
    elif len(minfo) == 2:
        try:
            commtype = subcomms[minfo[0]]
        except KeyError:
            em = Embed(
                title="Invalid Command",
                description="Could not find subcommand **" + minfo[0] +
                "**.\nValid subcommands are **get**, **sell**, and **buy**.",
                colour=0xd32323)
            await msgutils.edit_embed(Bot, stockmsg, em)
            return
        cont = minfo[1]

    link = "https://www.nasdaq.com/symbol/?Load=true&Search=" + cont
    try:
        response = req.get(link)
        response.raise_for_status()
        html_doc = response.text
        soup = BeautifulSoup(html_doc, 'html.parser')
        tabl = 0
        el = []
        for x in soup.find("div", {
                "id": "two_column_main_content_pnlData"
        }).findChildren():
            if x.name == 'table':
                for a in x.findChildren():
                    if a.name == 'td':
                        try:
                            el.append(a.findChildren()[0].decode_contents(
                                formatter="html"))
                        except IndexError:
                            el.append(a.decode_contents(formatter="html"))
        el = utils.group(el, 3)
        if len(el) > 1:
            em = Embed(
                title=
                "Multiple results found. Choose one. Type `cancel` to cancel",
                description="",
                colour=0xffd747)
            for a in range(0, len(el)):
                em.description += '\n' + str(a + 1) + ': ' + ' '.join(el[a])
            stockmsg = await msgutils.edit_embed(Bot, stockmsg, embed=em)

            def check(s):
                s = s.content
                if s == 'cancel':
                    return True
                return objutils.integer(s) and int(s) <= len(el) and int(s) > 0

            stock = await Bot.wait_for_message(timeout=600,
                                               author=msg.author,
                                               channel=msg.channel,
                                               check=check)
            if not stock:
                return
            await Bot.delete_message(stock)
            if stock.content == 'cancel':
                em = Embed(title="Stock Information",
                           description="*Operation Cancelled*",
                           colour=0xffd747)
                stockmsg = await msgutils.edit_embed(Bot, stockmsg, embed=em)
                return
            stock = el[int(stock.content) - 1]
        elif len(el) == 1:
            stock = el[0]
        else:
            em = Embed(
                title="No Results",
                description="Could not find results matching your input.",
                colour=0xffd747)
            stockmsg = await msgutils.edit_embed(Bot, stockmsg, embed=em)
            return
        link = "https://www.nasdaq.com/symbol/" + stock[0]
        response = req.get(link)
        response.raise_for_status()
        html_doc = response.text
        soup = BeautifulSoup(html_doc, 'html.parser')
        arr = " \u2b06 "
        if 'arrow-red' in soup.find("div", {
                "id": "qwidget-arrow"
        }).findChildren()[0].get("class"):
            arr = " \u2b07 "
        name = soup.find("div", {"id": "qwidget_pageheader"}).get_text()
        data = (soup.find("div", {
            "id": "qwidget_lastsale"
        }).get_text(), soup.find("div", {
            "id": "qwidget_netchange"
        }).get_text(), soup.find("div", {
            "id": "qwidget_percent"
        }).get_text())
        info = "**" + data[0] + "**• " + data[1] + arr + data[
            2] + '\nFor more information go to [the nasdaq website](' + link + ").\n\nThis was taken from [Stock-Viewer](https://github.com/UnsignedByte/Stock-Viewer) by [UnsignedByte](https://github.com/UnsignedByte)."
        if commtype == "get":
            em = Embed(title=name, description=info, colour=0xffd747)
            stockmsg = await msgutils.edit_embed(Bot, stockmsg, embed=em)
        if commtype == "buy":
            if msg.author.id in bot_data['user_data']:

                def check(s):
                    s = s.content
                    if s == 'cancel':
                        return True
                    return objutils.integer(s) and int(s) > 0

                em = Embed(
                    title="Buying Shares...",
                    description=
                    "How many shares would you like to buy? Input an integer.",
                    colour=0xffd747)
                em.add_field(name=name, value=info)
                while True:
                    stockmsg = await msgutils.edit_embed(Bot,
                                                         stockmsg,
                                                         embed=em)
                    num = await Bot.wait_for_message(timeout=600,
                                                     author=msg.author,
                                                     channel=msg.channel,
                                                     check=check)
                    if not num:
                        return
                    await Bot.delete_message(num)
                    if num.content == 'cancel':
                        em = Embed(title="Stock Information",
                                   description="*Operation Cancelled*",
                                   colour=0xffd747)
                        stockmsg = await msgutils.edit_embed(Bot,
                                                             stockmsg,
                                                             embed=em)
                        return
                    num = int(num.content)
                    if num * float(data[0][1:]) * 100 > bot_data['user_data'][
                            msg.author.id]["money"]:
                        em.description = "How many shares would you like to buy? Input an integer.\n\nCannot buy " + str(
                            num) + " shares, you do not have enough mooney!"
                    else:
                        break
                bot_data['user_data'][msg.author.id]["money"] -= num * float(
                    data[0][1:]) * 100
                if "stock" in bot_data['user_data'][msg.author.id]:
                    if stock[0] in bot_data['user_data'][
                            msg.author.id]["stock"]:
                        bot_data['user_data'][msg.author.id]["stock"][
                            stock[0]] += num
                    else:
                        bot_data['user_data'][msg.author.id]["stock"][
                            stock[0]] = num
                else:
                    bot_data['user_data'][msg.author.id]["stock"] = {}
                    bot_data['user_data'][msg.author.id]["stock"][
                        stock[0]] = num
                em.title = "Shares Bought."
                em.description = "You bought " + str(
                    num) + " shares for " + str(
                        num * float(data[0][1:])) + " Mooney!"
                stockmsg = await msgutils.edit_embed(Bot, stockmsg, em)
            else:
                em = Embed(
                    title="No Mooney",
                    description=
                    "You cannot buy stocks, as you have no mooney yet! Do `cow daily` to recieve your daily reward.",
                    colour=0xd32323)
                stockmsg = await msgutils.edit_embed(Bot, stockmsg, embed=em)
        elif commtype == "sell":
            if msg.author.id in bot_data['user_data'] and "stock" in bot_data[
                    'user_data'][msg.author.id] and stock[0] in bot_data[
                        'user_data'][msg.author.id]["stock"]:

                def check(s):
                    s = s.content
                    if s == 'cancel':
                        return True
                    return objutils.integer(s) and int(s) > 0

                em = Embed(
                    title="Selling Shares...",
                    description=
                    "How many shares would you like to sell? Input an integer.",
                    colour=0xffd747)
                em.add_field(name=name, value=info)
                while True:
                    stockmsg = await msgutils.edit_embed(Bot,
                                                         stockmsg,
                                                         embed=em)
                    num = await Bot.wait_for_message(timeout=600,
                                                     author=msg.author,
                                                     channel=msg.channel,
                                                     check=check)
                    if not num:
                        return
                    await Bot.delete_message(num)
                    if num.content == 'cancel':
                        em = Embed(title="Stock Information",
                                   description="*Operation Cancelled*",
                                   colour=0xffd747)
                        stockmsg = await msgutils.edit_embed(Bot,
                                                             stockmsg,
                                                             embed=em)
                        return
                    num = int(num.content)
                    if num > bot_data['user_data'][msg.author.id]["stock"][
                            stock[0]]:
                        em.description = "How many shares would you like to sell? Input an integer.\n\nCannot sell " + str(
                            num) + " shares, you do not own that many!"
                    else:
                        break
                bot_data['user_data'][msg.author.id]["money"] += num * float(
                    data[0][1:]) * 100
                bot_data['user_data'][msg.author.id]["stock"][stock[0]] -= num
                em.title = "Shares sold."
                em.description = "You sold " + str(num) + " shares for " + str(
                    num * float(data[0][1:])) + " Mooney!"
                stockmsg = await msgutils.edit_embed(Bot, stockmsg, em)
            else:
                em = Embed(title="No Stocks",
                           description="You have no stocks to sell.",
                           colour=0xd32323)
                stockmsg = await msgutils.edit_embed(Bot, stockmsg, embed=em)
    except req.exceptions.HTTPError:
        em = Embed(title="Invalid Input",
                   description="Your input was invalid",
                   colour=0xd32323)
        stockmsg = await msgutils.edit_embed(Bot, stockmsg, embed=em)
        return