From eaf02ac4c3a41f38244fbfa23f95ea1da289ea17 Mon Sep 17 00:00:00 2001 From: katejoh Date: Fri, 25 Aug 2023 16:00:40 +1000 Subject: [PATCH] style: convert casing according to PEP 8 --- api.py | 20 +-- ...iaQuestions.py => ask_trivia_questions.py} | 124 +++++++------- ...tudySession.py => create_study_session.py} | 38 ++--- cogs/hangman.py | 152 +++++++++--------- cogs/{randomTopic.py => random_topic.py} | 4 +- ...{sendRandomPost.py => send_random_post.py} | 22 +-- cogs/upcomingEvents.py | 51 ------ cogs/upcoming_events.py | 51 ++++++ main.py | 4 +- 9 files changed, 233 insertions(+), 233 deletions(-) rename cogs/{askTriviaQuestions.py => ask_trivia_questions.py} (55%) rename cogs/{createStudySession.py => create_study_session.py} (70%) rename cogs/{randomTopic.py => random_topic.py} (90%) rename cogs/{sendRandomPost.py => send_random_post.py} (62%) delete mode 100644 cogs/upcomingEvents.py create mode 100644 cogs/upcoming_events.py diff --git a/api.py b/api.py index 7df9f27f..779266c4 100644 --- a/api.py +++ b/api.py @@ -11,8 +11,8 @@ client = contentful.Client(SPACE_ID, ACCESS_TOKEN) -def getRandomMarketingPost(category): - categoryPosts = client.entries( +def get_random_marketing_post(category): + category_posts = client.entries( { "content_type": "marketing_archives", "limit": 1000, @@ -22,26 +22,26 @@ def getRandomMarketingPost(category): ) posts = [] - for post in categoryPosts: + for post in category_posts: if post.fields().get("img") != None: posts.append(post) return random.choice(posts) -def getNextUpcomingEvent(): - upcomingEvents = client.entries( +def get_next_upcoming_event(): + upcoming_events = client.entries( {"content_type": "upcomingEvents", "limit": 1, "order": "fields.index"} ) - return upcomingEvents[0] + return upcoming_events[0] -def getUpcomingEvents(): +def get_upcoming_events(): return client.entries({"content_type": "upcomingEvents", "order": "fields.index"}) -def getMostRecentEvent(): - pastEvents = client.entries( +def get_most_recent_event(): + past_events = client.entries( {"content_type": "pastEvents", "limit": 1, "order": "-fields.index"} ) - return pastEvents[0] + return past_events[0] diff --git a/cogs/askTriviaQuestions.py b/cogs/ask_trivia_questions.py similarity index 55% rename from cogs/askTriviaQuestions.py rename to cogs/ask_trivia_questions.py index fd289d50..ceb61130 100644 --- a/cogs/askTriviaQuestions.py +++ b/cogs/ask_trivia_questions.py @@ -4,12 +4,12 @@ from pyopentdb import OpenTDBClient, Category, QuestionType, Difficulty -class asksTriviaQuestionCog(commands.Cog): +class AskTriviaQuestionsCog(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot # Counter variable for incorrect answers - self.incorrectAnswers = 0 - self.answeredUsers = set() + self.incorrect_answers = 0 + self.answered_users = set() @app_commands.command( name="ask-trivia-questions", description="Asks trivia questions!" @@ -22,55 +22,55 @@ def __init__(self, bot: commands.Bot): app_commands.Choice(name="Hard", value=3), ] ) - async def asksTriviaQuestion( + async def ask_trivia_question( self, inter: discord.Interaction, difficulty: app_commands.Choice[int] ): await inter.response.defer() # Reset the answered_users set - self.answeredUsers = set() + self.answered_users = set() # Create a client to retrieve 1 "General Knowledge" question with the specified difficulty client = OpenTDBClient() if difficulty.value == 1: - questionSet = client.get_questions( + question_set = client.get_questions( amount=1, category=Category.GENERAL_KNOWLEDGE, difficulty=Difficulty.EASY, ) elif difficulty.value == 2: - questionSet = client.get_questions( + question_set = client.get_questions( amount=1, category=Category.GENERAL_KNOWLEDGE, difficulty=Difficulty.MEDIUM, ) elif difficulty.value == 3: - questionSet = client.get_questions( + question_set = client.get_questions( amount=1, category=Category.GENERAL_KNOWLEDGE, difficulty=Difficulty.HARD, ) - questionTxt = questionSet.items[0].question - questionDiff = questionSet.items[0].difficulty.name.title() - choices = questionSet.items[0].choices - answerIndx = questionSet.items[0].answer_index + question_txt = question_set.items[0].question + question_diff = question_set.items[0].difficulty.name.title() + choices = question_set.items[0].choices + answer_indx = question_set.items[0].answer_index embed = discord.Embed( title=f"Trivia Question!", - description=f"{questionTxt} \n\n Difficulty: {questionDiff} \n\n Incorrect answers so far: {self.incorrectAnswers}", + description=f"{question_txt} \n\n Difficulty: {question_diff} \n\n Incorrect answers so far: {self.incorrect_answers}", color=discord.Color.orange(), ) # changed from self to self.inccorect view = MyView( choices, - answerIndx, - questionTxt, - questionDiff, - self.incorrectAnswers, - self.answeredUsers, + answer_indx, + question_txt, + question_diff, + self.incorrect_answers, + self.answered_users, False, ) await inter.followup.send( @@ -83,22 +83,22 @@ class MyView(discord.ui.View): def __init__( self, choices, - answerIndx, - questionTxt, - questionDiff, - incorrectAnswers, - answeredUsers, + answer_indx, + question_txt, + question_diff, + incorrect_answers, + answered_users, disabled, ): super().__init__(timeout=None) self.select_menu = AnswersSelectMenu( choices, - answerIndx, - questionTxt, - questionDiff, - incorrectAnswers, - answeredUsers, + answer_indx, + question_txt, + question_diff, + incorrect_answers, + answered_users, disabled, ) @@ -110,20 +110,20 @@ class AnswersSelectMenu(discord.ui.Select): def __init__( self, choices, - answerIndx, - questionTxt, - questionDiff, - incorrectAnswers, - answeredUsers, + answer_indx, + question_txt, + question_diff, + incorrect_answers, + answered_users, disabled, ): - self.questionTxt = questionTxt - self.questionDiff = questionDiff + self.question_txt = question_txt + self.question_diff = question_diff self.choices = choices - self.correctChoice = choices[answerIndx] - self.answerIndx = answerIndx - self.incorrectAnswers = incorrectAnswers - self.answeredUsers = answeredUsers + self.correct_choice = choices[answer_indx] + self.answer_indx = answer_indx + self.incorrect_answers = incorrect_answers + self.answered_users = answered_users super().__init__( placeholder="Select a choice...", @@ -135,11 +135,11 @@ def __init__( self.disabled = disabled async def callback(self, interaction: discord.Interaction): - userId = interaction.user.id + user_id = interaction.user.id - selectedChoice = self.values[0] + selected_choice = self.values[0] - if userId in self.answeredUsers: + if user_id in self.answered_users: # User has already answered, send ephemeral message await interaction.response.send_message( f"You've already attempted answering this question before!", @@ -147,49 +147,49 @@ async def callback(self, interaction: discord.Interaction): ) return - if selectedChoice == self.correctChoice: + if selected_choice == self.correct_choice: # if the selected choice is correct, display a text - await self.updateMessageCorrect(interaction) + await self.update_message_correct(interaction) else: - self.incorrectAnswers += 1 - await self.updateMessageIncorrect(interaction) + self.incorrect_answers += 1 + await self.update_message_incorrect(interaction) - self.answeredUsers.add(userId) # Add the user to the answered users set + self.answered_users.add(user_id) # Add the user to the answered users set - async def updateMessageIncorrect(self, inter: discord.Interaction): + async def update_message_incorrect(self, inter: discord.Interaction): embed = discord.Embed( title=f"Trivia Question!", - description=f"{self.questionTxt} \n\n Difficulty: {self.questionDiff} \n\n Incorrect answers so far: {self.incorrectAnswers}", + description=f"{self.question_txt} \n\n Difficulty: {self.question_diff} \n\n Incorrect answers so far: {self.incorrect_answers}", color=discord.Color.red(), ) view = MyView( self.choices, - self.answerIndx, - self.questionTxt, - self.questionDiff, - self.incorrectAnswers, - self.answeredUsers, + self.answer_indx, + self.question_txt, + self.question_diff, + self.incorrect_answers, + self.answered_users, False, ) await inter.response.edit_message(embed=embed, view=view) - async def updateMessageCorrect(self, inter: discord.Interaction): + async def update_message_correct(self, inter: discord.Interaction): embed = discord.Embed( title=f"Trivia Question!", - description=f"{self.questionTxt} \n\n Difficulty: {self.questionDiff} \n\n <@{inter.user.id}> was the first to guess correctly! The correct answer was: {self.correctChoice} \n\n Incorrect answers so far: {self.incorrectAnswers}", + description=f"{self.question_txt} \n\n Difficulty: {self.question_diff} \n\n <@{inter.user.id}> was the first to guess correctly! The correct answer was: {self.correct_choice} \n\n Incorrect answers so far: {self.incorrect_answers}", color=discord.Color.green(), ) view = MyView( self.choices, - self.answerIndx, - self.questionTxt, - self.questionDiff, - self.incorrectAnswers, - self.answeredUsers, + self.answer_indx, + self.question_txt, + self.question_diff, + self.incorrect_answers, + self.answered_users, True, ) await inter.response.edit_message(embed=embed, view=view) async def setup(bot: commands.Bot): - await bot.add_cog(asksTriviaQuestionCog(bot)) + await bot.add_cog(AskTriviaQuestionsCog(bot)) diff --git a/cogs/createStudySession.py b/cogs/create_study_session.py similarity index 70% rename from cogs/createStudySession.py rename to cogs/create_study_session.py index 8ec8d277..77432a1c 100644 --- a/cogs/createStudySession.py +++ b/cogs/create_study_session.py @@ -6,7 +6,7 @@ from zoneinfo import ZoneInfo -class createStudySessionCog(commands.Cog): +class CreateStudySessionCog(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot @@ -23,12 +23,12 @@ async def create_study_session( self, inter: discord.Interaction, date: str, start_time: str, end_time: str ): timezone = ZoneInfo("Australia/Sydney") - dateFormat = "%Y-%m-%d %H:%M" + date_format = "%Y-%m-%d %H:%M" try: - startTime = dt.datetime.strptime( - f"{date} {start_time}", dateFormat + start_time = dt.datetime.strptime( + f"{date} {start_time}", date_format ).replace(tzinfo=timezone) - endTime = dt.datetime.strptime(f"{date} {end_time}", dateFormat).replace( + end_time = dt.datetime.strptime(f"{date} {end_time}", date_format).replace( tzinfo=timezone ) except ValueError: @@ -40,13 +40,13 @@ async def create_study_session( return # Discord timestamp formatting - startString = f"" - endString = f"" + start_string = f"" + end_string = f"" id = inter.user.id - messageContent = f""" - **🧡 Study Session! 🧡**\n\n<@{id}> is having a study session on {startString} until {endString} in the WIT Discord Server!\n\nClick the buttons below to RSVP.\n\n + message_content = f""" + **🧡 Study Session! 🧡**\n\n<@{id}> is having a study session on {start_string} until {end_string} in the WIT Discord Server!\n\nClick the buttons below to RSVP.\n\n """ embed = discord.Embed( title=f"Attendees (1):", @@ -55,37 +55,37 @@ async def create_study_session( ) view = MyView(id) await inter.response.send_message( - content=messageContent, + content=message_content, embed=embed, view=view, ) class MyView(discord.ui.View): - def __init__(self, creatorId): + def __init__(self, creator_id): super().__init__(timeout=None) - self.attendees = {creatorId} # initialize set of attendees + self.attendees = {creator_id} # initialize set of attendees @discord.ui.button(style=discord.ButtonStyle.green, label="Going") async def going(self, inter: discord.Interaction, button: discord.ui.Button): self.attendees.add(inter.user.id) - await self.updateMessage(inter) + await self.update_message(inter) @discord.ui.button(style=discord.ButtonStyle.red, label="Not Going") - async def notGoing(self, inter: discord.Interaction, button: discord.ui.Button): + async def not_going(self, inter: discord.Interaction, button: discord.ui.Button): self.attendees.discard(inter.user.id) - await self.updateMessage(inter) + await self.update_message(inter) - async def updateMessage(self, inter: discord.Interaction): - attendeesList = "\n".join(f"- <@{attendee}>" for attendee in self.attendees) + async def update_message(self, inter: discord.Interaction): + attendees_list = "\n".join(f"- <@{attendee}>" for attendee in self.attendees) embed = discord.Embed( title=f"Attendees ({len(self.attendees)}):", color=discord.Color.orange(), - description=f"\n\n{attendeesList}", + description=f"\n\n{attendees_list}", ) await inter.response.edit_message(embed=embed) async def setup(bot: commands.Bot): - await bot.add_cog(createStudySessionCog(bot)) + await bot.add_cog(CreateStudySessionCog(bot)) diff --git a/cogs/hangman.py b/cogs/hangman.py index eaade468..18c28676 100644 --- a/cogs/hangman.py +++ b/cogs/hangman.py @@ -5,7 +5,7 @@ from wonderwords import RandomWord -class hangmanCog(commands.Cog): +class HangmanCog(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot @@ -22,40 +22,40 @@ def __init__(self, bot: commands.Bot): app_commands.Choice(name="Random", value=4), ], ) - async def playHangman( + async def play_hangman( self, inter: discord.Interaction, category: app_commands.Choice[int], word_length: str, ): await inter.response.defer() - r = RandomWord() if category.value == 1: - selectedCategory = ["nouns"] + selected_category = ["nouns"] elif category.value == 2: - selectedCategory = ["adjectives"] + selected_category = ["adjectives"] elif category.value == 3: - selectedCategory = ["verbs"] + selected_category = ["verbs"] else: - selectedCategory = None + selected_category = None if word_length.lower() == "random": - selectedLength = None + selected_length = None else: try: - selectedLength = int(word_length) + selected_length = int(word_length) except ValueError: await inter.followup.send( "I can't generate a word unless word_length is an integer or 'Random', please try again." ) return + r = RandomWord() try: - randomWord = r.word( - include_parts_of_speech=selectedCategory, - word_min_length=selectedLength, - word_max_length=selectedLength, + random_word = r.word( + include_parts_of_speech=selected_category, + word_min_length=selected_length, + word_max_length=selected_length, ) except Exception as e: await inter.followup.send( @@ -81,11 +81,11 @@ async def playHangman( embed.add_field(name="Incorrect Letters", value=f"None", inline=True) embed.add_field( name="Word", - value=f"```{' '.join('_' for c in randomWord)}```", + value=f"```{' '.join('_' for c in random_word)}```", inline=False, ) - view = MyView(id, randomWord, category.name) + view = MyView(id, random_word, category.name) await inter.followup.send( embed=embed, view=view, @@ -93,21 +93,21 @@ async def playHangman( class MyView(discord.ui.View): - def __init__(self, creatorId, randomWord, category): + def __init__(self, creator_id, random_word, category): super().__init__(timeout=None) - self.creatorId = creatorId - self.randomWord = randomWord.upper() - self.revealedWord = "".join("_" for c in self.randomWord) - self.incorrectLetters = [] + self.creator_id = creator_id + self.random_word = random_word.upper() + self.revealed_word = "".join("_" for c in self.random_word) + self.incorrect_letters = [] self.pages = [] # list to store button pages - self.pageSize = 13 # Number of buttons per page + self.page_size = 13 # Number of buttons per page self.category = category - self.createButtons() - self.splitButtonsIntoPages() - self.currentPage = 0 - self.addButtonsToCurrentPage() - self.addPageSwitchingButtons() - self.hangmanStages = [ + self.create_buttons() + self.split_buttons_into_pages() + self.current_page = 0 + self.add_buttons_to_current_page() + self.add_page_switching_buttons() + self.hangman_stages = [ "```\n" " +----+\n" " | |\n" @@ -166,82 +166,82 @@ def __init__(self, creatorId, randomWord, category): "```", # 6 wrong ] - def createButtons(self): + def create_buttons(self): self.buttons = [] for letter in list(string.ascii_uppercase): - buttonCallback = self.createButtonCallback(letter) + button_callback = self.create_button_callback(letter) button = discord.ui.Button( style=discord.ButtonStyle.green, label=letter, custom_id=letter ) - button.callback = buttonCallback + button.callback = button_callback self.buttons.append(button) - def splitButtonsIntoPages(self): + def split_buttons_into_pages(self): self.pages = [ - self.buttons[i : i + self.pageSize] - for i in range(0, len(self.buttons), self.pageSize) + self.buttons[i : i + self.page_size] + for i in range(0, len(self.buttons), self.page_size) ] - def createButtonCallback(self, button_id): + def create_button_callback(self, button_id): # Runs when a letter is pressed to update hangman state - async def buttonCallback(interaction): + async def button_callback(interaction): for item in self.children: if item.custom_id == button_id: item.disabled = True - if not self.guessIsCorrect(button_id): - self.incorrectLetters.append(button_id) - if len(self.incorrectLetters) == 6 or self.randomWord == self.revealedWord: + if not self.guess_is_correct(button_id): + self.incorrect_letters.append(button_id) + if len(self.incorrect_letters) == 6 or self.random_word == self.revealed_word: for item in self.children: # Game has ended, disable all buttons item.disabled = True - await self.updateMessage(interaction, button_id) + await self.update_message(interaction, button_id) - return buttonCallback + return button_callback - def guessIsCorrect(self, guess): - correct = guess in self.randomWord + def guess_is_correct(self, guess): + correct = guess in self.random_word if correct: - self.revealedWord = "".join( + self.revealed_word = "".join( c if c == guess else r - for c, r in zip(self.randomWord, self.revealedWord) + for c, r in zip(self.random_word, self.revealed_word) ) return correct - async def updateMessage(self, interaction, button_id): + async def update_message(self, interaction, button_id): # Create a new embed with the updated information - incorrectLettersString = ( + incorrect_letters_string = ( "None" - if len(self.incorrectLetters) == 0 - else f"{(', '.join(c for c in self.incorrectLetters))}" + if len(self.incorrect_letters) == 0 + else f"{(', '.join(c for c in self.incorrect_letters))}" ) embed = discord.Embed( title="Hangman!", - description=f"{self.hangmanStages[min(len(self.incorrectLetters), len(self.hangmanStages)-1)]}", + description=f"{self.hangman_stages[min(len(self.incorrect_letters), len(self.hangman_stages)-1)]}", color=discord.Color.orange(), ) embed.add_field(name="Category", value=f"{self.category}", inline=False) embed.add_field( name="Incorrect Guesses", - value=f"{len(self.incorrectLetters)}/6", + value=f"{len(self.incorrect_letters)}/6", inline=True, ) embed.add_field( - name="Incorrect Letters", value=incorrectLettersString, inline=True + name="Incorrect Letters", value=incorrect_letters_string, inline=True ) embed.add_field( - name="Word", value=f"```{' '.join(self.revealedWord)}```", inline=False + name="Word", value=f"```{' '.join(self.revealed_word)}```", inline=False ) - if len(self.incorrectLetters) == 6: + if len(self.incorrect_letters) == 6: # Game is lost embed.add_field( name="Game Lost!", - value=f"The word was: {self.randomWord}", + value=f"The word was: {self.random_word}", inline=False, ) - elif self.randomWord == self.revealedWord: + elif self.random_word == self.revealed_word: # Game is won embed.add_field( name="Game Won!", @@ -252,43 +252,43 @@ async def updateMessage(self, interaction, button_id): # Update the message with the new embed await interaction.response.edit_message(embed=embed, view=self) - def addPageSwitchingButtons(self): - if self.currentPage > 0: - previousButton = discord.ui.Button( + def add_page_switching_buttons(self): + if self.current_page > 0: + previous_button = discord.ui.Button( style=discord.ButtonStyle.blurple, label="Previous", custom_id="previous", ) - previousButton.callback = self.previous_page - self.add_item(previousButton) + previous_button.callback = self.previous_page + self.add_item(previous_button) - if self.currentPage < len(self.pages) - 1: - nextButton = discord.ui.Button( + if self.current_page < len(self.pages) - 1: + next_button = discord.ui.Button( style=discord.ButtonStyle.blurple, label="Next", custom_id="next" ) - nextButton.callback = self.next_page - self.add_item(nextButton) + next_button.callback = self.next_page + self.add_item(next_button) async def previous_page(self, interaction): - if self.currentPage > 0: - self.currentPage -= 1 - await self.updateView(interaction) + if self.current_page > 0: + self.current_page -= 1 + await self.update_view(interaction) async def next_page(self, interaction): - if self.currentPage < len(self.pages) - 1: - self.currentPage += 1 - await self.updateView(interaction) + if self.current_page < len(self.pages) - 1: + self.current_page += 1 + await self.update_view(interaction) - async def updateView(self, interaction): + async def update_view(self, interaction): self.clear_items() - self.addButtonsToCurrentPage() - self.addPageSwitchingButtons() + self.add_buttons_to_current_page() + self.add_page_switching_buttons() await interaction.response.edit_message(view=self) - def addButtonsToCurrentPage(self): - for button in self.pages[self.currentPage]: + def add_buttons_to_current_page(self): + for button in self.pages[self.current_page]: self.add_item(button) async def setup(bot: commands.Bot): - await bot.add_cog(hangmanCog(bot)) + await bot.add_cog(HangmanCog(bot)) diff --git a/cogs/randomTopic.py b/cogs/random_topic.py similarity index 90% rename from cogs/randomTopic.py rename to cogs/random_topic.py index 078f504b..62f8fc66 100644 --- a/cogs/randomTopic.py +++ b/cogs/random_topic.py @@ -4,7 +4,7 @@ import random_topic -class randomTopicCog(commands.Cog): +class RandomTopicCog(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot @@ -21,4 +21,4 @@ async def random_topic_command(self, int: discord.Interaction): async def setup(bot: commands.Bot): - await bot.add_cog(randomTopicCog(bot)) + await bot.add_cog(RandomTopicCog(bot)) diff --git a/cogs/sendRandomPost.py b/cogs/send_random_post.py similarity index 62% rename from cogs/sendRandomPost.py rename to cogs/send_random_post.py index 927de2f4..fc7f2685 100644 --- a/cogs/sendRandomPost.py +++ b/cogs/send_random_post.py @@ -2,38 +2,38 @@ from discord import app_commands from discord.ext import commands -from api import getRandomMarketingPost +from api import get_random_marketing_post import io import aiohttp -class sendRandomPostCog(commands.Cog): +class RandomPostCog(commands.Cog): def __init__(self, bot: commands.Bot): self.bot = bot @app_commands.command( name="random-willow-motivation", description="Send a random motivational post!" ) - async def sendRandomMotivation(self, int: discord.Interaction): - await sendPost(int, getRandomMarketingPost("Monday")) + async def send_random_motivation(self, int: discord.Interaction): + await send_post(int, get_random_marketing_post("Monday")) @app_commands.command( name="random-willow-meme", description="Send a random Willow meme!" ) async def sendRandomMeme(self, int: discord.Interaction): - await sendPost(int, getRandomMarketingPost("Memes")) + await send_post(int, get_random_marketing_post("Memes")) @app_commands.command( name="random-willow-post", description="Send a random Willow post!" ) async def sendRandomWillow(self, int: discord.Interaction): - await sendPost(int, getRandomMarketingPost("Mascot")) + await send_post(int, get_random_marketing_post("Mascot")) -async def sendPost(int: discord.Interaction, randomPost): - randomPostFields = randomPost.fields() - label = randomPostFields.get("label").replace(" ", "-") + ".png" - link = "https:" + randomPostFields.get("img").url() +async def send_post(int: discord.Interaction, randomPost): + random_post_fields = randomPost.fields() + label = random_post_fields.get("label").replace(" ", "-") + ".png" + link = "https:" + random_post_fields.get("img").url() async with aiohttp.ClientSession() as session: await int.response.defer() @@ -45,4 +45,4 @@ async def sendPost(int: discord.Interaction, randomPost): async def setup(bot: commands.Bot): - await bot.add_cog(sendRandomPostCog(bot)) + await bot.add_cog(RandomPostCog(bot)) diff --git a/cogs/upcomingEvents.py b/cogs/upcomingEvents.py deleted file mode 100644 index c8ec4d77..00000000 --- a/cogs/upcomingEvents.py +++ /dev/null @@ -1,51 +0,0 @@ -import discord -from discord import app_commands -from discord.ext import commands - -from api import getNextUpcomingEvent, getUpcomingEvents, getMostRecentEvent - -EVENT_RECAPS_LINK = "https://unswwit.com/events/event-recaps/" - - -class upcomingEventsCog(commands.Cog): - def __init__(self, bot: commands.Bot): - self.bot = bot - - @app_commands.command( - name="next-upcoming-event", - description="See information about WIT's next upcoming event!", - ) - async def nextUpcomingEvent(self, int: discord.Interaction): - try: - nextEventFields = getNextUpcomingEvent().fields() - await int.response.send_message( - f"**🧡 WIT's next event is *{nextEventFields.get('date')}*! 🧡**\n\n**Event Details:** {nextEventFields.get('title')}\n\n{nextEventFields.get('description')}\n**Event Link: **{nextEventFields.get('facebook_link')}" - ) - except: - await noEventsMessage(int) - - @app_commands.command( - name="all-upcoming-events", - description="See an overview of all of WIT's upcoming events!", - ) - async def upcomingEvents(self, int: discord.Interaction): - upcomingEvents = getUpcomingEvents() - if len(upcomingEvents) == 0: - return await noEventsMessage(int) - - overview = "**🧡 WIT's Upcoming Events 🧡**" - for event in upcomingEvents: - eventFields = event.fields() - overview += f"\n\n*{eventFields.get('date')}*\n{eventFields.get('title')}: <{eventFields.get('facebook_link')}>" - await int.response.send_message(overview) - - -async def noEventsMessage(int: discord.Interaction): - recentEventFields = getMostRecentEvent().fields() - return await int.response.send_message( - f"Unfortunately WIT has no upcoming events for now! Keep an eye out on our socials for new events every term 🧡\n\n**Most Recent Event**\n{recentEventFields.get('title')}: {EVENT_RECAPS_LINK}{recentEventFields.get('year')}/{recentEventFields.get('event_number')}" - ) - - -async def setup(bot: commands.Bot): - await bot.add_cog(upcomingEventsCog(bot)) diff --git a/cogs/upcoming_events.py b/cogs/upcoming_events.py new file mode 100644 index 00000000..e25a36ea --- /dev/null +++ b/cogs/upcoming_events.py @@ -0,0 +1,51 @@ +import discord +from discord import app_commands +from discord.ext import commands + +from api import get_next_upcoming_event, get_upcoming_events, get_most_recent_event + +EVENT_RECAPS_LINK = "https://unswwit.com/events/event-recaps/" + + +class UpcomingEventsCog(commands.Cog): + def __init__(self, bot: commands.Bot): + self.bot = bot + + @app_commands.command( + name="next-upcoming-event", + description="See information about WIT's next upcoming event!", + ) + async def next_upcoming_event(self, int: discord.Interaction): + try: + next_event_fields = get_next_upcoming_event().fields() + await int.response.send_message( + f"**🧡 WIT's next event is *{next_event_fields.get('date')}*! 🧡**\n\n**Event Details:** {next_event_fields.get('title')}\n\n{next_event_fields.get('description')}\n**Event Link: **{next_event_fields.get('facebook_link')}" + ) + except: + await no_events_message(int) + + @app_commands.command( + name="all-upcoming-events", + description="See an overview of all of WIT's upcoming events!", + ) + async def upcoming_events(self, int: discord.Interaction): + upcoming_events = get_upcoming_events() + if len(upcoming_events) == 0: + return await no_events_message(int) + + overview = "**🧡 WIT's Upcoming Events 🧡**" + for event in upcoming_events: + event_fields = event.fields() + overview += f"\n\n*{event_fields.get('date')}*\n{event_fields.get('title')}: <{event_fields.get('facebook_link')}>" + await int.response.send_message(overview) + + +async def no_events_message(int: discord.Interaction): + recent_event_fields = get_most_recent_event().fields() + return await int.response.send_message( + f"Unfortunately WIT has no upcoming events for now! Keep an eye out on our socials for new events every term 🧡\n\n**Most Recent Event**\n{recent_event_fields.get('title')}: {EVENT_RECAPS_LINK}{recent_event_fields.get('year')}/{recent_event_fields.get('event_number')}" + ) + + +async def setup(bot: commands.Bot): + await bot.add_cog(UpcomingEventsCog(bot)) diff --git a/main.py b/main.py index 9e2f7e48..f3940cb4 100644 --- a/main.py +++ b/main.py @@ -33,8 +33,8 @@ async def on_ready(): @bot.command() @commands.guild_only() @commands.is_owner() -async def sync(ctx: Context, guilds: Greedy[discord.Object], botName): - if not guilds and botName == BOT_NAME: +async def sync(ctx: Context, guilds: Greedy[discord.Object], bot_name): + if not guilds and bot_name == BOT_NAME: print("Syncing command(s)...") synced = await bot.tree.sync() await ctx.send(f"Synced {len(synced)} command(s) globally!")