From 4fb0acb7f1b2f67d050a87cface4257b3596e406 Mon Sep 17 00:00:00 2001 From: Vivaan Verma Date: Mon, 19 Jul 2021 14:30:48 +0100 Subject: Lay out purge command and cog structure --- arthur/exts/cloudflare/zones.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 arthur/exts/cloudflare/zones.py (limited to 'arthur/exts/cloudflare/zones.py') diff --git a/arthur/exts/cloudflare/zones.py b/arthur/exts/cloudflare/zones.py new file mode 100644 index 0000000..64cd5f3 --- /dev/null +++ b/arthur/exts/cloudflare/zones.py @@ -0,0 +1,19 @@ +"""The zones cog helps with managing Cloudflare zones""" +from discord.ext import commands + +from arthur.apis.cloudflare import zones +from arthur.bot import KingArthur + +class Zones(commands.Cog): + + def __init__(self, bot: KingArthur) -> None: + self.bot = bot + + @commands.group(name="zones", invoke_without_command=True) + async def zones(self, ctx: commands.Context) -> None: + "Commands for working with Cloudflare zones" + await ctx.send_help(ctx.command) + + @zones.command(name="purge") + async def purge(self, ctx: commands.Context, zone_name: str = "pythondiscord.com"): + pass \ No newline at end of file -- cgit v1.2.3 From 3189e6921bfd20a05b137d2cdc8e048225e44de8 Mon Sep 17 00:00:00 2001 From: Vivaan Verma Date: Mon, 19 Jul 2021 15:46:37 +0100 Subject: Finished the CF cache purge command --- arthur/apis/cloudflare/zones.py | 33 +++++++++++++++++++++++++++++---- arthur/config.py | 3 +++ arthur/exts/cloudflare/zones.py | 28 ++++++++++++++++++++++++++-- 3 files changed, 58 insertions(+), 6 deletions(-) (limited to 'arthur/exts/cloudflare/zones.py') diff --git a/arthur/apis/cloudflare/zones.py b/arthur/apis/cloudflare/zones.py index 48714a6..93c29d1 100644 --- a/arthur/apis/cloudflare/zones.py +++ b/arthur/apis/cloudflare/zones.py @@ -1,10 +1,36 @@ +from typing import Optional + import aiohttp -async def purge_zone(zone_identifier: str, api_token: str) -> dict: +from arthur.config import CONFIG + + +CF_TOKEN = CONFIG.cloudflare_token + +async def list_zones(zone_name: Optional[str] = None) -> dict[str, str]: + + endpoint = f"https://api.cloudflare.com/client/v4/zones" + request_headers = { + "X-Auth-User-Service-Key": CF_TOKEN + } + + if zone_name is not None: + endpoint += f"?name={zone_name}" + + async with aiohttp.ClientSession() as session: + async with session.post(endpoint, headers=request_headers) as response: + info = await response.json() + + zones = info["result"] + + return {zone.name: zone.id for zone in zones} + + +async def purge_zone(zone_identifier: str) -> dict: endpoint = f"https://api.cloudflare.com/client/v4/zones/{zone_identifier}/purge_cache?purge_everything=true" request_headers = { - "X-Auth-User-Service-Key": api_token + "X-Auth-User-Service-Key": CF_TOKEN } async with aiohttp.ClientSession() as session: @@ -13,7 +39,6 @@ async def purge_zone(zone_identifier: str, api_token: str) -> dict: return { "success": info["success"], - "errors": info["errors"], - "messages": info["messages"] + "errors": info["errors"] } diff --git a/arthur/config.py b/arthur/config.py index 982aa68..03eab03 100644 --- a/arthur/config.py +++ b/arthur/config.py @@ -14,6 +14,9 @@ class Config(BaseSettings): # Authorised role ID for usage devops_role: int = 409416496733880320 + # Token for authorising with the Cloudflare API + cloudflare_token: str + class Config: # noqa: D106 env_file = ".env" env_prefix = "KING_ARTHUR_" diff --git a/arthur/exts/cloudflare/zones.py b/arthur/exts/cloudflare/zones.py index 64cd5f3..20169bc 100644 --- a/arthur/exts/cloudflare/zones.py +++ b/arthur/exts/cloudflare/zones.py @@ -1,4 +1,6 @@ """The zones cog helps with managing Cloudflare zones""" +from typing import Optional + from discord.ext import commands from arthur.apis.cloudflare import zones @@ -15,5 +17,27 @@ class Zones(commands.Cog): await ctx.send_help(ctx.command) @zones.command(name="purge") - async def purge(self, ctx: commands.Context, zone_name: str = "pythondiscord.com"): - pass \ No newline at end of file + async def purge(self, ctx: commands.Context, zone_name: Optional[str] = "pythondiscord.com"): + """Command to clear the Cloudflare cache of the specified zone""" + pydis_zones = await zones.list_zones(zone_name) + required_id = pydis_zones[zone_name] + purge_attempt_response = await zones.purge_zone(required_id) + + message = "__Cloudflare cache purge status__\n" + + if purge_attempt_response["success"]: + message += "Purge status: **Successful** :white_check_mark:\n" + message += f"Zone purged: **Zone purged: `{zone_name}`" + return await ctx.send(message) + else: + message += "Purge status: **Failed** :x:\n" + if errors := purge_attempt_response["errors"]: + message += "__Errors:__\n" + for error in errors: + message += f"**Code**: `{error.code}`\n" + message += f"**Message**: {error.message}\n" + return await ctx.send(message) + +def setup(bot: KingArthur) -> None: + """Add the extension to the bot.""" + bot.add_cog(Zones(bot)) \ No newline at end of file -- cgit v1.2.3 From d8fbfffebfac31604c7b6fcf9b5b96a8e945791b Mon Sep 17 00:00:00 2001 From: Vivaan Verma Date: Mon, 19 Jul 2021 15:49:41 +0100 Subject: Lint all code with black --- arthur/apis/cloudflare/zones.py | 15 ++++----------- arthur/exts/cloudflare/zones.py | 5 +++-- arthur/exts/error_handler/error_handler.py | 3 +-- arthur/exts/kubernetes/deployments.py | 4 ++-- 4 files changed, 10 insertions(+), 17 deletions(-) (limited to 'arthur/exts/cloudflare/zones.py') diff --git a/arthur/apis/cloudflare/zones.py b/arthur/apis/cloudflare/zones.py index 93c29d1..e2955f7 100644 --- a/arthur/apis/cloudflare/zones.py +++ b/arthur/apis/cloudflare/zones.py @@ -7,12 +7,11 @@ from arthur.config import CONFIG CF_TOKEN = CONFIG.cloudflare_token + async def list_zones(zone_name: Optional[str] = None) -> dict[str, str]: endpoint = f"https://api.cloudflare.com/client/v4/zones" - request_headers = { - "X-Auth-User-Service-Key": CF_TOKEN - } + request_headers = {"X-Auth-User-Service-Key": CF_TOKEN} if zone_name is not None: endpoint += f"?name={zone_name}" @@ -29,16 +28,10 @@ async def list_zones(zone_name: Optional[str] = None) -> dict[str, str]: async def purge_zone(zone_identifier: str) -> dict: endpoint = f"https://api.cloudflare.com/client/v4/zones/{zone_identifier}/purge_cache?purge_everything=true" - request_headers = { - "X-Auth-User-Service-Key": CF_TOKEN - } + request_headers = {"X-Auth-User-Service-Key": CF_TOKEN} async with aiohttp.ClientSession() as session: async with session.post(endpoint, headers=request_headers) as response: info = await response.json() - - return { - "success": info["success"], - "errors": info["errors"] - } + return {"success": info["success"], "errors": info["errors"]} diff --git a/arthur/exts/cloudflare/zones.py b/arthur/exts/cloudflare/zones.py index 20169bc..3b8b3b7 100644 --- a/arthur/exts/cloudflare/zones.py +++ b/arthur/exts/cloudflare/zones.py @@ -6,8 +6,8 @@ from discord.ext import commands from arthur.apis.cloudflare import zones from arthur.bot import KingArthur -class Zones(commands.Cog): +class Zones(commands.Cog): def __init__(self, bot: KingArthur) -> None: self.bot = bot @@ -38,6 +38,7 @@ class Zones(commands.Cog): message += f"**Message**: {error.message}\n" return await ctx.send(message) + def setup(bot: KingArthur) -> None: """Add the extension to the bot.""" - bot.add_cog(Zones(bot)) \ No newline at end of file + bot.add_cog(Zones(bot)) diff --git a/arthur/exts/error_handler/error_handler.py b/arthur/exts/error_handler/error_handler.py index 2a61f40..673fbc7 100644 --- a/arthur/exts/error_handler/error_handler.py +++ b/arthur/exts/error_handler/error_handler.py @@ -49,8 +49,7 @@ class ErrorHandler(Cog): await ctx.send( generate_error_message( description=( - f"Unknown exception occurred: `{error.__class__.__name__}:" - f" {error}`" + f"Unknown exception occurred: `{error.__class__.__name__}:" f" {error}`" ) ) ) diff --git a/arthur/exts/kubernetes/deployments.py b/arthur/exts/kubernetes/deployments.py index dccf676..dc1284f 100644 --- a/arthur/exts/kubernetes/deployments.py +++ b/arthur/exts/kubernetes/deployments.py @@ -134,14 +134,14 @@ class Deployments(commands.Cog): content=generate_error_message( description="Could not find deployment, check the namespace.", ), - ephemeral=False + ephemeral=False, ) return await interaction.respond( content=generate_error_message( description=f"Unexpected error occurred, error code {e.status}" ), - ephemeral=False + ephemeral=False, ) else: description = ( -- cgit v1.2.3 From c2139527c79f2bd4ab7c1e8819e1270252d3616a Mon Sep 17 00:00:00 2001 From: Vivaan Verma Date: Mon, 19 Jul 2021 16:06:04 +0100 Subject: Fix linting again --- arthur/apis/cloudflare/zones.py | 6 +++--- arthur/exts/cloudflare/zones.py | 12 ++++++++---- 2 files changed, 11 insertions(+), 7 deletions(-) (limited to 'arthur/exts/cloudflare/zones.py') diff --git a/arthur/apis/cloudflare/zones.py b/arthur/apis/cloudflare/zones.py index a5a81d8..9098d99 100644 --- a/arthur/apis/cloudflare/zones.py +++ b/arthur/apis/cloudflare/zones.py @@ -1,15 +1,15 @@ +"""APIs for managing Cloudflare zones.""" from typing import Optional import aiohttp from arthur.config import CONFIG - CF_TOKEN = CONFIG.cloudflare_token async def list_zones(zone_name: Optional[str] = None) -> dict[str, str]: - + """List all Cloudflare zones.""" endpoint = "https://api.cloudflare.com/client/v4/zones" request_headers = {"X-Auth-User-Service-Key": CF_TOKEN} @@ -26,7 +26,7 @@ async def list_zones(zone_name: Optional[str] = None) -> dict[str, str]: async def purge_zone(zone_identifier: str) -> dict: - + """Purge the cache for a Cloudflare zone.""" endpoint = f"https://api.cloudflare.com/client/v4/zones/{zone_identifier}/purge_cache?purge_everything=true" # noqa: E501 request_headers = {"X-Auth-User-Service-Key": CF_TOKEN} diff --git a/arthur/exts/cloudflare/zones.py b/arthur/exts/cloudflare/zones.py index 3b8b3b7..c6e625f 100644 --- a/arthur/exts/cloudflare/zones.py +++ b/arthur/exts/cloudflare/zones.py @@ -1,4 +1,4 @@ -"""The zones cog helps with managing Cloudflare zones""" +"""The zones cog helps with managing Cloudflare zones.""" from typing import Optional from discord.ext import commands @@ -8,17 +8,21 @@ from arthur.bot import KingArthur class Zones(commands.Cog): + """Commands for working with Cloudflare zones.""" + def __init__(self, bot: KingArthur) -> None: self.bot = bot @commands.group(name="zones", invoke_without_command=True) async def zones(self, ctx: commands.Context) -> None: - "Commands for working with Cloudflare zones" + """Commands for working with Cloudflare zones.""" await ctx.send_help(ctx.command) @zones.command(name="purge") - async def purge(self, ctx: commands.Context, zone_name: Optional[str] = "pythondiscord.com"): - """Command to clear the Cloudflare cache of the specified zone""" + async def purge(self, ctx: commands.Context, + zone_name: Optional[str] = "pythondiscord.com" + ) -> None: + """Command to clear the Cloudflare cache of the specified zone.""" pydis_zones = await zones.list_zones(zone_name) required_id = pydis_zones[zone_name] purge_attempt_response = await zones.purge_zone(required_id) -- cgit v1.2.3 From 03924ead228cfcc318f38a4e89ff14d75a71ba22 Mon Sep 17 00:00:00 2001 From: Vivaan Verma Date: Thu, 22 Jul 2021 12:01:49 +0100 Subject: Fix and refactor Reflected on feedback provided by @jb3 including: - Change auth method - Move POST request data from params to body --- arthur/apis/cloudflare/zones.py | 18 +++++++++++------- arthur/exts/cloudflare/zones.py | 11 +++++------ 2 files changed, 16 insertions(+), 13 deletions(-) (limited to 'arthur/exts/cloudflare/zones.py') diff --git a/arthur/apis/cloudflare/zones.py b/arthur/apis/cloudflare/zones.py index 367dc3b..e027a9a 100644 --- a/arthur/apis/cloudflare/zones.py +++ b/arthur/apis/cloudflare/zones.py @@ -5,33 +5,37 @@ import aiohttp from arthur.config import CONFIG -CF_TOKEN = CONFIG.cloudflare_token +AUTH_HEADER = { + "Authorization": f"Bearer {CONFIG.cloudflare_token}" +} async def list_zones(zone_name: Optional[str] = None) -> dict[str, str]: """List all Cloudflare zones.""" endpoint = "https://api.cloudflare.com/client/v4/zones" - request_headers = {"X-Auth-User-Service-Key": CF_TOKEN} if zone_name is not None: endpoint += f"?name={zone_name}" async with aiohttp.ClientSession() as session: - async with session.get(endpoint, headers=request_headers) as response: + async with session.get(endpoint, headers=AUTH_HEADER) as response: info = await response.json() zones = info["result"] - return {zone.name: zone.id for zone in zones} + return {zone["name"]: zone["id"] for zone in zones} async def purge_zone(zone_identifier: str) -> dict: """Purge the cache for a Cloudflare zone.""" - endpoint = f"https://api.cloudflare.com/client/v4/zones/{zone_identifier}/purge_cache?purge_everything=true" # noqa: E501 - request_headers = {"X-Auth-User-Service-Key": CF_TOKEN} + endpoint = f"https://api.cloudflare.com/client/v4/zones/{zone_identifier}" + + PURGE_EVERYTHING = { + "purge_everything": True + } async with aiohttp.ClientSession() as session: - async with session.post(endpoint, headers=request_headers) as response: + async with session.post(endpoint, headers=AUTH_HEADER, body=PURGE_EVERYTHING) as response: info = await response.json() return {"success": info["success"], "errors": info["errors"]} diff --git a/arthur/exts/cloudflare/zones.py b/arthur/exts/cloudflare/zones.py index c6e625f..448ad81 100644 --- a/arthur/exts/cloudflare/zones.py +++ b/arthur/exts/cloudflare/zones.py @@ -27,16 +27,15 @@ class Zones(commands.Cog): required_id = pydis_zones[zone_name] purge_attempt_response = await zones.purge_zone(required_id) - message = "__Cloudflare cache purge status__\n" + message = "" if purge_attempt_response["success"]: - message += "Purge status: **Successful** :white_check_mark:\n" - message += f"Zone purged: **Zone purged: `{zone_name}`" - return await ctx.send(message) + message += ":white_check_mark:" + message += f"**Cache cleared!** The Cloudflare cache for `{zone_name}` was cleared." else: - message += "Purge status: **Failed** :x:\n" + message += f":x: **'Tis but a scratch! The cache for `{zone_name}` couldn't be cleared." if errors := purge_attempt_response["errors"]: - message += "__Errors:__\n" + message += "\nReceived errors:\n" for error in errors: message += f"**Code**: `{error.code}`\n" message += f"**Message**: {error.message}\n" -- cgit v1.2.3 From 941e7690b4099ee3c3da9e5d4b6ebd56327c262c Mon Sep 17 00:00:00 2001 From: Vivaan Verma Date: Thu, 22 Jul 2021 17:58:06 +0100 Subject: Standardise responses + more --- arthur/exts/cloudflare/zones.py | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) (limited to 'arthur/exts/cloudflare/zones.py') diff --git a/arthur/exts/cloudflare/zones.py b/arthur/exts/cloudflare/zones.py index 448ad81..ed1ff0d 100644 --- a/arthur/exts/cloudflare/zones.py +++ b/arthur/exts/cloudflare/zones.py @@ -5,6 +5,7 @@ from discord.ext import commands from arthur.apis.cloudflare import zones from arthur.bot import KingArthur +from arthur.utils import generate_error_message class Zones(commands.Cog): @@ -21,26 +22,26 @@ class Zones(commands.Cog): @zones.command(name="purge") async def purge(self, ctx: commands.Context, zone_name: Optional[str] = "pythondiscord.com" - ) -> None: + ) -> None: """Command to clear the Cloudflare cache of the specified zone.""" pydis_zones = await zones.list_zones(zone_name) required_id = pydis_zones[zone_name] purge_attempt_response = await zones.purge_zone(required_id) - message = "" - if purge_attempt_response["success"]: - message += ":white_check_mark:" - message += f"**Cache cleared!** The Cloudflare cache for `{zone_name}` was cleared." + message = ":white_check_mark:" + message += f" **Cache cleared!** The Cloudflare cache for `{zone_name}` was cleared." else: - message += f":x: **'Tis but a scratch! The cache for `{zone_name}` couldn't be cleared." + description_content = f"The cache for `{zone_name}` couldn't be cleared.\n" if errors := purge_attempt_response["errors"]: - message += "\nReceived errors:\n" for error in errors: - message += f"**Code**: `{error.code}`\n" - message += f"**Message**: {error.message}\n" - return await ctx.send(message) + description_content += f"`{error['code']}`: {error['message']}\n" + message = generate_error_message( + description=description_content, + emote=":x:" + ) + await ctx.send(message) def setup(bot: KingArthur) -> None: """Add the extension to the bot.""" -- cgit v1.2.3 From 52722c7c930eeeb925f724b016091a666829e527 Mon Sep 17 00:00:00 2001 From: Vivaan Verma Date: Thu, 22 Jul 2021 19:57:50 +0100 Subject: Lint fix --- arthur/exts/cloudflare/zones.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'arthur/exts/cloudflare/zones.py') diff --git a/arthur/exts/cloudflare/zones.py b/arthur/exts/cloudflare/zones.py index ed1ff0d..91eee33 100644 --- a/arthur/exts/cloudflare/zones.py +++ b/arthur/exts/cloudflare/zones.py @@ -22,7 +22,7 @@ class Zones(commands.Cog): @zones.command(name="purge") async def purge(self, ctx: commands.Context, zone_name: Optional[str] = "pythondiscord.com" - ) -> None: + ) -> None: """Command to clear the Cloudflare cache of the specified zone.""" pydis_zones = await zones.list_zones(zone_name) required_id = pydis_zones[zone_name] @@ -43,6 +43,7 @@ class Zones(commands.Cog): await ctx.send(message) + def setup(bot: KingArthur) -> None: """Add the extension to the bot.""" bot.add_cog(Zones(bot)) -- cgit v1.2.3 From 00fbfd927c69388cd7304856118408ee5dfec445 Mon Sep 17 00:00:00 2001 From: Vivaan Verma <54081925+doublevcodes@users.noreply.github.com> Date: Sun, 25 Jul 2021 17:27:36 +0100 Subject: Indentation fix --- arthur/exts/cloudflare/zones.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) (limited to 'arthur/exts/cloudflare/zones.py') diff --git a/arthur/exts/cloudflare/zones.py b/arthur/exts/cloudflare/zones.py index 91eee33..564dd2e 100644 --- a/arthur/exts/cloudflare/zones.py +++ b/arthur/exts/cloudflare/zones.py @@ -20,9 +20,11 @@ class Zones(commands.Cog): await ctx.send_help(ctx.command) @zones.command(name="purge") - async def purge(self, ctx: commands.Context, - zone_name: Optional[str] = "pythondiscord.com" - ) -> None: + async def purge( + self, + ctx: commands.Context, + zone_name: Optional[str] = "pythondiscord.com" + ) -> None: """Command to clear the Cloudflare cache of the specified zone.""" pydis_zones = await zones.list_zones(zone_name) required_id = pydis_zones[zone_name] -- cgit v1.2.3