Ejemplo n.º 1
0
    async def forecast(self, *arg):
        """Get the forecast for the next 5 days for a specified location from Yahoo. E.g '!forecast glasgow'"""

        # Use default city if no argument passed
        if not arg:
            city = self.default_city
        else:
            city = arg[0]

        location = self.weather_object.lookup_by_location(city)
        forecasts = location.forecast
        count = 0
        embed = discord.Embed(type="rich",
                              colour=utils.generate_random_colour(),
                              timestamp=datetime.now())
        embed.set_author(name="5-day forecast for {}".format(location.title))

        for cast in forecasts:
            if count > 4:
                break
            count += 1
            embed.add_field(name=cast.date,
                            value="{}\nHigh: {}{}{}\nLow: {}{}{}".format(
                                cast.text, cast.high, self.degree_sign,
                                location.units.temperature, cast.low,
                                self.degree_sign, location.units.temperature))

        await self.bot.say(embed=embed)
Ejemplo n.º 2
0
    async def collect_category(self, ctx):
        """Presents an Embed and finds the category from the Reaction the user provided"""
        embed = discord.Embed(type="rich", colour=utils.generate_random_colour())
        embed.set_author(name="Role Categories")
        embed.description = "Click on an emoji at the bottom of this panel that corresponds with the category of roles you want to assign yourself. Another panel will pop up that will ask you for the specific roles."

        current_emoji_index = 0
        for cat, roles_array in ROLE_CATEGORIES.items():
            embed.add_field(name="{} {}".format(utils.resolve_emoji_from_alphabet(utils.ALPHABET[current_emoji_index]), cat), value="`{}`".format("`\n`".join(roles_array)))
            current_emoji_index += 1

        reaction_message = await self.bot.send_message(ctx.message.channel, embed=embed)
        for i, cat in enumerate(list(ROLE_CATEGORIES)):
            await self.bot.add_reaction(reaction_message, utils.resolve_emoji_from_alphabet(utils.ALPHABET[i]))

        def check(reaction, user):
            if user.id != ctx.message.author.id:
                return False

            letter = utils.resolve_letter_from_emoji(reaction.emoji)
            for i in range(0, len(ROLE_CATEGORIES)):
                if letter == utils.ALPHABET[i]:
                    return True

            return False

        res = await self.bot.wait_for_reaction(message=reaction_message, check=check, timeout=30)

        index = utils.ALPHABET.index(utils.resolve_letter_from_emoji(res.reaction.emoji))
        return {
            "category": list(ROLE_CATEGORIES)[index],
            "message": reaction_message
        }
Ejemplo n.º 3
0
async def urban(ctx, query):
    """Search for a definition from Urban Dictionary."""

    defineURL = 'https://api.urbandictionary.com/v0/define?term='

    response = requests.get(defineURL + query)
    data = response.json()

    firstEntry = data["list"][0]

    definition = firstEntry["definition"]
    example = firstEntry["example"]
    url = firstEntry["permalink"]

    title = "Urban Dictionary: "
    title += query

    embed = discord.Embed(type="rich",
                          colour=utils.generate_random_colour(),
                          timestamp=datetime.now())
    embed.set_author(name=title)
    embed.add_field(name="Definition", value=definition)
    embed.add_field(name="Example", value=example)
    embed.add_field(name="URL", value=url)

    await BOT.say(embed=embed)
Ejemplo n.º 4
0
    async def weather(self, *arg):
        """Get current weather conditions at a specified location from Yahoo. E.g '!weather glasgow'"""

        # Use default city if no argument passed
        if not arg:
            city = self.default_city
        else:
            city = arg[0]

        location = self.weather_object.lookup_by_location(city)

        embed = discord.Embed(type="rich",
                              colour=utils.generate_random_colour(),
                              timestamp=datetime.now())
        embed.set_author(name=location.title)
        embed.add_field(name="Temperature",
                        value="{}{}{}".format(location.condition.temp,
                                              self.degree_sign,
                                              location.units.temperature))
        embed.add_field(name="Condition", value=location.condition.text)
        embed.add_field(name="Humidity",
                        value="{}%".format(location.atmosphere["humidity"]))
        embed.add_field(name="Wind",
                        value="{} {}".format(location.wind.speed,
                                             location.units.speed))

        await self.bot.say(embed=embed)
Ejemplo n.º 5
0
    async def run_lemmatron(self, ctx):
        word = parse.quote('_'.join(ctx.message.content.split(' ')[1:]).lower())
        url = "{}{}/{}".format(self.base_address, self.endpoints["lemmatron"], word)

        res = requests.get(url, headers=self.default_headers)

        embed = discord.Embed(colour=utils.generate_random_colour())
        embed.timestamp = ctx.message.timestamp
        embed.set_author(name="Inflections for {}".format(word), icon_url=ctx.message.author.avatar_url)
        embed.set_thumbnail(url=OXFORD_IMAGE_URL)
        embed.set_footer(text="Powered by the Oxford Dictionary API")

        if res.status_code != 200:
            embed = self._set_error(embed=embed, res=res, ctx=ctx)
            await self.bot.send_message(ctx.message.channel.id, embed=embed)
            return 1

        result_words = json.loads(res.text)["results"]
        headword = result_words[0]["word"]

        user_choice = None
        if len(result_words) > 1:
            embed.description = "{}, I have found multiple headwords for your inflection. Select your word now.".format(ctx.message.author.mention)
            choices = list(map(lambda x: {
                "name": x.word,
                "value": "Inflections: `" + ("`, `".join(list(map(lambda y: y["inflectionOf"][0]["text"], result_words["lexicalEntries"])))) + "`"
            }, result_words))

            user_choice = await utils.collect_choice_from_embed(ctx.message.channel, choices=choices, bot=self.bot, embed=embed, target_user=ctx.message.author)
            headword = result_words[user_choice["choice"]]["word"]

        return {
            "headword": headword,
            "message": user_choice["message"] if user_choice else None
        }
Ejemplo n.º 6
0
    async def define(self, ctx):
        """Get the definition of a specified word, like '!define computer'."""
        await self.bot.send_typing(ctx.message.channel)

        if len(ctx.message.content.split(' ')) == 1:
            return await self.bot.send_message(ctx.message.channel, "See how to use this command by running `{}help define`".format(ctx.prefix))

        user_word = ' '.join(ctx.message.content.split(' ')[1:])
        embed = discord.Embed(colour=utils.generate_random_colour())
        embed.timestamp = datetime.now()
        embed.set_author(name="Definitions for {}".format(user_word), url=OXFORD_BASE_SEARCH + user_word, icon_url=ctx.message.author.avatar_url)
        embed.set_thumbnail(url=OXFORD_IMAGE_URL)
        embed.set_footer(text="Powered by the Oxford Dictionary API")

        lemmatron_data = await self.run_lemmatron(ctx)
        if isinstance(lemmatron_data, int) and lemmatron_data > 0:
            return

        definitions = await self.fetch_definitions(ctx, parse.quote('_'.join(lemmatron_data["headword"].split(' ')).lower()))
        if isinstance(definitions, int) and definitions > 0:
            return

        for word in definitions:
            senses = []
            for entry in word["entries"]:
                for i, sense in enumerate(entry["senses"]):
                    if "definitions" not in sense:
                        continue

                    definition = "\n{} `{}`".format(utils.resolve_emoji_from_alphabet(utils.ALPHABET[i]), sense["definitions"][0])
                    examples = list(map(lambda x: x["text"], sense["examples"] if "examples" in sense else []))

                    senses.append({
                        "definition": definition,
                        "examples": examples
                    })

            definition_text = ""
            for sense in senses:
                definition_text += "\n{}{}{}{}".format(sense["definition"], "\n• *" if sense["examples"] else "", "*\n• *".join(sense["examples"]), '*' if sense["examples"] else "")

            name = "{} ({})".format(word["text"], word["lexicalCategory"])
            embed.add_field(name=name, value=definition_text, inline=False)

        if lemmatron_data["message"]:
            await self.bot.edit_message(lemmatron_data["message"], embed=embed)
        else:
            await self.bot.send_message(ctx.message.channel, embed=embed)
Ejemplo n.º 7
0
    async def roles(self, ctx):
        """Add a role to your profile to let us know more about you, like what year of your course you are in."""
        category = await self.collect_category(ctx)
        roles_to_add = await self.collect_roles(category["category"], category["message"], ctx)
        # Differentiate the two lists (user roles and selected roles)
        roles_to_add = list(set(roles_to_add) - set(ctx.message.author.roles))

        result_embed = discord.Embed(type="rich", colour=utils.generate_random_colour())
        result_embed.set_author(name="Added {} Roles".format(len(roles_to_add)))
        if roles_to_add:
            await self.bot.add_roles(ctx.message.author, *roles_to_add)
            result_embed.add_field(name="You have been granted the following roles:", value="`{}`".format("`, `".join(list(map(lambda r: r.name, roles_to_add)))))
        else:
            result_embed.description = "You were not applicable for or already have some of the roles you picked."

        await self.bot.clear_reactions(category["message"])
        await self.bot.edit_message(category["message"], embed=result_embed)
Ejemplo n.º 8
0
	def embed(self):
		"""Constructs a Rich Embed for this poll"""
		e = discord.Embed(type="rich",
						  description="This is {}'s poll.".format(self.initiator.mention),
						  timestamp=datetime.now() + timedelta(seconds=self.duration),
						  colour=utils.generate_random_colour())

		e.add_field(name="\u200b", value="**Options**", inline=False)
		for i, option in enumerate(self.options):
			current_votes = len(self.results[utils.ALPHABET[i]])
			e.add_field(name="{}. {}".format(utils.ALPHABET[i].upper(), option), value="{} votes".format(current_votes), inline=True)

		e.set_author(name=self.question,
					 icon_url=self.initiator.avatar_url)
		if self.time_left > 0:
			e.set_footer(text="Time remaining: {} seconds".format(int(self.time_left)))

		return e
Ejemplo n.º 9
0
    async def roles(self, ctx):
        """Print a list of all server roles."""
        roleString = ""
        count = 0

        rolesDict = {}

        for role in ctx.message.author.guild.roles:
            if role.name not in self.restrictedRoles:
                rolesDict[role.name] = 0

        # For each server role, for each user's list of roles, add to a count if there is a user with that role
        for role in ctx.message.author.guild.roles:
            if role.name not in self.restrictedRoles:
                for user in ctx.message.author.guild.members:
                    for userRole in user.roles:
                        if role == userRole:
                            rolesDict[role.name] += 1

        # Convert dict to list so we can sort alphabetically
        rolesList = []
        for k, v in rolesDict.items():
            rolesString = "`"
            rolesString += k
            rolesString += "` "
            rolesString += str(v)
            rolesString += "\n"
            rolesList.append(rolesString)

        rolesList = sorted(rolesList)

        # Convert list to string so we can display using line terminator \n
        rolesString = ""
        for x in rolesList:
            rolesString += x

        embed = discord.Embed(type="rich",
                              colour=utils.generate_random_colour())
        embed.set_author(
            name="Use '!role Role Name' to add a role to your profile.")
        embed.add_field(name="Roles", value=rolesString)

        await ctx.send(embed=embed)
Ejemplo n.º 10
0
async def wiki(ctx):
	"""Get the first few sentences of a Wikipedia page."""

	query = ctx.message.content
	query = query.replace('!wiki', '')

	summary = wikipedia.summary(query, auto_suggest=True, sentences=2)
	page = wikipedia.page(query, auto_suggest=True)

	title = "Wikipedia: "
	title += page.title
	URL = page.url

	embed = discord.Embed(type="rich", colour=utils.generate_random_colour(), timestamp=datetime.now())
	embed.set_author(name=title)
	embed.add_field(name="Summary", value=summary)
	embed.add_field(name="Read More", value=URL)
	
	await ctx.message.channel.send(embed=embed)
Ejemplo n.º 11
0
async def stats(ctx):
	"""Get server statistics."""
	server = ctx.message.author.guild
	serverName = server.name
	numberOfUsers = server.member_count
	members = server.members
	numberOfOnlineUsers = getOnlineUserCount(members)
	createdDate = server.created_at.strftime('%Y-%m-%d')
	newestMember = getNewestMember(members)

	embed = discord.Embed(type="rich", colour=utils.generate_random_colour(), timestamp=datetime.now())
	embed.set_thumbnail(url=server.icon_url)
	embed.set_author(name=serverName)
	embed.add_field(name="Created", value=createdDate)
	embed.add_field(name="Users Online", value=numberOfOnlineUsers)
	embed.add_field(name="Users Total", value=numberOfUsers)
	embed.add_field(name="Newest Member", value=newestMember)

	await ctx.message.channel.send(embed=embed)
Ejemplo n.º 12
0
    def __init__(self, ctx, *, bot):
        self.bot = bot
        self.channel_id = ctx.message.channel.id
        self.message = None
        self.word = random.choice(HANGMAN_WORDS).upper()
        self.stage = 0
        self.guessed = []

        # Set up the embed template
        self.embed = discord.Embed(colour=utils.generate_random_colour())
        self.embed.timestamp = ctx.message.timestamp
        self.embed.description = "It's Hangman! Guess the word procedurally by typing in a letter - but beware! The more incorrect letters guessed, the more complete the hangman will become. Once the hangman is fully complete, everyone loses."
        self.embed.set_author(name="Hangman")
        self.embed.set_footer(
            text="Initiated by {}".format(str(ctx.message.author)))
        self.embed.add_field(name="GUESS THE WORD",
                             value="`{}`".format(
                                 blank_word(word=self.word,
                                            guessed=self.guessed)))
        self.embed.add_field(name="Most recent Guess", value="---")
        self.embed.add_field(name="Guessed Letters", value="---", inline=False)
        self.embed.add_field(name="Hangman",
                             value=HANGMAN_STAGES[self.stage],
                             inline=False)
Ejemplo n.º 13
0
    async def collect_roles(self, category, reaction_message, ctx):
        """Presents another Embed and gives the user the roles they selected"""
        embed = discord.Embed(type="rich", colour=utils.generate_random_colour())
        embed.set_author(name="Select roles from {}".format(category))
        embed.description = "Click on the emojis at the bottom of this panel that correspond with the roles you want added to your profile. The panel will close itself in 30 seconds, allowing you to select as many roles as you want."
        if category is list(ROLE_CATEGORIES)[0]:
            embed.set_footer(text="Please select one role.")
        else:
            embed.set_footer(text="You have 30 seconds to choose your roles")

        roles_list = []
        for i, r in enumerate(ROLE_CATEGORIES[category]):
            roles_list.append("{} {}".format(utils.resolve_emoji_from_alphabet(utils.ALPHABET[i]), r))

        embed.add_field(name="Available Roles", value="\n".join(roles_list))

        await self.bot.clear_reactions(reaction_message)
        await self.bot.edit_message(reaction_message, embed=embed)

        for i, r in enumerate(ROLE_CATEGORIES[category]):
            await self.bot.add_reaction(reaction_message, utils.resolve_emoji_from_alphabet(utils.ALPHABET[i]))

        # Allow only one role for Years / Course Levels
        if category is list(ROLE_CATEGORIES)[0]:
            def check(reaction, user):
                if user.id != ctx.message.author.id:
                    return False

                letter = utils.resolve_letter_from_emoji(reaction.emoji)
                for i in range(0, len(ROLE_CATEGORIES[list(ROLE_CATEGORIES)[0]])):
                    if letter == utils.ALPHABET[i]:
                        return True

                return False

            res = await self.bot.wait_for_reaction(message=reaction_message, check=check, timeout=30)

            index = utils.ALPHABET.index(utils.resolve_letter_from_emoji(res.reaction.emoji))
            role_to_add = ROLE_CATEGORIES[list(ROLE_CATEGORIES)[0]][index]
            role_to_add = next((r for r in ctx.message.server.roles if r.name == role_to_add), None)

            await self.handle_years(role_to_add, ctx.message.author)
            return [role_to_add]
        else:
            await self.bot.wait_until_ready()
            await asyncio.sleep(30)

            # Update the message that collects the reactions so we can access `.reactions`
            reaction_message = await self.bot.get_message(reaction_message.channel, reaction_message.id)

            selected_emojis = reaction_message.reactions.copy()
            reaction_users = []
            for i, reaction in enumerate(reaction_message.reactions):
                reaction_users.append(await self.bot.get_reaction_users(reaction))

            for i, reaction in enumerate(reaction_message.reactions):
                id_list = list(map(lambda x: x.id, reaction_users[i]))

                if ctx.message.author.id not in id_list:
                    selected_emojis.remove(reaction)

            roles_selected = list(map(lambda r: utils.ALPHABET.index(utils.resolve_letter_from_emoji(r.emoji)), selected_emojis))
            roles_to_add = list(map(lambda i: ROLE_CATEGORIES[category][i], roles_selected))
            for i, role_string in enumerate(roles_to_add):
                roles_to_add[i] = next((r for r in ctx.message.server.roles if r.name == role_string), None)

            # Remove all potential `None` from the list
            roles_to_add = [x for x in roles_to_add if x is not None]
            return roles_to_add