Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch to extension based Cogs #7

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions sanic.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
from discord.ext import commands

from sanicbot.core.cogs import HelpCog, GitCog
from sanicbot.core.config import config

bot = commands.Bot(help_command=None, command_prefix=None)
git_cog = GitCog(bot)

EXTENSIONS = (
'sanicbot.extensions.git',
'sanicbot.extensions.help',
)


def main():
bot = commands.Bot(help_command=None, command_prefix='!')

for ext in EXTENSIONS:
bot.load_extension(ext)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By adding Cog classes using bot.add_cog we can avoid adding setup() functions to the cog files. (see PR #8 for implementation). By extending the commands.Bot class we have more control over the bot scope and can handle adding cogs more elegantly.


if __name__ == '__main__':
bot.command_prefix = '!'
bot.add_cog(git_cog)
bot.add_cog(HelpCog(bot))
bot.run(config['SANIC']['token'])


if __name__ == '__main__':
main()
Empty file added sanicbot/extensions/__init__.py
Empty file.
34 changes: 25 additions & 9 deletions sanicbot/core/cogs.py → sanicbot/extensions/git.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@
from discord.ext import commands
from discord.ext.commands import Context

from sanicbot.core.config import config
from sanicbot.core.utils import failure_message, success_message


class GitCog(commands.Cog):
class Git(commands.Cog):
issue_pattern = re.compile(r"#(?P<issue_id>[1,2]\d{3})")

def __init__(self, bot):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot

async def lookup(self, ctx: Context, number: int, repo: str):
Expand Down Expand Up @@ -44,19 +45,34 @@ async def retrieve_github_issue(
repo = f"sanic-{repo}"
await self.lookup(ctx, number, repo)

@commands.command()
async def issue(self, ctx: Context, repo: str, title: str, *, content: str) -> None:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a worthwhile command, however it would be better implemented using slash sub-commands. Considering what @ahopkins mentioned about a GH client, sub-commands would make things easier.

repo = repo if repo.startswith("sanic") else "sanic-" + repo
url = f"https://api.github.com/repos/sanic-org/{repo}/issues"
body = f"Forwarded from discord (Author: {ctx.author}, ID: {ctx.author.id})\n" + content
data = {
"title": title,
"body": body,
}
headers = {
"Accept": "application/vnd.github.v3+json",
"Authorization": "token " + config["SANIC"]["git_token"]
}
async with httpx.AsyncClient() as client:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

by extending the commands.Bot class (see PR #8 for implementation) we can attach a bot-level httpclient so we're not creating a new client each time a command is called.

response = await client.post(url, data=data, headers=headers)
if response.status_code == 200:
await success_message(ctx, "Issue created\n" + response.json()["url"])
else:
await failure_message(ctx, "An error occured: `" + response.json()["message"] + "`")
Comment on lines +61 to +66
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It may be premature for now, but it would be nice to abstract some of this into a GH client.

Copy link

@airsho airsho Oct 6, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could be set up like so: /gh create issue whereas issue lookup could be set up like: /gh issue 2559 and PRs /gh pr 352, could display lists of issues/PRs with pagination: /gh issues 1 and /gh prs 1


@commands.Cog.listener('on_message')
async def github_issue_message_listener(self, message: Message):
if not message.author.bot:
if match := self.issue_pattern.search(message.content):
await self.lookup(
message.channel, int(match.group("issue_id")), "sanic"
)
else:
await self.bot.process_commands(message)


class HelpCog(commands.Cog):
@commands.command()
async def help(self, ctx):
with open("./resources/help.txt") as f:
await ctx.send(f.read())
def setup(bot: commands.Bot):
bot.add_cog(Git(bot))
13 changes: 13 additions & 0 deletions sanicbot/extensions/help.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from discord.ext import commands


class Help(commands.Cog):
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By switching to application (slash) commands, this cog becomes obsolete. A user simply needs to start typing / to get a list of commands and their descriptions.

@commands.command()
async def help(self, ctx):
with open("./resources/help.txt") as f:
await ctx.send(f.read())


def setup(bot: commands.Bot):
bot.add_cog(Help())