From ea5f95800b99efbf34b671e6a9ae67e418d6909e Mon Sep 17 00:00:00 2001 From: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Date: Sun, 15 Jan 2023 23:33:35 +0000 Subject: [PATCH] Format Python code with psf/black push --- cogs/commands.py | 25 ++++++----- cogs/image_service_cog.py | 11 ++--- cogs/moderations_service_cog.py | 44 +++++++++++-------- cogs/prompt_optimizer_cog.py | 13 +++--- cogs/text_service_cog.py | 78 ++++++++++++++++----------------- gpt3discord.py | 3 +- models/autocomplete_model.py | 21 +++++---- models/openai_model.py | 9 ++-- services/image_service.py | 4 +- services/moderations_service.py | 4 +- services/text_service.py | 14 +++--- 11 files changed, 118 insertions(+), 108 deletions(-) diff --git a/cogs/commands.py b/cogs/commands.py index fd6ddde..3099b73 100644 --- a/cogs/commands.py +++ b/cogs/commands.py @@ -9,7 +9,8 @@ ALLOWED_GUILDS = EnvService.get_allowed_guilds() class Commands(discord.Cog, name="Commands"): - '''Cog containing all slash and context commands as one-liners''' + """Cog containing all slash and context commands as one-liners""" + def __init__( self, bot, @@ -60,7 +61,7 @@ class Commands(discord.Cog, name="Commands"): ) # - #System commands + # System commands # @add_to_group("system") @@ -140,9 +141,9 @@ class Commands(discord.Cog, name="Commands"): async def delete_all_conversation_threads(self, ctx: discord.ApplicationContext): await self.converser_cog.delete_all_conversation_threads_command(ctx) - #""" - #Moderation commands - #""" + # """ + # Moderation commands + # """ @add_to_group("mod") @discord.slash_command( @@ -169,13 +170,13 @@ class Commands(discord.Cog, name="Commands"): name="status", description="Enable or disable the moderations service for the current guild (on/off)", required=True, - choices=["on", "off"] + choices=["on", "off"], ) @discord.option( name="alert_channel_id", description="The channel ID to send moderation alerts to", required=False, - autocomplete=Settings_autocompleter.get_value_alert_id_channel + autocomplete=Settings_autocompleter.get_value_alert_id_channel, ) @discord.guild_only() async def moderations( @@ -270,7 +271,7 @@ class Commands(discord.Cog, name="Commands"): ) # - #GPT commands + # GPT commands # @add_to_group("gpt") @@ -427,7 +428,7 @@ class Commands(discord.Cog, name="Commands"): await self.converser_cog.end_command(ctx) # - #DALLE commands + # DALLE commands # @add_to_group("dalle") @@ -454,7 +455,7 @@ class Commands(discord.Cog, name="Commands"): await self.image_service_cog.optimize_command(ctx, prompt) # - #Other commands + # Other commands # @discord.slash_command( @@ -483,7 +484,7 @@ class Commands(discord.Cog, name="Commands"): await self.converser_cog.setup_command(ctx) # - #Text-based context menu commands from here + # Text-based context menu commands from here # @discord.message_command( @@ -493,7 +494,7 @@ class Commands(discord.Cog, name="Commands"): await self.converser_cog.ask_gpt_action(ctx, message) # - #Image-based context menu commands from here + # Image-based context menu commands from here # @discord.message_command( diff --git a/cogs/image_service_cog.py b/cogs/image_service_cog.py index e030f55..6e432a1 100644 --- a/cogs/image_service_cog.py +++ b/cogs/image_service_cog.py @@ -21,7 +21,8 @@ if USER_INPUT_API_KEYS: class DrawDallEService(discord.Cog, name="DrawDallEService"): - '''Cog containing a draw commands and file management for saved images''' + """Cog containing a draw commands and file management for saved images""" + def __init__( self, bot, usage_service, model, message_queue, deletion_queue, converser_cog ): @@ -38,7 +39,7 @@ class DrawDallEService(discord.Cog, name="DrawDallEService"): async def draw_command( self, ctx: discord.ApplicationContext, prompt: str, from_action=False ): - '''With an ApplicationContext and prompt, send a dalle image to the invoked channel. Ephemeral if from an action''' + """With an ApplicationContext and prompt, send a dalle image to the invoked channel. Ephemeral if from an action""" user_api_key = None if USER_INPUT_API_KEYS: user_api_key = await TextService.get_user_api_key( @@ -70,11 +71,11 @@ class DrawDallEService(discord.Cog, name="DrawDallEService"): await ctx.send_followup(e, ephemeral=from_action) async def draw_action(self, ctx, message): - '''decoupler to handle context actions for the draw command''' + """decoupler to handle context actions for the draw command""" await self.draw_command(ctx, message.content, from_action=True) async def local_size_command(self, ctx: discord.ApplicationContext): - '''Get the folder size of the image folder''' + """Get the folder size of the image folder""" await ctx.defer() image_path = self.model.IMAGE_SAVE_PATH @@ -89,7 +90,7 @@ class DrawDallEService(discord.Cog, name="DrawDallEService"): await ctx.respond(f"The size of the local images folder is {total_size} MB.") async def clear_local_command(self, ctx): - '''Delete all local images''' + """Delete all local images""" await ctx.defer() image_path = self.model.IMAGE_SAVE_PATH diff --git a/cogs/moderations_service_cog.py b/cogs/moderations_service_cog.py index ad2750e..8b780b4 100644 --- a/cogs/moderations_service_cog.py +++ b/cogs/moderations_service_cog.py @@ -16,7 +16,8 @@ except Exception as e: class ModerationsService(discord.Cog, name="ModerationsService"): - '''Cog containing moderation tools and features''' + """Cog containing moderation tools and features""" + def __init__( self, bot, @@ -41,7 +42,7 @@ class ModerationsService(discord.Cog, name="ModerationsService"): @discord.Cog.listener() async def on_ready(self): - '''Check moderation service for each guild''' + """Check moderation service for each guild""" for guild in self.bot.guilds: self.get_or_set_warn_set(guild.id) self.get_or_set_delete_set(guild.id) @@ -49,20 +50,20 @@ class ModerationsService(discord.Cog, name="ModerationsService"): print("The moderation service is ready.") def check_guild_moderated(self, guild_id): - '''Given guild id, return bool of moderation status''' + """Given guild id, return bool of moderation status""" return guild_id in MOD_DB and MOD_DB[guild_id]["moderated"] def get_moderated_alert_channel(self, guild_id): - '''Given guild id, return alert channel''' + """Given guild id, return alert channel""" return MOD_DB[guild_id]["alert_channel"] def set_moderated_alert_channel(self, guild_id, channel_id): - '''Given guild id and channel id, set channel to recieve alerts''' + """Given guild id and channel id, set channel to recieve alerts""" MOD_DB[guild_id] = {"moderated": True, "alert_channel": channel_id} MOD_DB.commit() def get_or_set_warn_set(self, guild_id): - '''Get warn_set set for the guild, if not set them from default values''' + """Get warn_set set for the guild, if not set them from default values""" guild_id = str(guild_id) key = guild_id + "_warn_set" if key not in MOD_DB: @@ -73,7 +74,7 @@ class ModerationsService(discord.Cog, name="ModerationsService"): return dict(MOD_DB[key]) def get_or_set_delete_set(self, guild_id): - '''Get delete_set set for the guild, if not set them from default values''' + """Get delete_set set for the guild, if not set them from default values""" guild_id = str(guild_id) key = guild_id + "_delete_set" if key not in MOD_DB: @@ -84,21 +85,21 @@ class ModerationsService(discord.Cog, name="ModerationsService"): return dict(MOD_DB[key]) def set_warn_set(self, guild_id, threshold_set): - '''Set threshold for warning a message''' + """Set threshold for warning a message""" guild_id = str(guild_id) key = guild_id + "_warn_set" MOD_DB[key] = zip(threshold_set.keys, threshold_set.thresholds) MOD_DB.commit() def set_delete_set(self, guild_id, threshold_set): - '''Set threshold for deleting a message''' + """Set threshold for deleting a message""" guild_id = str(guild_id) key = guild_id + "_delete_set" MOD_DB[key] = zip(threshold_set.keys, threshold_set.thresholds) MOD_DB.commit() def set_guild_moderated(self, guild_id, status=True): - '''Set the guild to moderated or not''' + """Set the guild to moderated or not""" if guild_id not in MOD_DB: MOD_DB[guild_id] = {"moderated": status, "alert_channel": 0} MOD_DB.commit() @@ -110,7 +111,7 @@ class ModerationsService(discord.Cog, name="ModerationsService"): MOD_DB.commit() async def check_and_launch_moderations(self, guild_id, alert_channel_override=None): - '''Create the moderation service''' + """Create the moderation service""" print("Checking and attempting to launch moderations service...") if self.check_guild_moderated(guild_id): Moderation.moderation_queues[guild_id] = asyncio.Queue() @@ -144,7 +145,7 @@ class ModerationsService(discord.Cog, name="ModerationsService"): async def moderations_command( self, ctx: discord.ApplicationContext, status: str, alert_channel_id: str ): - '''command handler for toggling moderation and setting an alert channel''' + """command handler for toggling moderation and setting an alert channel""" await ctx.defer() try: @@ -175,7 +176,7 @@ class ModerationsService(discord.Cog, name="ModerationsService"): ) async def stop_moderations_service(self, guild_id): - '''Remove guild moderation status and stop the service''' + """Remove guild moderation status and stop the service""" self.set_guild_moderated(guild_id, False) Moderation.moderation_tasks[guild_id].cancel() Moderation.moderation_tasks[guild_id] = None @@ -183,7 +184,7 @@ class ModerationsService(discord.Cog, name="ModerationsService"): Moderation.moderations_launched.remove(guild_id) async def start_moderations_service(self, guild_id, alert_channel_id=None): - '''Set guild moderation and start the service''' + """Set guild moderation and start the service""" self.set_guild_moderated(guild_id) moderations_channel = await self.check_and_launch_moderations( guild_id, @@ -194,9 +195,13 @@ class ModerationsService(discord.Cog, name="ModerationsService"): self.set_moderated_alert_channel(guild_id, moderations_channel.id) async def restart_moderations_service(self, ctx): - '''restarts the moderation of the guild it's run in''' + """restarts the moderation of the guild it's run in""" if not self.check_guild_moderated(ctx.guild_id): - await ctx.respond("Moderations are not enabled, can't restart", ephemeral=True, delete_after=30) + await ctx.respond( + "Moderations are not enabled, can't restart", + ephemeral=True, + delete_after=30, + ) return await ctx.respond( @@ -221,7 +226,8 @@ class ModerationsService(discord.Cog, name="ModerationsService"): embed = discord.Embed( title="Moderation Settings", - description="The moderation settings for this guild for the type: " + category, + description="The moderation settings for this guild for the type: " + + category, color=discord.Color.yellow() if type == "warn" else discord.Color.red(), ) @@ -243,7 +249,7 @@ class ModerationsService(discord.Cog, name="ModerationsService"): violence, violence_graphic, ): - '''command handler for assigning threshold values for warn or delete''' + """command handler for assigning threshold values for warn or delete""" all_args = [ hate, hate_threatening, @@ -306,7 +312,7 @@ class ModerationsService(discord.Cog, name="ModerationsService"): async def moderations_test_command( self, ctx: discord.ApplicationContext, prompt: str ): - '''command handler for checking moderation values of a given input''' + """command handler for checking moderation values of a given input""" await ctx.defer() response = await self.model.send_moderations_request(prompt) await ctx.respond(response["results"][0]["category_scores"]) diff --git a/cogs/prompt_optimizer_cog.py b/cogs/prompt_optimizer_cog.py index 6adf6ae..6392a48 100644 --- a/cogs/prompt_optimizer_cog.py +++ b/cogs/prompt_optimizer_cog.py @@ -18,7 +18,8 @@ if USER_INPUT_API_KEYS: class ImgPromptOptimizer(discord.Cog, name="ImgPromptOptimizer"): - '''cog containing the optimizer command''' + """cog containing the optimizer command""" + _OPTIMIZER_PRETEXT = "Optimize the following text for DALL-E image generation to have the most detailed and realistic image possible. Prompt:" def __init__( @@ -55,10 +56,12 @@ class ImgPromptOptimizer(discord.Cog, name="ImgPromptOptimizer"): self.OPTIMIZER_PRETEXT = self._OPTIMIZER_PRETEXT async def optimize_command(self, ctx: discord.ApplicationContext, prompt: str): - '''Command handler. Given a string it generates an output that's fitting for image generation''' + """Command handler. Given a string it generates an output that's fitting for image generation""" user_api_key = None if USER_INPUT_API_KEYS: - user_api_key = await TextService.get_user_api_key(ctx.user.id, ctx, USER_KEY_DB) + user_api_key = await TextService.get_user_api_key( + ctx.user.id, ctx, USER_KEY_DB + ) if not user_api_key: return @@ -75,7 +78,7 @@ class ImgPromptOptimizer(discord.Cog, name="ImgPromptOptimizer"): final_prompt += "." # Get the token amount for the prompt - #tokens = self.usage_service.count_tokens(final_prompt) + # tokens = self.usage_service.count_tokens(final_prompt) try: response = await self.model.send_request( @@ -253,7 +256,7 @@ class RedoButton(discord.ui.Button["OptimizeView"]): ].in_interaction(interaction_id): # Get the message and the prompt and call encapsulated_send ctx = self.converser_cog.redo_users[user_id].ctx - #message = self.converser_cog.redo_users[user_id].message + # message = self.converser_cog.redo_users[user_id].message prompt = self.converser_cog.redo_users[user_id].prompt response_message = self.converser_cog.redo_users[user_id].response await interaction.response.send_message( diff --git a/cogs/text_service_cog.py b/cogs/text_service_cog.py index f0219c6..4a77585 100644 --- a/cogs/text_service_cog.py +++ b/cogs/text_service_cog.py @@ -27,7 +27,7 @@ else: separator = "/" # -#Get the user key service if it is enabled. +# Get the user key service if it is enabled. # USER_INPUT_API_KEYS = EnvService.get_user_input_api_keys() USER_KEY_DB = None @@ -53,8 +53,8 @@ if USER_INPUT_API_KEYS: # -#Obtain the Moderation table and the General table, these are two SQLite tables that contain -#information about the server that are used for persistence and to auto-restart the moderation service. +# Obtain the Moderation table and the General table, these are two SQLite tables that contain +# information about the server that are used for persistence and to auto-restart the moderation service. # MOD_DB = None GENERAL_DB = None @@ -156,7 +156,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): self.conversation_thread_owners = {} async def load_file(self, file, ctx): - '''Take filepath, return content or respond if not found''' + """Take filepath, return content or respond if not found""" try: async with aiofiles.open(file, "r") as f: return await f.read() @@ -169,7 +169,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): @discord.Cog.listener() async def on_member_join(self, member): - '''When members join send welcome message if enabled''' + """When members join send welcome message if enabled""" if self.model.welcome_message_enabled: query = f"Please generate a welcome message for {member.name} who has just joined the server." @@ -195,7 +195,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): @discord.Cog.listener() async def on_ready(self): - '''When ready to recieve data set debug channel and sync commands''' + """When ready to recieve data set debug channel and sync commands""" self.debug_channel = self.bot.get_guild(self.DEBUG_GUILD).get_channel( self.DEBUG_CHANNEL ) @@ -227,7 +227,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): async def end_conversation( self, ctx, opener_user_id=None, conversation_limit=False ): - '''end the thread of the user interacting with the bot, if the conversation has reached the limit close it for the owner''' + """end the thread of the user interacting with the bot, if the conversation has reached the limit close it for the owner""" normalized_user_id = opener_user_id if opener_user_id else ctx.author.id if ( conversation_limit @@ -296,7 +296,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): traceback.print_exc() async def send_settings_text(self, ctx): - '''compose and return the settings menu to the interacting user''' + """compose and return the settings menu to the interacting user""" embed = discord.Embed( title="GPT3Bot Settings", description="The current settings of the model", @@ -328,7 +328,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): await ctx.respond(embed=embed, ephemeral=True) async def process_settings(self, ctx, parameter, value): - '''Given a parameter and value set the corresponding parameter in storage to the value''' + """Given a parameter and value set the corresponding parameter in storage to the value""" # Check if the parameter is a valid parameter if hasattr(self.model, parameter): @@ -355,14 +355,14 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): await ctx.respond("The parameter is not a valid parameter") def generate_debug_message(self, prompt, response): - '''create a debug message with a prompt and a response field''' + """create a debug message with a prompt and a response field""" debug_message = "----------------------------------------------------------------------------------\n" debug_message += "Prompt:\n```\n" + prompt + "\n```\n" debug_message += "Response:\n```\n" + json.dumps(response, indent=4) + "\n```\n" return debug_message async def paginate_and_send(self, response_text, ctx): - '''paginate a response to a text cutoff length and send it in chunks''' + """paginate a response to a text cutoff length and send it in chunks""" from_context = isinstance(ctx, discord.ApplicationContext) response_text = [ @@ -385,7 +385,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): await ctx.channel.send(chunk) async def paginate_embed(self, response_text, codex, prompt=None, instruction=None): - '''Given a response text make embed pages and return a list of the pages. Codex makes it a codeblock in the embed''' + """Given a response text make embed pages and return a list of the pages. Codex makes it a codeblock in the embed""" if codex: # clean codex input response_text = response_text.replace("```", "") response_text = response_text.replace(f"***Prompt: {prompt}***\n", "") @@ -419,11 +419,11 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): return pages async def queue_debug_message(self, debug_message, debug_channel): - '''Put a message into the debug queue''' + """Put a message into the debug queue""" await self.message_queue.put(Message(debug_message, debug_channel)) async def queue_debug_chunks(self, debug_message, debug_channel): - '''Put a message as chunks into the debug queue''' + """Put a message as chunks into the debug queue""" debug_message_chunks = [ debug_message[i : i + self.TEXT_CUTOFF] for i in range(0, len(debug_message), self.TEXT_CUTOFF) @@ -450,7 +450,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): await self.message_queue.put(Message(chunk, debug_channel)) async def send_debug_message(self, debug_message, debug_channel): - '''process a debug message and put directly into queue or chunk it''' + """process a debug message and put directly into queue or chunk it""" # Send the debug message try: if len(debug_message) > self.TEXT_CUTOFF: @@ -464,7 +464,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): ) async def check_conversation_limit(self, message): - '''Check if a conversation has reached the set limit and end it if it has''' + """Check if a conversation has reached the set limit and end it if it has""" # After each response, check if the user has reached the conversation limit in terms of messages or time. if message.channel.id in self.conversation_threads: # If the user has reached the max conversation length, end the conversation @@ -478,7 +478,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): await self.end_conversation(message, conversation_limit=True) async def summarize_conversation(self, message, prompt): - '''Takes a conversation history filled prompt and summarizes it to then start a new history with it as the base''' + """Takes a conversation history filled prompt and summarizes it to then start a new history with it as the base""" response = await self.model.send_summary_request(prompt) summarized_text = response["choices"][0]["text"] @@ -510,7 +510,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): # A listener for message edits to redo prompts if they are edited @discord.Cog.listener() async def on_message_edit(self, before, after): - '''When a message is edited run moderation if enabled, and process if it a prompt that should be redone''' + """When a message is edited run moderation if enabled, and process if it a prompt that should be redone""" if after.author.id == self.bot.user.id: return @@ -533,7 +533,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): @discord.Cog.listener() async def on_message(self, message): - '''On a new message check if it should be moderated then process it for conversation''' + """On a new message check if it should be moderated then process it for conversation""" if message.author == self.bot.user: return @@ -558,7 +558,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): original_message[message.author.id] = message.id def cleanse_response(self, response_text): - '''Cleans history tokens from response''' + """Cleans history tokens from response""" response_text = response_text.replace("GPTie:\n", "") response_text = response_text.replace("GPTie:", "") response_text = response_text.replace("GPTie: ", "") @@ -568,7 +568,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): def remove_awaiting( self, author_id, channel_id, from_ask_command, from_edit_command ): - '''Remove user from ask/edit command response wait, if not any of those then process the id to remove user from thread response wait''' + """Remove user from ask/edit command response wait, if not any of those then process the id to remove user from thread response wait""" if author_id in self.awaiting_responses: self.awaiting_responses.remove(author_id) if not from_ask_command and not from_edit_command: @@ -576,14 +576,12 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): self.awaiting_thread_responses.remove(channel_id) async def mention_to_username(self, ctx, message): - '''replaces discord mentions with their server nickname in text, if the user is not found keep the mention as is''' + """replaces discord mentions with their server nickname in text, if the user is not found keep the mention as is""" if not discord.utils.raw_mentions(message): return message for mention in discord.utils.raw_mentions(message): try: - user = await discord.utils.get_or_fetch( - ctx.guild, "member", mention - ) + user = await discord.utils.get_or_fetch(ctx.guild, "member", mention) message = message.replace(f"<@{str(mention)}>", user.display_name) except Exception: pass @@ -592,7 +590,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): # COMMANDS async def help_command(self, ctx): - '''Command handler. Generates a help message and sends it to the user''' + """Command handler. Generates a help message and sends it to the user""" await ctx.defer() embed = discord.Embed( title="GPT3Bot Help", description="The current commands", color=0xC730C7 @@ -647,7 +645,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): async def set_usage_command( self, ctx: discord.ApplicationContext, usage_amount: float ): - '''Command handler. Sets the usage file to the given value''' + """Command handler. Sets the usage file to the given value""" await ctx.defer() # Attempt to convert the input usage value into a float @@ -662,7 +660,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): async def delete_all_conversation_threads_command( self, ctx: discord.ApplicationContext ): - '''Command handler. Deletes all threads made by the bot in the current guild''' + """Command handler. Deletes all threads made by the bot in the current guild""" await ctx.defer() for thread in ctx.guild.threads: @@ -675,7 +673,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): await ctx.respond("All conversation threads in this server have been deleted.") async def usage_command(self, ctx): - '''Command handler. Responds with the current usage of the bot''' + """Command handler. Responds with the current usage of the bot""" await ctx.defer() embed = discord.Embed( title="GPT3Bot Usage", description="The current usage", color=0x00FF00 @@ -713,7 +711,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): frequency_penalty (float): Sets the frequency penalty override presence_penalty (float): Sets the presence penalty override from_action (bool, optional): Enables ephemeral. Defaults to None. - """ + """ user = ctx.user prompt = await self.mention_to_username(ctx, prompt.strip()) @@ -757,7 +755,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): temperature (float): Sets the temperature override top_p (float): Sets the top p override codex (bool): Enables the codex edit model - """ + """ user = ctx.user text = await self.mention_to_username(ctx, text.strip()) @@ -785,7 +783,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): ) async def private_test_command(self, ctx: discord.ApplicationContext): - '''Command handler. Creates a private thread in the current channel''' + """Command handler. Creates a private thread in the current channel""" await ctx.defer(ephemeral=True) await ctx.respond("Your private test thread") thread = await ctx.channel.create_thread( @@ -812,7 +810,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): opener_file (str): A .txt or .json file which is appended before the opener private (bool): If the thread should be private minimal (bool): If a minimal starter should be used - """ + """ user = ctx.user @@ -967,7 +965,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): self.awaiting_thread_responses.remove(thread.id) async def end_command(self, ctx: discord.ApplicationContext): - '''Command handler. Gets the user's thread and ends it''' + """Command handler. Gets the user's thread and ends it""" await ctx.defer(ephemeral=True) user_id = ctx.user.id try: @@ -989,7 +987,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): ) async def setup_command(self, ctx: discord.ApplicationContext): - '''Command handler. Opens the setup modal''' + """Command handler. Opens the setup modal""" if not USER_INPUT_API_KEYS: await ctx.respond( "This server doesn't support user input API keys.", @@ -1003,7 +1001,7 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): async def settings_command( self, ctx: discord.ApplicationContext, parameter: str = None, value: str = None ): - '''Command handler. Returns current settings or sets new values''' + """Command handler. Returns current settings or sets new values""" await ctx.defer() if parameter is None and value is None: await self.send_settings_text(ctx) @@ -1025,13 +1023,11 @@ class GPT3ComCon(discord.Cog, name="GPT3ComCon"): await self.process_settings(ctx, parameter, value) # - #Text-based context menu commands from here + # Text-based context menu commands from here # - async def ask_gpt_action( - self, ctx, message: discord.Message - ): - '''Message command. Return the message''' + async def ask_gpt_action(self, ctx, message: discord.Message): + """Message command. Return the message""" await self.ask_command( ctx, message.content, None, None, None, None, from_action=message.content ) diff --git a/gpt3discord.py b/gpt3discord.py index dcda0d7..4c36c48 100644 --- a/gpt3discord.py +++ b/gpt3discord.py @@ -67,7 +67,7 @@ asyncio.ensure_future(Deletion.process_deletion_queue(deletion_queue, 1, 1)) # -#Settings for the bot +# Settings for the bot # activity = discord.Activity( type=discord.ActivityType.watching, name="for /help /gpt, and more!" @@ -81,6 +81,7 @@ model = Model(usage_service) # An encapsulating wrapper for the discord.py client. This uses the old re-write without cogs, but it gets the job done! # + @bot.event # Using self gives u async def on_ready(): # I can make self optional by print("We have logged in as {0.user}".format(bot)) diff --git a/models/autocomplete_model.py b/models/autocomplete_model.py index 7898f9c..63d14a3 100644 --- a/models/autocomplete_model.py +++ b/models/autocomplete_model.py @@ -12,9 +12,10 @@ model = Model(usage_service) class Settings_autocompleter: - '''autocompleter for the settings command''' + """autocompleter for the settings command""" + async def get_settings(ctx: discord.AutocompleteContext): - '''get settings for the settings option''' + """get settings for the settings option""" SETTINGS = [ re.sub("^_", "", key) for key in model.__dict__.keys() @@ -29,7 +30,7 @@ class Settings_autocompleter: async def get_value( ctx: discord.AutocompleteContext, ): # Behaves a bit weird if you go back and edit the parameter without typing in a new command - '''gets valid values for the value option''' + """gets valid values for the value option""" values = { "max_conversation_length": [str(num) for num in range(1, 500, 2)], "num_images": [str(num) for num in range(1, 4 + 1)], @@ -57,16 +58,14 @@ class Settings_autocompleter: async def get_value_moderations( ctx: discord.AutocompleteContext, ): # Behaves a bit weird if you go back and edit the parameter without typing in a new command - '''gets valid values for the type option''' + """gets valid values for the type option""" print(f"The value is {ctx.value}") return [ - value - for value in ["warn", "delete"] - if value.startswith(ctx.value.lower()) + value for value in ["warn", "delete"] if value.startswith(ctx.value.lower()) ] async def get_value_alert_id_channel(self, ctx: discord.AutocompleteContext): - '''gets valid values for the channel option''' + """gets valid values for the channel option""" return [ channel.name for channel in ctx.interaction.guild.channels @@ -74,11 +73,11 @@ class Settings_autocompleter: ] - class File_autocompleter: - '''Autocompleter for the opener command''' + """Autocompleter for the opener command""" + async def get_openers(ctx: discord.AutocompleteContext): - '''get all files in the openers folder''' + """get all files in the openers folder""" try: return [ file diff --git a/models/openai_model.py b/models/openai_model.py index 31c4628..e2b0f2c 100644 --- a/models/openai_model.py +++ b/models/openai_model.py @@ -42,9 +42,11 @@ class Model: self._temp = 0.8 # Higher value means more random, lower value means more likely to be a coherent sentence self._top_p = 0.95 # 1 is equivalent to greedy sampling, 0.1 means that the model will only consider the top 10% of the probability distribution self._max_tokens = 4000 # The maximum number of tokens the model can generate - self._presence_penalty = 0 # Penalize new tokens based on whether they appear in the text so far + self._presence_penalty = ( + 0 # Penalize new tokens based on whether they appear in the text so far + ) # Penalize new tokens based on their existing frequency in the text so far. (Higher frequency = lower probability of being chosen.) - self._frequency_penalty = 0 + self._frequency_penalty = 0 self._best_of = 1 # Number of responses to compare the loglikelihoods of self._prompt_min_length = 8 self._max_conversation_length = 100 @@ -669,7 +671,8 @@ class Model: images = await asyncio.get_running_loop().run_in_executor( None, lambda: [ - Image.open(requests.get(url, stream=True, timeout=10).raw) for url in image_urls + Image.open(requests.get(url, stream=True, timeout=10).raw) + for url in image_urls ], ) diff --git a/services/image_service.py b/services/image_service.py index 9e66ce8..662446b 100644 --- a/services/image_service.py +++ b/services/image_service.py @@ -36,7 +36,7 @@ class ImageService: vary (bool, optional): If the image is a variation of another one. Defaults to None. draw_from_optimizer (bool, optional): If the prompt is passed from the optimizer command. Defaults to None. custom_api_key (str, optional): User defined OpenAI API key. Defaults to None. - """ + """ await asyncio.sleep(0) # send the prompt to the model from_context = isinstance(ctx, discord.ApplicationContext) @@ -84,7 +84,7 @@ class ImageService: embed.set_image(url=f"attachment://{file.filename}") if not response_message: # Original generation case - # Start an interaction with the user, we also want to send data embed=embed, file=file, + # Start an interaction with the user, we also want to send data embed=embed, file=file, # view=SaveView(image_urls, image_service_cog, image_service_cog.converser_cog) result_message = ( await ctx.channel.send( diff --git a/services/moderations_service.py b/services/moderations_service.py index 83061da..d891f3f 100644 --- a/services/moderations_service.py +++ b/services/moderations_service.py @@ -32,7 +32,7 @@ class ThresholdSet: sm_t (float): sexual/minors v_t (float): violence vg_t (float): violence/graphic - """ + """ self.keys = [ "hate", "hate/threatening", @@ -55,7 +55,7 @@ class ThresholdSet: # The string representation is just the keys alongside the threshold values def __str__(self): - '''"key": value format''' + """ "key": value format""" # "key": value format return ", ".join([f"{k}: {v}" for k, v in zip(self.keys, self.thresholds)]) diff --git a/services/text_service.py b/services/text_service.py index ef0a8fb..43829d5 100644 --- a/services/text_service.py +++ b/services/text_service.py @@ -57,7 +57,7 @@ class TextService: edited_request (bool, optional): If we're doing an edited message. Defaults to False. redo_request (bool, optional): If we're redoing a previous prompt. Defaults to False. from_action (bool, optional): If the function is being called from a message action. Defaults to False. - """ + """ new_prompt = ( prompt + "\nGPTie: " if not from_ask_command and not from_edit_command @@ -367,7 +367,9 @@ class TextService: custom_api_key=custom_api_key, ) paginator = pages.Paginator( - pages=embed_pages, timeout=None, custom_view=view, + pages=embed_pages, + timeout=None, + custom_view=view, author_check=True, ) response_message = await paginator.respond(ctx.interaction) @@ -514,9 +516,7 @@ class TextService: converser_cog, message, USER_INPUT_API_KEYS, USER_KEY_DB ): content = message.content.strip() - conversing = converser_cog.check_conversing( - message.channel.id, content - ) + conversing = converser_cog.check_conversing(message.channel.id, content) # If the user is conversing and they want to end it, end it immediately before we continue any further. if conversing and message.content.lower() in converser_cog.END_PROMPTS: @@ -701,7 +701,7 @@ class TextService: # -#Conversation interaction buttons +# Conversation interaction buttons # @@ -840,7 +840,7 @@ class RedoButton(discord.ui.Button["ConversationView"]): # -#The setup modal when using user input API keys +# The setup modal when using user input API keys #