diff options
-rw-r--r-- | bot/constants.py | 11 | ||||
-rw-r--r-- | bot/exts/evergreen/bookmark.py | 3 | ||||
-rw-r--r-- | bot/exts/evergreen/emoji_count.py | 91 | ||||
-rw-r--r-- | bot/exts/evergreen/source.py | 109 | ||||
-rw-r--r-- | bot/exts/halloween/hacktober-issue-finder.py | 12 | ||||
-rw-r--r-- | bot/exts/halloween/hacktoberstats.py | 39 | ||||
-rw-r--r-- | bot/exts/halloween/spookysound.py | 48 | ||||
-rw-r--r-- | bot/exts/halloween/timeleft.py | 32 | ||||
-rw-r--r-- | bot/exts/valentines/valentine_zodiac.py | 145 | ||||
-rw-r--r-- | bot/resources/valentines/zodiac_compatibility.json | 24 | ||||
-rw-r--r-- | bot/resources/valentines/zodiac_explanation.json | 122 | ||||
-rw-r--r-- | bot/utils/converters.py | 16 |
12 files changed, 531 insertions, 121 deletions
diff --git a/bot/constants.py b/bot/constants.py index 935b90e0..e113428e 100644 --- a/bot/constants.py +++ b/bot/constants.py @@ -11,7 +11,6 @@ __all__ = ( "Client", "Colours", "Emojis", - "Hacktoberfest", "Icons", "Lovefest", "Month", @@ -75,7 +74,7 @@ class Channels(NamedTuple): python_discussion = 267624335836053506 show_your_projects = int(environ.get("CHANNEL_SHOW_YOUR_PROJECTS", 303934982764625920)) show_your_projects_discussion = 360148304664723466 - hacktoberfest_2019 = 628184417646411776 + hacktoberfest_2020 = 760857070781071431 class Client(NamedTuple): @@ -129,10 +128,6 @@ class Emojis: status_offline = "<:status_offline:470326266537705472>" -class Hacktoberfest(NamedTuple): - voice_id = 514420006474219521 - - class Icons: questionmark = "https://cdn.discordapp.com/emojis/512367613339369475.png" bookmark = ( @@ -272,3 +267,7 @@ POSITIVE_REPLIES = [ class Wikipedia: total_chance = 3 + +class Source: + github = "https://github.com/python-discord/seasonalbot" + github_avatar_url = "https://avatars1.githubusercontent.com/u/9919" diff --git a/bot/exts/evergreen/bookmark.py b/bot/exts/evergreen/bookmark.py index 73908702..5fa05d2e 100644 --- a/bot/exts/evergreen/bookmark.py +++ b/bot/exts/evergreen/bookmark.py @@ -5,6 +5,7 @@ import discord from discord.ext import commands from bot.constants import Colours, ERROR_REPLIES, Emojis, Icons +from bot.utils.converters import WrappedMessageConverter log = logging.getLogger(__name__) @@ -19,7 +20,7 @@ class Bookmark(commands.Cog): async def bookmark( self, ctx: commands.Context, - target_message: discord.Message, + target_message: WrappedMessageConverter, *, title: str = "Bookmark" ) -> None: diff --git a/bot/exts/evergreen/emoji_count.py b/bot/exts/evergreen/emoji_count.py new file mode 100644 index 00000000..ef900199 --- /dev/null +++ b/bot/exts/evergreen/emoji_count.py @@ -0,0 +1,91 @@ +import datetime +import logging +import random +from typing import Dict, Optional + +import discord +from discord.ext import commands + +from bot.constants import Colours, ERROR_REPLIES + +log = logging.getLogger(__name__) + + +class EmojiCount(commands.Cog): + """Command that give random emoji based on category.""" + + def __init__(self, bot: commands.Bot): + self.bot = bot + + def embed_builder(self, emoji: dict) -> discord.Embed: + """Generates an embed with the emoji names and count.""" + embed = discord.Embed( + color=Colours.orange, + title="Emoji Count", + timestamp=datetime.datetime.utcnow() + ) + + if len(emoji) == 1: + for key, value in emoji.items(): + embed.description = f"There are **{len(value)}** emojis in the **{key}** category" + embed.set_thumbnail(url=random.choice(value).url) + else: + msg = '' + for key, value in emoji.items(): + emoji_choice = random.choice(value) + emoji_info = f'There are **{len(value)}** emojis in the **{key}** category\n' + msg += f'<:{emoji_choice.name}:{emoji_choice.id}> {emoji_info}' + embed.description = msg + return embed + + @staticmethod + def generate_invalid_embed(ctx: commands.Context) -> discord.Embed: + """Genrates error embed.""" + embed = discord.Embed( + color=Colours.soft_red, + title=random.choice(ERROR_REPLIES) + ) + + emoji_dict = {} + for emoji in ctx.guild.emojis: + emoji_dict[emoji.name.split("_")[0]] = [] + + error_comp = ', '.join(key for key in emoji_dict.keys()) + embed.description = f"These are the valid categories\n```{error_comp}```" + return embed + + def emoji_list(self, ctx: commands.Context, categories: dict) -> Dict: + """Generates an embed with the emoji names and count.""" + out = {category: [] for category in categories} + + for emoji in ctx.guild.emojis: + category = emoji.name.split('_')[0] + if category in out: + out[category].append(emoji) + return out + + @commands.command(name="emoji_count", aliases=["ec"]) + async def ec(self, ctx: commands.Context, *, emoji: str = None) -> Optional[str]: + """Returns embed with emoji category and info given by the user.""" + emoji_dict = {} + + for a in ctx.guild.emojis: + if emoji is None: + log.trace("Emoji Category not provided by the user") + emoji_dict.update({a.name.split("_")[0]: []}) + elif a.name.split("_")[0] in emoji: + log.trace("Emoji Category provided by the user") + emoji_dict.update({a.name.split("_")[0]: []}) + + emoji_dict = self.emoji_list(ctx, emoji_dict) + + if len(emoji_dict) == 0: + embed = self.generate_invalid_embed(ctx) + else: + embed = self.embed_builder(emoji_dict) + await ctx.send(embed=embed) + + +def setup(bot: commands.Bot) -> None: + """Emoji Count Cog load.""" + bot.add_cog(EmojiCount(bot)) diff --git a/bot/exts/evergreen/source.py b/bot/exts/evergreen/source.py new file mode 100644 index 00000000..0725714f --- /dev/null +++ b/bot/exts/evergreen/source.py @@ -0,0 +1,109 @@ +import inspect +from pathlib import Path +from typing import Optional, Tuple, Union + +from discord import Embed +from discord.ext import commands + +from bot.constants import Source + +SourceType = Union[commands.Command, commands.Cog, str, commands.ExtensionNotLoaded] + + +class SourceConverter(commands.Converter): + """Convert an argument into a help command, tag, command, or cog.""" + + async def convert(self, ctx: commands.Context, argument: str) -> SourceType: + """Convert argument into source object.""" + cog = ctx.bot.get_cog(argument) + if cog: + return cog + + cmd = ctx.bot.get_command(argument) + if cmd: + return cmd + + raise commands.BadArgument( + f"Unable to convert `{argument}` to valid command or Cog." + ) + + +class BotSource(commands.Cog): + """Displays information about the bot's source code.""" + + def __init__(self, bot: commands.Bot): + self.bot = bot + + @commands.command(name="source", aliases=("src",)) + async def source_command(self, ctx: commands.Context, *, source_item: SourceConverter = None) -> None: + """Display information and a GitHub link to the source code of a command, tag, or cog.""" + if not source_item: + embed = Embed(title="Seasonal Bot's GitHub Repository") + embed.add_field(name="Repository", value=f"[Go to GitHub]({Source.github})") + embed.set_thumbnail(url=Source.github_avatar_url) + await ctx.send(embed=embed) + return + + embed = await self.build_embed(source_item) + await ctx.send(embed=embed) + + def get_source_link(self, source_item: SourceType) -> Tuple[str, str, Optional[int]]: + """ + Build GitHub link of source item, return this link, file location and first line number. + + Raise BadArgument if `source_item` is a dynamically-created object (e.g. via internal eval). + """ + if isinstance(source_item, commands.Command): + src = source_item.callback.__code__ + filename = src.co_filename + else: + src = type(source_item) + try: + filename = inspect.getsourcefile(src) + except TypeError: + raise commands.BadArgument("Cannot get source for a dynamically-created object.") + + if not isinstance(source_item, str): + try: + lines, first_line_no = inspect.getsourcelines(src) + except OSError: + raise commands.BadArgument("Cannot get source for a dynamically-created object.") + + lines_extension = f"#L{first_line_no}-L{first_line_no+len(lines)-1}" + else: + first_line_no = None + lines_extension = "" + + file_location = Path(filename).relative_to(Path.cwd()).as_posix() + + url = f"{Source.github}/blob/master/{file_location}{lines_extension}" + + return url, file_location, first_line_no or None + + async def build_embed(self, source_object: SourceType) -> Optional[Embed]: + """Build embed based on source object.""" + url, location, first_line = self.get_source_link(source_object) + + if isinstance(source_object, commands.Command): + if source_object.cog_name == 'Help': + title = "Help Command" + description = source_object.__doc__.splitlines()[1] + else: + description = source_object.short_doc + title = f"Command: {source_object.qualified_name}" + else: + title = f"Cog: {source_object.qualified_name}" + description = source_object.description.splitlines()[0] + + embed = Embed(title=title, description=description) + embed.set_thumbnail(url=Source.github_avatar_url) + embed.add_field(name="Source Code", value=f"[Go to GitHub]({url})") + line_text = f":{first_line}" if first_line else "" + embed.set_footer(text=f"{location}{line_text}") + + return embed + + +def setup(bot: commands.Bot) -> None: + """Load the BotSource cog.""" + bot.add_cog(BotSource(bot)) diff --git a/bot/exts/halloween/hacktober-issue-finder.py b/bot/exts/halloween/hacktober-issue-finder.py index b5ad1c4f..78acf391 100644 --- a/bot/exts/halloween/hacktober-issue-finder.py +++ b/bot/exts/halloween/hacktober-issue-finder.py @@ -7,13 +7,19 @@ import aiohttp import discord from discord.ext import commands -from bot.constants import Month +from bot.constants import Month, Tokens from bot.utils.decorators import in_month log = logging.getLogger(__name__) URL = "https://api.github.com/search/issues?per_page=100&q=is:issue+label:hacktoberfest+language:python+state:open" -HEADERS = {"Accept": "application / vnd.github.v3 + json"} + +REQUEST_HEADERS = { + "User-Agent": "Python Discord Hacktoberbot", + "Accept": "application / vnd.github.v3 + json" +} +if GITHUB_TOKEN := Tokens.github: + REQUEST_HEADERS["Authorization"] = f"token {GITHUB_TOKEN}" class HacktoberIssues(commands.Cog): @@ -66,7 +72,7 @@ class HacktoberIssues(commands.Cog): url += f"&page={page}" log.debug(f"making api request to url: {url}") - async with session.get(url, headers=HEADERS) as response: + async with session.get(url, headers=REQUEST_HEADERS) as response: if response.status != 200: log.error(f"expected 200 status (got {response.status}) from the GitHub api.") await ctx.send(f"ERROR: expected 200 status (got {response.status}) from the GitHub api.") diff --git a/bot/exts/halloween/hacktoberstats.py b/bot/exts/halloween/hacktoberstats.py index db5e37f2..ed1755e3 100644 --- a/bot/exts/halloween/hacktoberstats.py +++ b/bot/exts/halloween/hacktoberstats.py @@ -10,7 +10,7 @@ import aiohttp import discord from discord.ext import commands -from bot.constants import Channels, Month, WHITELISTED_CHANNELS +from bot.constants import Channels, Month, Tokens, WHITELISTED_CHANNELS from bot.utils.decorators import in_month, override_in_channel from bot.utils.persist import make_persistent @@ -18,7 +18,16 @@ log = logging.getLogger(__name__) CURRENT_YEAR = datetime.now().year # Used to construct GH API query PRS_FOR_SHIRT = 4 # Minimum number of PRs before a shirt is awarded -HACKTOBER_WHITELIST = WHITELISTED_CHANNELS + (Channels.hacktoberfest_2019,) +HACKTOBER_WHITELIST = WHITELISTED_CHANNELS + (Channels.hacktoberfest_2020,) + +REQUEST_HEADERS = {"User-Agent": "Python Discord Hacktoberbot"} +if GITHUB_TOKEN := Tokens.github: + REQUEST_HEADERS["Authorization"] = f"token {GITHUB_TOKEN}" + +GITHUB_NONEXISTENT_USER_MESSAGE = ( + "The listed users cannot be searched either because the users do not exist " + "or you do not have permission to view the users." +) class HacktoberStats(commands.Cog): @@ -29,7 +38,7 @@ class HacktoberStats(commands.Cog): self.link_json = make_persistent(Path("bot", "resources", "halloween", "github_links.json")) self.linked_accounts = self.load_linked_users() - @in_month(Month.OCTOBER) + @in_month(Month.SEPTEMBER, Month.OCTOBER, Month.NOVEMBER) @commands.group(name="hacktoberstats", aliases=("hackstats",), invoke_without_command=True) @override_in_channel(HACKTOBER_WHITELIST) async def hacktoberstats_group(self, ctx: commands.Context, github_username: str = None) -> None: @@ -57,7 +66,7 @@ class HacktoberStats(commands.Cog): await self.get_stats(ctx, github_username) - @in_month(Month.OCTOBER) + @in_month(Month.SEPTEMBER, Month.OCTOBER, Month.NOVEMBER) @hacktoberstats_group.command(name="link") @override_in_channel(HACKTOBER_WHITELIST) async def link_user(self, ctx: commands.Context, github_username: str = None) -> None: @@ -92,7 +101,7 @@ class HacktoberStats(commands.Cog): logging.info(f"{author_id} tried to link a GitHub account but didn't provide a username") await ctx.send(f"{author_mention}, a GitHub username is required to link your account") - @in_month(Month.OCTOBER) + @in_month(Month.SEPTEMBER, Month.OCTOBER, Month.NOVEMBER) @hacktoberstats_group.command(name="unlink") @override_in_channel(HACKTOBER_WHITELIST) async def unlink_user(self, ctx: commands.Context) -> None: @@ -175,11 +184,11 @@ class HacktoberStats(commands.Cog): n = pr_stats['n_prs'] if n >= PRS_FOR_SHIRT: - shirtstr = f"**{github_username} has earned a tshirt!**" + shirtstr = f"**{github_username} has earned a T-shirt or a tree!**" elif n == PRS_FOR_SHIRT - 1: - shirtstr = f"**{github_username} is 1 PR away from a tshirt!**" + shirtstr = f"**{github_username} is 1 PR away from a T-shirt or a tree!**" else: - shirtstr = f"**{github_username} is {PRS_FOR_SHIRT - n} PRs away from a tshirt!**" + shirtstr = f"**{github_username} is {PRS_FOR_SHIRT - n} PRs away from a T-shirt or a tree!**" stats_embed = discord.Embed( title=f"{github_username}'s Hacktoberfest", @@ -196,7 +205,7 @@ class HacktoberStats(commands.Cog): stats_embed.set_author( name="Hacktoberfest", url="https://hacktoberfest.digitalocean.com", - icon_url="https://hacktoberfest.digitalocean.com/pretty_logo.png" + icon_url="https://avatars1.githubusercontent.com/u/35706162?s=200&v=4" ) stats_embed.add_field( name="Top 5 Repositories:", @@ -242,16 +251,22 @@ class HacktoberStats(commands.Cog): f"&per_page={per_page}" ) - headers = {"user-agent": "Discord Python Hacktoberbot"} async with aiohttp.ClientSession() as session: - async with session.get(query_url, headers=headers) as resp: + async with session.get(query_url, headers=REQUEST_HEADERS) as resp: jsonresp = await resp.json() if "message" in jsonresp.keys(): # One of the parameters is invalid, short circuit for now api_message = jsonresp["errors"][0]["message"] - logging.error(f"GitHub API request for '{github_username}' failed with message: {api_message}") + + # Ignore logging non-existent users or users we do not have permission to see + if api_message == GITHUB_NONEXISTENT_USER_MESSAGE: + logging.debug(f"No GitHub user found named '{github_username}'") + else: + logging.error(f"GitHub API request for '{github_username}' failed with message: {api_message}") + return + else: if jsonresp["total_count"] == 0: # Short circuit if there aren't any PRs diff --git a/bot/exts/halloween/spookysound.py b/bot/exts/halloween/spookysound.py deleted file mode 100644 index 569a9153..00000000 --- a/bot/exts/halloween/spookysound.py +++ /dev/null @@ -1,48 +0,0 @@ -import logging -import random -from pathlib import Path - -import discord -from discord.ext import commands - -from bot.bot import SeasonalBot -from bot.constants import Hacktoberfest - -log = logging.getLogger(__name__) - - -class SpookySound(commands.Cog): - """A cog that plays a spooky sound in a voice channel on command.""" - - def __init__(self, bot: SeasonalBot): - self.bot = bot - self.sound_files = list(Path("bot/resources/halloween/spookysounds").glob("*.mp3")) - self.channel = None - - @commands.cooldown(rate=1, per=1) - @commands.command(brief="Play a spooky sound, restricted to once per 2 mins") - async def spookysound(self, ctx: commands.Context) -> None: - """ - Connect to the Hacktoberbot voice channel, play a random spooky sound, then disconnect. - - Cannot be used more than once in 2 minutes. - """ - if not self.channel: - await self.bot.wait_until_guild_available() - self.channel = self.bot.get_channel(Hacktoberfest.voice_id) - - await ctx.send("Initiating spooky sound...") - file_path = random.choice(self.sound_files) - src = discord.FFmpegPCMAudio(str(file_path.resolve())) - voice = await self.channel.connect() - voice.play(src, after=lambda e: self.bot.loop.create_task(self.disconnect(voice))) - - @staticmethod - async def disconnect(voice: discord.VoiceClient) -> None: - """Helper method to disconnect a given voice client.""" - await voice.disconnect() - - -def setup(bot: SeasonalBot) -> None: - """Spooky sound Cog load.""" - bot.add_cog(SpookySound(bot)) diff --git a/bot/exts/halloween/timeleft.py b/bot/exts/halloween/timeleft.py index 295acc89..47adb09b 100644 --- a/bot/exts/halloween/timeleft.py +++ b/bot/exts/halloween/timeleft.py @@ -13,20 +13,23 @@ class TimeLeft(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot - @staticmethod - def in_october() -> bool: - """Return True if the current month is October.""" - return datetime.utcnow().month == 10 + def in_hacktober(self) -> bool: + """Return True if the current time is within Hacktoberfest.""" + _, end, start = self.load_date() + + now = datetime.utcnow() + + return start <= now <= end @staticmethod - def load_date() -> Tuple[int, datetime, datetime]: + def load_date() -> Tuple[datetime, datetime, datetime]: """Return of a tuple of the current time and the end and start times of the next October.""" now = datetime.utcnow() year = now.year if now.month > 10: year += 1 - end = datetime(year, 11, 1, 11, 59, 59) - start = datetime(year, 10, 1) + end = datetime(year, 11, 1, 12) # November 1st 12:00 (UTC-12:00) + start = datetime(year, 9, 30, 10) # September 30th 10:00 (UTC+14:00) return now, end, start @commands.command() @@ -35,16 +38,23 @@ class TimeLeft(commands.Cog): Calculates the time left until the end of Hacktober. Whilst in October, displays the days, hours and minutes left. - Only displays the days left until the beginning and end whilst in a different month + Only displays the days left until the beginning and end whilst in a different month. + + This factors in that Hacktoberfest starts when it is October anywhere in the world + and ends with the same rules. It treats the start as UTC+14:00 and the end as + UTC-12. """ now, end, start = self.load_date() diff = end - now days, seconds = diff.days, diff.seconds - if self.in_october(): + if self.in_hacktober(): minutes = seconds // 60 hours, minutes = divmod(minutes, 60) - await ctx.send(f"There is currently only {days} days, {hours} hours and {minutes}" - "minutes left until the end of Hacktober.") + + await ctx.send( + f"There are {days} days, {hours} hours and {minutes}" + f" minutes left until the end of Hacktober." + ) else: start_diff = start - now start_days = start_diff.days diff --git a/bot/exts/valentines/valentine_zodiac.py b/bot/exts/valentines/valentine_zodiac.py index ef9ddc78..2696999f 100644 --- a/bot/exts/valentines/valentine_zodiac.py +++ b/bot/exts/valentines/valentine_zodiac.py @@ -1,7 +1,10 @@ +import calendar +import json import logging import random -from json import load +from datetime import datetime from pathlib import Path +from typing import Tuple, Union import discord from discord.ext import commands @@ -19,37 +22,123 @@ class ValentineZodiac(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot - self.zodiacs = self.load_json() + self.zodiacs, self.zodiac_fact = self.load_comp_json() @staticmethod - def load_json() -> dict: + def load_comp_json() -> Tuple[dict, dict]: """Load zodiac compatibility from static JSON resource.""" - p = Path("bot/resources/valentines/zodiac_compatibility.json") - with p.open(encoding="utf8") as json_data: - zodiacs = load(json_data) - return zodiacs - - @commands.command(name="partnerzodiac") - async def counter_zodiac(self, ctx: commands.Context, zodiac_sign: str) -> None: - """Provides a counter compatible zodiac sign to the given user's zodiac sign.""" - try: - compatible_zodiac = random.choice(self.zodiacs[zodiac_sign.lower()]) - except KeyError: - return await ctx.send(zodiac_sign.capitalize() + " zodiac sign does not exist.") - - emoji1 = random.choice(HEART_EMOJIS) - emoji2 = random.choice(HEART_EMOJIS) - embed = discord.Embed( - title="Zodic Compatibility", - description=f'{zodiac_sign.capitalize()}{emoji1}{compatible_zodiac["Zodiac"]}\n' - f'{emoji2}Compatibility meter : {compatible_zodiac["compatibility_score"]}{emoji2}', - color=Colours.pink - ) - embed.add_field( - name=f'A letter from Dr.Zodiac {LETTER_EMOJI}', - value=compatible_zodiac['description'] - ) + explanation_file = Path("bot/resources/valentines/zodiac_explanation.json") + compatibility_file = Path("bot/resources/valentines/zodiac_compatibility.json") + with explanation_file.open(encoding="utf8") as json_data: + zodiac_fact = json.load(json_data) + for zodiac_data in zodiac_fact.values(): + zodiac_data['start_at'] = datetime.fromisoformat(zodiac_data['start_at']) + zodiac_data['end_at'] = datetime.fromisoformat(zodiac_data['end_at']) + + with compatibility_file.open(encoding="utf8") as json_data: + zodiacs = json.load(json_data) + + return zodiacs, zodiac_fact + + def generate_invalidname_embed(self, zodiac: str) -> discord.Embed: + """Returns error embed.""" + embed = discord.Embed() + embed.color = Colours.soft_red + error_msg = f"**{zodiac}** is not a valid zodiac sign, here is the list of valid zodiac signs.\n" + names = list(self.zodiac_fact) + middle_index = len(names) // 2 + first_half_names = ", ".join(names[:middle_index]) + second_half_names = ", ".join(names[middle_index:]) + embed.description = error_msg + first_half_names + ",\n" + second_half_names + log.info("Invalid zodiac name provided.") + return embed + + def zodiac_build_embed(self, zodiac: str) -> discord.Embed: + """Gives informative zodiac embed.""" + zodiac = zodiac.capitalize() + embed = discord.Embed() + embed.color = Colours.pink + if zodiac in self.zodiac_fact: + log.trace("Making zodiac embed.") + embed.title = f"__{zodiac}__" + embed.description = self.zodiac_fact[zodiac]["About"] + embed.add_field(name='__Motto__', value=self.zodiac_fact[zodiac]["Motto"], inline=False) + embed.add_field(name='__Strengths__', value=self.zodiac_fact[zodiac]["Strengths"], inline=False) + embed.add_field(name='__Weaknesses__', value=self.zodiac_fact[zodiac]["Weaknesses"], inline=False) + embed.add_field(name='__Full form__', value=self.zodiac_fact[zodiac]["full_form"], inline=False) + embed.set_thumbnail(url=self.zodiac_fact[zodiac]["url"]) + else: + embed = self.generate_invalidname_embed(zodiac) + log.trace("Successfully created zodiac information embed.") + return embed + + def zodiac_date_verifier(self, query_date: datetime) -> str: + """Returns zodiac sign by checking date.""" + for zodiac_name, zodiac_data in self.zodiac_fact.items(): + if zodiac_data["start_at"].date() <= query_date.date() <= zodiac_data["end_at"].date(): + log.trace("Zodiac name sent.") + return zodiac_name + + @commands.group(name='zodiac', invoke_without_command=True) + async def zodiac(self, ctx: commands.Context, zodiac_sign: str) -> None: + """Provides information about zodiac sign by taking zodiac sign name as input.""" + final_embed = self.zodiac_build_embed(zodiac_sign) + await ctx.send(embed=final_embed) + log.trace("Embed successfully sent.") + + @zodiac.command(name="date") + async def date_and_month(self, ctx: commands.Context, date: int, month: Union[int, str]) -> None: + """Provides information about zodiac sign by taking month and date as input.""" + if isinstance(month, str): + month = month.capitalize() + try: + month = list(calendar.month_abbr).index(month[:3]) + log.trace('Valid month name entered by user') + except ValueError: + log.info('Invalid month name entered by user') + await ctx.send(f"Sorry, but `{month}` is not a valid month name.") + return + if (month == 1 and 1 <= date <= 19) or (month == 12 and 22 <= date <= 31): + zodiac = "capricorn" + final_embed = self.zodiac_build_embed(zodiac) + else: + try: + zodiac_sign_based_on_date = self.zodiac_date_verifier(datetime(2020, month, date)) + log.trace("zodiac sign based on month and date received.") + except ValueError as e: + final_embed = discord.Embed() + final_embed.color = Colours.soft_red + final_embed.description = f"Zodiac sign could not be found because.\n```{e}```" + log.info(f'Error in "zodiac date" command:\n{e}.') + else: + final_embed = self.zodiac_build_embed(zodiac_sign_based_on_date) + + await ctx.send(embed=final_embed) + log.trace("Embed from date successfully sent.") + + @zodiac.command(name="partnerzodiac", aliases=['partner']) + async def partner_zodiac(self, ctx: commands.Context, zodiac_sign: str) -> None: + """Provides a random counter compatible zodiac sign to the given user's zodiac sign.""" + embed = discord.Embed() + embed.color = Colours.pink + zodiac_check = self.zodiacs.get(zodiac_sign.capitalize()) + if zodiac_check: + compatible_zodiac = random.choice(self.zodiacs[zodiac_sign.capitalize()]) + emoji1 = random.choice(HEART_EMOJIS) + emoji2 = random.choice(HEART_EMOJIS) + embed.title = "Zodiac Compatibility" + embed.description = ( + f'{zodiac_sign.capitalize()}{emoji1}{compatible_zodiac["Zodiac"]}\n' + f'{emoji2}Compatibility meter : {compatible_zodiac["compatibility_score"]}{emoji2}' + ) + embed.add_field( + name=f'A letter from Dr.Zodiac {LETTER_EMOJI}', + value=compatible_zodiac['description'] + ) + else: + embed = self.generate_invalidname_embed(zodiac_sign) await ctx.send(embed=embed) + log.trace("Embed from date successfully sent.") def setup(bot: commands.Bot) -> None: diff --git a/bot/resources/valentines/zodiac_compatibility.json b/bot/resources/valentines/zodiac_compatibility.json index 3971d40d..ea9a7b37 100644 --- a/bot/resources/valentines/zodiac_compatibility.json +++ b/bot/resources/valentines/zodiac_compatibility.json @@ -1,5 +1,5 @@ { - "aries":[ + "Aries":[ { "Zodiac" : "Sagittarius", "description" : "The Archer is one of the most compatible signs Aries should consider when searching out relationships that will bear fruit. Sagittarians share a certain love of freedom with Aries that will help the two of them conquer new territory together.", @@ -21,7 +21,7 @@ "compatibility_score" : "74%" } ], - "taurus":[ + "Taurus":[ { "Zodiac" : "Virgo", "description" : "Although these signs have their set of differences, the Virgo Taurus compatibility is usually pretty strong. This is because both the signs want the same thing ultimately and have generally synchronous ways of reaching those points. This helps them complement each other and create a healthy relationship between them.", @@ -43,7 +43,7 @@ "compatibility_score" : "91%" } ], - "gemini":[ + "Gemini":[ { "Zodiac" : "Aries", "description" : "The theorem of astrology says that Aries and Gemini have a zero tolerance for boredom and will at once get rid of anything dull. An Arian will let a Geminian enjoy his personal freedom and the Gemini will respect his individuality.", @@ -65,7 +65,7 @@ "compatibility_score" : "91%" } ], - "cancer":[ + "Cancer":[ { "Zodiac" : "Taurus", "description" : "The Cancer Taurus zodiac relationship compatibility is strong because of their mutual love for safety, stability, and comfort. Their mutual understanding will always be powerful, which will be the pillar of strength of their relationship.", @@ -82,7 +82,7 @@ "compatibility_score" : "77%" } ], - "leo":[ + "Leo":[ { "Zodiac" : "Aries", "description" : "A Leo is generous and an Arian is open to life. Sharing the same likes and dislikes, they both crave for fun, romance and excitement. A Leo respects an Arian's need for freedom because an Arian does not interfere much in the life of a Leo. Aries will love the charisma and ideas of the Leo.", @@ -104,7 +104,7 @@ "compatibility_score" : "75%" } ], - "virgo":[ + "Virgo":[ { "Zodiac" : "Taurus", "description" : "Although these signs have their set of differences, the Virgo Taurus compatibility is usually pretty strong. This is because both the signs want the same thing ultimately and have generally synchronous ways of reaching those points. This helps them complement each other and create a healthy relationship between them.", @@ -126,7 +126,7 @@ "compatibility_score" : "77%" } ], - "libra":[ + "Libra":[ { "Zodiac" : "Leo", "description" : "Libra and Leo love match can work well for both the partners and truly help them learn from each other and grow individually, as well as together. Libra and Leo, when in the right frame of mind, form a formidable couple that attracts admiration and respect everywhere it goes.", @@ -148,7 +148,7 @@ "compatibility_score" : "71%" } ], - "scorpio":[ + "Scorpio":[ { "Zodiac" : "Cancer", "description" : "This union is not unusual, but will take a fair share of work in the start. A strong foundation of clear cut communication is mandatory to make this a loving and stress free relationship!", @@ -170,7 +170,7 @@ "compatibility_score" : "81%" } ], - "sagittarius":[ + "Sagittarius":[ { "Zodiac" : "Aries", "description" : "Sagittarius and Aries can make a very compatible pair. Their relationship will have a lot of passion, enthusiasm, and energy. These are very good traits to make their relationship deeper and stronger. Both Aries and Sagittarius will enjoy each other's company and their energy level rises as the relationship grows. Both will support and help in fighting hardships and failures.", @@ -192,7 +192,7 @@ "compatibility_score" : "83%" } ], - "capricorn":[ + "Capricorn":[ { "Zodiac" : "Taurus", "description" : "This is one of the most grounded and reliable bonds of the zodiac chart. If Capricorn and Taurus do find a way to handle their minor issues, they have a good chance of making it together and that too, in a happy, peaceful, and healthy relationship.", @@ -214,7 +214,7 @@ "compatibility_score" : "76%" } ], - "aquarius":[ + "Aquarius":[ { "Zodiac" : "Aries", "description" : "The relationship of Aries and Aquarius is very exciting, adventurous and interesting. They will enjoy each other's company as both of them love fun and freedom.This is a couple that lacks tenderness. They are not two brutes who let their relationship fade as soon as their passion does.", @@ -236,7 +236,7 @@ "compatibility_score" : "83%" } ], - "pisces":[ + "Pisces":[ { "Zodiac" : "Taurus", "description" : "This relationship will survive the test of time if both parties involved have unbreakable trust in each other and nurture that connection they have painstakingly built over the years. They must remember to be honest and committed to their partner through all times.If natural communication flows between them like clockwork, this will be a beautiful love story with a prominent tag of ‘happily-ever-after’ pinned right to it!", diff --git a/bot/resources/valentines/zodiac_explanation.json b/bot/resources/valentines/zodiac_explanation.json new file mode 100644 index 00000000..33864ea5 --- /dev/null +++ b/bot/resources/valentines/zodiac_explanation.json @@ -0,0 +1,122 @@ +{ + "Aries": { + "start_at": "2020-03-21", + "end_at": "2020-04-19", + "About": "Amazing people born between **March 21** to **April 19**. Aries loves to be number one, so it\u2019s no surprise that these audacious rams are the first sign of the zodiac. Bold and ambitious, Aries dives headfirst into even the most challenging situations.", + "Motto": "***\u201cWhen you know yourself, you're empowered. When you accept yourself, you're invincible.\u201d***", + "Strengths": "Courageous, determined, confident, enthusiastic, optimistic, honest, passionate.", + "Weaknesses": "Impatient, moody, short-tempered, impulsive, aggressive.", + "full_form": "__**A**__ssertive, __**R**__efreshing, __**I**__ndependent, __**E**__nergetic, __**S**__exy", + "url": "https://www.horoscope.com/images-US/signs/profile-aries.png" + }, + "Taurus": { + "start_at": "2020-04-20", + "end_at": "2020-05-20", + "About": "Amazing people born between **April 20** to **May 20**. Taurus is an earth sign represented by the bull. Like their celestial spirit animal, Taureans enjoy relaxing in serene, bucolic environments surrounded by soft sounds, soothing aromas, and succulent flavors", + "Motto": "***\u201cNothing worth having comes easy.\u201d***", + "Strengths": "Reliable, patient, practical, devoted, responsible, stable.", + "Weaknesses": "Stubborn, possessive, uncompromising.", + "full_form": "__**T**__railblazing, __**A**__mbitious, __**U**__nwavering, __**R**__eliable, __**U**__nderstanding, __**S**__table", + "url": "https://www.horoscope.com/images-US/signs/profile-taurus.png" + }, + "Gemini": { + "start_at": "2020-05-21", + "end_at": "2020-06-20", + "About": "Amazing people born between **May 21** to **June 20**. Have you ever been so busy that you wished you could clone yourself just to get everything done? That\u2019s the Gemini experience in a nutshell. Appropriately symbolized by the celestial twins, this air sign was interested in so many pursuits that it had to double itself.", + "Motto": "***\u201cI manifest my reality.\u201d***", + "Strengths": "Gentle, affectionate, curious, adaptable, ability to learn quickly and exchange ideas.", + "Weaknesses": "Nervous, inconsistent, indecisive.", + "full_form": "__**G**__enerous, __**E**__motionally in tune, __**M**__otivated, __**I**__maginative, __**N**__ice, __**I**__ntelligent", + "url": "https://www.horoscope.com/images-US/signs/profile-gemini.png" + }, + "Cancer": { + "start_at": "2020-06-21", + "end_at": "2020-07-22", + "About": "Amazing people born between **June 21 ** to **July 22**. Cancer is a cardinal water sign. Represented by the crab, this crustacean seamlessly weaves between the sea and shore representing Cancer\u2019s ability to exist in both emotional and material realms. Cancers are highly intuitive and their psychic abilities manifest in tangible spaces: For instance, Cancers can effortlessly pick up the energies in a room.", + "Motto": "***\u201cI feel, therefore I am.\u201d***", + "Strengths": "Tenacious, highly imaginative, loyal, emotional, sympathetic, persuasive.", + "Weaknesses": "Moody, pessimistic, suspicious, manipulative, insecuremoody, pessimistic, suspicious, manipulative, insecure.", + "full_form": "__**C**__aring, __**A**__mbitious, __**N**__ourishing, __**C**__reative, __**E**__motionally intelligent, __**R**__esilient", + "url": "https://www.horoscope.com/images-US/signs/profile-cancer.png" + }, + "Leo": { + "start_at": "2020-07-23", + "end_at": "2020-08-22", + "About": "Amazing people born between **July 23** to **August 22**. Roll out the red carpet because Leo has arrived. Leo is represented by the lion and these spirited fire signs are the kings and queens of the celestial jungle. They\u2019re delighted to embrace their royal status: Vivacious, theatrical, and passionate, Leos love to bask in the spotlight and celebrate themselves.", + "Motto": "***\u201cIf you know the way, go the way and show the way\u2014you're a leader.\u201d***", + "Strengths": "Creative, passionate, generous, warm-hearted, cheerful, humorous.", + "Weaknesses": "Arrogant, stubborn, self-centered, lazy, inflexible.", + "full_form": "__**L**__eaders, __**E**__nergetic, __**O**__ptimistic", + "url": "https://www.horoscope.com/images-US/signs/profile-leo.png" + }, + "Virgo": { + "start_at": "2020-08-23", + "end_at": "2020-09-22", + "About": "Amazing people born between **August 23** to **September 22**. Virgo is an earth sign historically represented by the goddess of wheat and agriculture, an association that speaks to Virgo\u2019s deep-rooted presence in the material world. Virgos are logical, practical, and systematic in their approach to life. This earth sign is a perfectionist at heart and isn\u2019t afraid to improve skills through diligent and consistent practice.", + "Motto": "***\u201cMy best can always be better.\u201d***", + "Strengths": "Loyal, analytical, kind, hardworking, practical.", + "Weaknesses": "Shyness, worry, overly critical of self and others, all work and no play.", + "full_form": "__**V**__irtuous, __**I**__ntelligent, __**R**__esponsible, __**G**__enerous, __**O**__ptimistic", + "url": "https://www.horoscope.com/images-US/signs/profile-virgo.png" + }, + "Libra": { + "start_at": "2020-09-23", + "end_at": "2020-10-22", + "About": "Amazing people born between **September 23** to **October 22**. Libra is an air sign represented by the scales (interestingly, the only inanimate object of the zodiac), an association that reflects Libra's fixation on balance and harmony. Libra is obsessed with symmetry and strives to create equilibrium in all areas of life.", + "Motto": "***\u201cNo person is an island.\u201d***", + "Strengths": "Cooperative, diplomatic, gracious, fair-minded, social.", + "Weaknesses": "Indecisive, avoids confrontations, will carry a grudge, self-pity.", + "full_form": "__**L**__oyal, __**I**__nquisitive, __**B**__alanced, __**R**__esponsible, __**A**__ltruistic", + "url": "https://www.horoscope.com/images-US/signs/profile-libra.png" + }, + "Scorpio": { + "start_at": "2020-10-23", + "end_at": "2020-11-21", + "About": "Amazing people born between **October 23** to **November 21**. Scorpio is one of the most misunderstood signs of the zodiac. Because of its incredible passion and power, Scorpio is often mistaken for a fire sign. In fact, Scorpio is a water sign that derives its strength from the psychic, emotional realm.", + "Motto": "***\u201cYou never know what you are capable of until you try.\u201d***", + "Strengths": "Resourceful, brave, passionate, stubborn, a true friend.", + "Weaknesses": "Distrusting, jealous, secretive, violent.", + "full_form": "__**S**__eductive, __**C**__erebral, __**O**__riginal, __**R**__eactive, __**P**__assionate, __**I**__ntuitive, __**O**__utstanding", + "url": "https://www.horoscope.com/images-US/signs/profile-scorpio.png" + }, + "Sagittarius": { + "start_at": "2020-11-22", + "end_at": "2020-12-21", + "About": "Amazing people born between **November 22** to **December 21**. Represented by the archer, Sagittarians are always on a quest for knowledge. The last fire sign of the zodiac, Sagittarius launches its many pursuits like blazing arrows, chasing after geographical, intellectual, and spiritual adventures.", + "Motto": "***\u201cTowering genius disdains a beaten path.\u201d***", + "Strengths": "Generous, idealistic, great sense of humor.", + "Weaknesses": "Promises more than can deliver, very impatient, will say anything no matter how undiplomatic.", + "full_form": "__**S**__eductive, __**A**__dventurous, __**G**__rateful, __**I**__ntelligent, __**T**__railblazing, __**T**__enacious adept, __**A**__dept, __**R**__esponsible, __**I**__dealistic, __**U**__nparalled, __**S**__ophisticated", + "url": "https://www.horoscope.com/images-US/signs/profile-sagittarius.png" + }, + "Capricorn": { + "start_at": "2020-12-22", + "end_at": "2021-01-19", + "About": "Amazing people born between **December 22** to **January 19**. The last earth sign of the zodiac, Capricorn is represented by the sea goat, a mythological creature with the body of a goat and tail of a fish. Accordingly, Capricorns are skilled at navigating both the material and emotional realms.", + "Motto": "***\u201cI can succeed at anything I put my mind to.\u201d***", + "Strengths": "Responsible, disciplined, self-control, good managers.", + "Weaknesses": "Know-it-all, unforgiving, condescending, expecting the worst.", + "full_form": "__**C**__onfident, __**A**__nalytical, __**P**__ractical, __**R**__esponsible, __**I**__ntelligent, __**C**__aring, __**O**__rganized, __**R**__ealistic, __**N**__eat", + "url": "https://www.horoscope.com/images-US/signs/profile-capricorn.png" + }, + "Aquarius": { + "start_at": "2020-01-20", + "end_at": "2020-02-18", + "About": "Amazing people born between **January 20** to **February 18**. Despite the \u201caqua\u201d in its name, Aquarius is actually the last air sign of the zodiac. Aquarius is represented by the water bearer, the mystical healer who bestows water, or life, upon the land. Accordingly, Aquarius is the most humanitarian astrological sign.", + "Motto": "***\u201cThere is no me, there is only we.\u201d***", + "Strengths": "Progressive, original, independent, humanitarian.", + "Weaknesses": "Runs from emotional expression, temperamental, uncompromising, aloof.", + "full_form": "__**A**__nalytical, __**Q**__uirky, __**U**__ncompromising, __**A**__ction-focused, __**R**__espectful, __**I**__ntelligent, __**U**__nique, __**S**__incere", + "url": "https://www.horoscope.com/images-US/signs/profile-aquarius.png" + }, + "Pisces": { + "start_at": "2020-02-19", + "end_at": "2020-03-20", + "About": "Amazing people born between **February 19** to **March 20**. Pisces, a water sign, is the last constellation of the zodiac. It's symbolized by two fish swimming in opposite directions, representing the constant division of Pisces' attention between fantasy and reality. As the final sign, Pisces has absorbed every lesson \u2014 the joys and the pain, the hopes and the fears \u2014 learned by all of the other signs.", + "Motto": "***\u201cI have a lot of love to give, it only takes a little patience and those worth giving it all to.\u201d***", + "Strengths": "Compassionate, artistic, intuitive, gentle, wise, musical.", + "Weaknesses": "Fearful, overly trusting, sad, desire to escape reality, can be a victim or a martyr.", + "full_form": "__**P**__sychic, __**I**__ntelligent, __**S**__urprising, __**C**__reative, __**E**__motionally-driven, __**S**__ensitive", + "url": "https://www.horoscope.com/images-US/signs/profile-pisces.png" + } +} diff --git a/bot/utils/converters.py b/bot/utils/converters.py new file mode 100644 index 00000000..228714c9 --- /dev/null +++ b/bot/utils/converters.py @@ -0,0 +1,16 @@ +import discord +from discord.ext.commands.converter import MessageConverter + + +class WrappedMessageConverter(MessageConverter): + """A converter that handles embed-suppressed links like <http://example.com>.""" + + async def convert(self, ctx: discord.ext.commands.Context, argument: str) -> discord.Message: + """Wrap the commands.MessageConverter to handle <> delimited message links.""" + # It's possible to wrap a message in [<>] as well, and it's supported because its easy + if argument.startswith("[") and argument.endswith("]"): + argument = argument[1:-1] + if argument.startswith("<") and argument.endswith(">"): + argument = argument[1:-1] + + return await super().convert(ctx, argument) |