Skip to content
This repository has been archived by the owner on Oct 10, 2024. It is now read-only.

Add rules command #33

Merged
merged 6 commits into from
Jun 25, 2021
Merged
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
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,13 @@ In order to run buttercup, [poetry](https://python-poetry.org/) is used to manag

Apart from this, a `.toml` configuration file is expected. Below is a default `config.toml`:
```
[secrets]
discord = "YOUR DISCORD BOT SECRET HERE"
[Discord]
token = "<YOUR DISCORD BOT SECRET HERE>"

[Reddit]
client_id = "<YOUR REDDIT CLIENT ID HERE>"
client_secret = "<YOUR REDDIT CLIENT SECRET HERE>"
user_agent = "grafeas.org.buttercup:v0.1.0 (contact u/<YOUR USERNAME HERE>)"

[guild]
name = "Test Bubbles"
Expand Down
95 changes: 95 additions & 0 deletions buttercup/cogs/rules.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
from datetime import datetime

import asyncpraw
from asyncprawcore import NotFound, Redirect
from discord import Embed
from discord.ext.commands import Cog
from discord_slash import SlashContext, cog_ext
from discord_slash.utils.manage_commands import create_option

from buttercup.bot import ButtercupBot
from buttercup.strings import translation

i18n = translation()


def extract_sub_name(subreddit: str) -> str:
"""Extract the name of the sub without prefix."""
if subreddit.startswith("/r/"):
return subreddit[3:]
if subreddit.startswith("r/"):
return subreddit[2:]
return subreddit


class Rules(Cog):
def __init__(self, bot: ButtercupBot, reddit_api: asyncpraw.Reddit) -> None:
"""Initialize the Rules cog."""
self.bot = bot
self.reddit_api = reddit_api

@cog_ext.cog_slash(
name="rules",
description="Get the rules of the specified subreddit.",
options=[
create_option(
name="subreddit",
description="The subreddit to get the rules of.",
TimJentzsch marked this conversation as resolved.
Show resolved Hide resolved
option_type=3,
required=True,
)
],
)
async def _rules(self, ctx: SlashContext, subreddit: str) -> None:
"""Get the rules of the specified subreddit."""
# Send a quick response
# We will edit this later with the actual content
start = datetime.now()
sub_name = extract_sub_name(subreddit)
msg = await ctx.send(i18n["rules"]["getting_rules"].format(sub_name))

sub = await self.reddit_api.subreddit(sub_name)

embed = Embed(title=i18n["rules"]["embed_title"].format(sub_name))

try:
async for rule in sub.rules:
# The value field is not allowed to be a blank string
# So we just repeat the name of the rule if it is not provided
embed.add_field(
name=rule.short_name,
value=rule.description or rule.short_name,
inline=False,
)
except Redirect:
# Sometimes Reddit redirects to the subreddit search
await msg.edit(content=i18n["rules"]["sub_not_found"].format(sub_name))
return
except NotFound:
# Sometimes it throws a not found exception, e.g. if a character isn't allowed
await msg.edit(content=i18n["rules"]["sub_not_found"].format(sub_name))
return

delay = datetime.now() - start
await msg.edit(
content=i18n["rules"]["embed_message"].format(
f"{delay.microseconds // 1000} ms"
),
embed=embed,
)


def setup(bot: ButtercupBot) -> None:
"""Set up the Rules cog."""
reddit_config = bot.config["Reddit"]
reddit_api = asyncpraw.Reddit(
client_id=reddit_config["client_id"],
client_secret=reddit_config["client_secret"],
user_agent=reddit_config["user_agent"],
)
bot.add_cog(Rules(bot=bot, reddit_api=reddit_api))


def teardown(bot: ButtercupBot) -> None:
"""Unload the Rules cog."""
bot.remove_cog("Rules")
4 changes: 2 additions & 2 deletions buttercup/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
from buttercup import logger
from buttercup.bot import ButtercupBot

EXTENSIONS = ["admin", "handlers", "name_validator", "find", "stats", "ping"]
EXTENSIONS = ["admin", "handlers", "name_validator", "find", "stats", "rules", "ping"]


logger.configure_logging()
config_path = sys.argv[1] if len(sys.argv) > 1 else "config.toml"
bot = ButtercupBot(command_prefix="!", config_path=config_path, extensions=EXTENSIONS)
bot.run(bot.config["secrets"]["discord"])
bot.run(bot.config["Discord"]["token"])
9 changes: 9 additions & 0 deletions buttercup/strings/en_US.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,12 @@ stats:
**Volunteers**: {:,d}
**Transcriptions**: {:,d}
**Days Since Inception**: {:,d}
rules:
getting_rules: |
Getting the rules for r/{0}...
sub_not_found: |
I couldn't find a sub named r/{0}. Are you sure you spelled it correctly?
embed_message: |
Here are the rules! ({0})
embed_title: |
Rules for r/{0}
80 changes: 79 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

67 changes: 34 additions & 33 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,33 +1,34 @@
[tool.poetry]
name = "buttercup"
version = "0.1.0"
description = "The Discord Bot!"
authors = ["Grafeas Group Ltd. <devs@grafeas.org>"]

[tool.poetry.dependencies]
"discord.py" = "^1.7.2"
discord-py-slash-command = "^1.2.2"
python = "^3.8"
toml = "^0.10.1"
blossom-wrapper = { git = "https://github.com/GrafeasGroup/blossom-wrapper.git", branch = "master" }
requests = "^2.25.1"
PyYAML = "^5.3.1"
python-dateutil = "^2.8.1"

[tool.poetry.dev-dependencies]
better-exceptions = "^0.2.2"
black = "^19.10b0"
flake8 = { version = "^3.7.9", allow-prereleases = true }
flake8-annotations = "^2.0.1"
flake8-black = "^0.1.1"
flake8-docstrings = "^1.5.0"
flake8-import-order = "^0.18.1"
flake8-variables-names = "^0.0.3"
pep8-naming = "^0.9.1"
pre-commit = "^2.4.0"
seed-isort-config = "^2.1.1"
isort = "^4.3.21"

[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"
[tool.poetry]
name = "buttercup"
version = "0.1.0"
description = "The Discord Bot!"
authors = ["Grafeas Group Ltd. <devs@grafeas.org>"]

[tool.poetry.dependencies]
"discord.py" = "^1.7.2"
discord-py-slash-command = "^1.2.2"
python = "^3.8"
toml = "^0.10.1"
blossom-wrapper = { git = "https://github.com/GrafeasGroup/blossom-wrapper.git", branch = "master" }
requests = "^2.25.1"
PyYAML = "^5.3.1"
python-dateutil = "^2.8.1"
asyncpraw = "^7.2.0"

[tool.poetry.dev-dependencies]
better-exceptions = "^0.2.2"
black = "^19.10b0"
flake8 = { version = "^3.7.9", allow-prereleases = true }
flake8-annotations = "^2.0.1"
flake8-black = "^0.1.1"
flake8-docstrings = "^1.5.0"
flake8-import-order = "^0.18.1"
flake8-variables-names = "^0.0.3"
pep8-naming = "^0.9.1"
pre-commit = "^2.4.0"
seed-isort-config = "^2.1.1"
isort = "^4.3.21"

[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"