aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--CONTRIBUTING.md65
-rw-r--r--bot/cogs/alias.py2
-rw-r--r--bot/cogs/bigbrother.py173
-rw-r--r--bot/cogs/moderation.py57
-rw-r--r--bot/constants.py1
-rw-r--r--config-default.yml2
6 files changed, 228 insertions, 72 deletions
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 36152fc5d..e05655af1 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,40 +1,49 @@
# Contributing to one of our projects
-Our projects are open-source, and are deployed as commits are pushed to the `master` branch on each repository.
-We've created a set of guidelines here in order to keep everything clean and in working order. Please note that
-contributions may be rejected on the basis of a contributor failing to follow the guidelines.
+Our projects are open-source and are automatically deployed whenever commits are pushed to the `master` branch on each repository, so we've created a set of guidelines in order to keep everything clean and in working order.
+
+Note that contributions may be rejected on the basis of a contributor failing to follow these guidelines.
## Rules
1. **No force-pushes** or modifying the Git history in any way.
-1. If you have direct access to the repository, **create a branch for your changes** and create a merge request for that branch.
- If not, fork it and work on a separate branch there.
- * Some repositories require this and will reject any direct pushes to `master`. Make this a habit!
-1. If someone is working on a merge request, **do not open your own merge request for the same task**. Instead, leave some comments
- on the existing merge request. Communication is key, and there's no point in two separate implementations of the same thing.
- * One option is to fork the other contributor's repository, and submit your changes to their branch with your
- own merge request. If you do this, we suggest following these guidelines when interacting with their repository
- as well.
-1. **Adhere to the prevailing code style**, which we enforce using [flake8](http://flake8.pycqa.org/en/latest/index.html).
- * Additionally, run `flake8` against your code before you push it. Your commit will be rejected by the build server
- if it fails to lint.
-1. **Don't fight the framework**. Every framework has its flaws, but the frameworks we've picked out have been carefully
- chosen for their particular merits. If you can avoid it, please resist reimplementing swathes of framework logic - the
- work has already been done for you!
-1. **Work as a team** and cooperate where possible. Keep things friendly, and help each other out - these are shared
- projects, and nobody likes to have their feet trodden on.
-1. **Internal projects are internal**. As a contributor, you have access to information that the rest of the server
- does not. With this trust comes responsibility - do not release any information you have learned as a result of
- your contributor position. We are very strict about announcing things at specific times, and many staff members
- will not appreciate a disruption of the announcement schedule.
-
-Above all, the needs of our community should come before the wants of an individual. Work together, build solutions to
-problems and try to do so in a way that people can learn from easily. Abuse of our trust may result in the loss of your Contributor role, especially in relation to Rule 7.
+2. If you have direct access to the repository, **create a branch for your changes** and create a pull request for that branch. If not, create a branch on a fork of the repository and create a pull request from there.
+ * It's common practice for a repository to reject direct pushes to `master`, so make branching a habit!
+3. **Adhere to the prevailing code style**, which we enforce using [flake8](http://flake8.pycqa.org/en/latest/index.html).
+ * Run `flake8` against your code **before** you push it. Your commit will be rejected by the build server if it fails to lint.
+ * [Git Hooks](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) are a powerful tool that can be a daunting to set up. Fortunately, [`pre-commit`](https://github.com/pre-commit/pre-commit) abstracts this process away from you and is provided as a dev dependency for this project. Run `pipenv run precommit` when setting up the project and you'll never have to worry about breaking the build for linting errors.
+4. **Make great commits**. A well structured git log is key to a project's maintainability; it efficiently provides insight into when and *why* things were done for future maintainers of the project.
+ * Commits should be as narrow in scope as possible. Commits that span hundreds of lines across multiple unrelated functions and/or files are very hard for maintainers to follow. After about a week they'll probably be hard for you to follow too.
+ * Try to avoid making minor commits for fixing typos or linting errors. Since you've already set up a pre-commit hook to run `flake8` before a commit, you shouldn't be committing linting issues anyway.
+ * A more in-depth guide to writing great commit messages can be found in Chris Beam's [*How to Write a Git Commit Message*](https://chris.beams.io/posts/git-commit/)
+5. **Avoid frequent pushes to the main repository**. This goes for PRs opened against your fork as well. Our test build pipelines are triggered every time a push to the repository (or PR) is made. Try to batch your commits until you've finished working for that session, or you've reached a point where collaborators need your commits to continue their own work. This also provides you the opportunity to amend commits for minor changes rather than having to commit them on their own because you've already pushed.
+ * This includes merging master into your branch. Try to leave merging from master for after your PR passes review; a maintainer will bring your PR up to date before merging. Exceptions to this include: resolving merge conflicts, needing something that was pushed to master for your branch, or something was pushed to master that could potentionally affect the functionality of what you're writing.
+6. **Don't fight the framework**. Every framework has its flaws, but the frameworks we've picked out have been carefully chosen for their particular merits. If you can avoid it, please resist reimplementing swathes of framework logic - the work has already been done for you!
+7. If someone is working on a pull request, **do not open your own pull request for the same task**. Instead, collaborate with the author(s) of the existing pull request. Communication is key, and there's no point in two separate implementations of the same thing.
+ * One option is to fork the other contributor's repository and submit your changes to their branch with your own pull request. We suggest following these guidelines when interacting with their repository as well.
+8. **Work as a team** and collaborate whereever possible. Keep things friendly and help each other out - these are shared projects and nobody likes to have their feet trodden on.
+9. **Internal projects are internal**. As a contributor, you have access to information that the rest of the server does not. With this trust comes responsibility - do not release any information you have learned as a result of your contributor position. We are very strict about announcing things at specific times, and many staff members will not appreciate a disruption of the announcement schedule.
+
+Above all, the needs of our community should come before the wants of an individual. Work together, build solutions to problems and try to do so in a way that people can learn from easily. Abuse of our trust may result in the loss of your Contributor role, especially in relation to Rule 7.
## Changes to this arrangement
-All projects evolve over time, and this contribution guide is no different. This document may also be subject to pull
-requests or changes by contributors, where you believe you have something valuable to add or change.
+All projects evolve over time, and this contribution guide is no different. This document is open to pull requests or changes by contributors. If you believe you have something valuable to add or change, please don't hesitate to do so in a PR.
+
+## Supplemental Information
+### Developer Environment
+A working environment for the [PyDis site](https://github.com/python-discord/site) is required to develop the bot. Instructions for setting up environments for both the site and the bot can be found on the PyDis Wiki:
+ * [Site](https://wiki.pythondiscord.com/wiki/contributing/project/site)
+ * [Bot](https://wiki.pythondiscord.com/wiki/contributing/project/bot)
+
+### Logging levels
+The project currently defines [`logging`](https://docs.python.org/3/library/logging.html) levels as follows:
+* **TRACE:** Use this for tracing every step of a complex process. That way we can see which step of the process failed. Err on the side of verbose. **Note:** This is a PyDis-implemented logging level.
+* **DEBUG:** Someone is interacting with the application, and the application is behaving as expected.
+* **INFO:** Something completely ordinary happened. Like a cog loading during startup.
+* **WARNING:** Someone is interacting with the application in an unexpected way or the application is responding in an unexpected way, but without causing an error.
+* **ERROR:** An error that affects the specific part that is being interacted with
+* **CRITICAL:** An error that affects the whole application.
## Footnotes
diff --git a/bot/cogs/alias.py b/bot/cogs/alias.py
index 0b848c773..0e6b3a7c6 100644
--- a/bot/cogs/alias.py
+++ b/bot/cogs/alias.py
@@ -71,7 +71,7 @@ class Alias:
@command(name="watch", hidden=True)
async def bigbrother_watch_alias(
- self, ctx, user: User, *, reason: str
+ self, ctx: Context, user: User, *, reason: str
):
"""
Alias for invoking <prefix>bigbrother watch user [text_channel].
diff --git a/bot/cogs/bigbrother.py b/bot/cogs/bigbrother.py
index 70916cd7b..f07289985 100644
--- a/bot/cogs/bigbrother.py
+++ b/bot/cogs/bigbrother.py
@@ -3,23 +3,30 @@ import logging
import re
from collections import defaultdict, deque
from time import strptime, struct_time
-from typing import List, Union
+from typing import List, NamedTuple, Optional, Union
from aiohttp import ClientError
from discord import Color, Embed, Guild, Member, Message, TextChannel, User
-from discord.ext.commands import Bot, Context, group
+from discord.ext.commands import Bot, Context, command, group
from bot.constants import BigBrother as BigBrotherConfig, Channels, Emojis, Guild as GuildConfig, Keys, Roles, URLs
from bot.decorators import with_role
from bot.pagination import LinePaginator
from bot.utils import messages
from bot.utils.moderation import post_infraction
+from bot.utils.time import parse_rfc1123, time_since
log = logging.getLogger(__name__)
URL_RE = re.compile(r"(https?://[^\s]+)")
+class WatchInformation(NamedTuple):
+ reason: str
+ actor_id: Optional[int]
+ inserted_at: Optional[str]
+
+
class BigBrother:
"""User monitoring to assist with moderation."""
@@ -66,7 +73,7 @@ class BigBrother:
data = await response.json()
self.update_cache(data)
- async def get_watch_reason(self, user_id: int) -> str:
+ async def get_watch_information(self, user_id: int) -> WatchInformation:
""" Fetches and returns the latest watch reason for a user using the infraction API """
re_bb_watch = rf"^{self.infraction_watch_prefix}"
@@ -84,20 +91,34 @@ class BigBrother:
infraction_list = await response.json()
except ClientError:
log.exception(f"Failed to retrieve bb watch reason for {user_id}.")
- return "(error retrieving bb reason)"
+ return WatchInformation(reason="(error retrieving bb reason)", actor_id=None, inserted_at=None)
if infraction_list:
+ # Get the latest watch reason
latest_reason_infraction = max(infraction_list, key=self._parse_infraction_time)
+
+ # Get the actor of the watch/nominate action
+ actor_id = int(latest_reason_infraction["actor"]["user_id"])
+
+ # Get the date the watch was set
+ date = latest_reason_infraction["inserted_at"]
+
+ # Get the latest reason without the prefix
latest_reason = latest_reason_infraction['reason'][len(self.infraction_watch_prefix):]
+
log.trace(f"The latest bb watch reason for {user_id}: {latest_reason}")
- return latest_reason
+ return WatchInformation(reason=latest_reason, actor_id=actor_id, inserted_at=date)
- log.trace(f"No bb watch reason found for {user_id}; returning default string")
- return "(no reason specified)"
+ log.trace(f"No bb watch reason found for {user_id}; returning defaults")
+ return WatchInformation(reason="(no reason specified)", actor_id=None, inserted_at=None)
@staticmethod
- def _parse_infraction_time(infraction: str) -> struct_time:
- """Takes RFC1123 date_time string and returns time object for sorting purposes"""
+ def _parse_infraction_time(infraction: dict) -> struct_time:
+ """
+ Helper function that retrieves the insertion time from the infraction dictionary,
+ converts the retrieved RFC1123 date_time string to a time object, and returns it
+ so infractions can be sorted by their insertion time.
+ """
date_string = infraction["inserted_at"]
return strptime(date_string, "%a, %d %b %Y %H:%M:%S %Z")
@@ -182,15 +203,38 @@ class BigBrother:
if message.author.id != last_user or message.channel.id != last_channel or msg_count > limit:
# Retrieve watch reason from API if it's not already in the cache
if message.author.id not in self.watch_reasons:
- log.trace(f"No watch reason for {message.author.id} found in cache; retrieving from API")
- user_watch_reason = await self.get_watch_reason(message.author.id)
- self.watch_reasons[message.author.id] = user_watch_reason
+ log.trace(f"No watch information for {message.author.id} found in cache; retrieving from API")
+ user_watch_information = await self.get_watch_information(message.author.id)
+ self.watch_reasons[message.author.id] = user_watch_information
self.last_log = [message.author.id, message.channel.id, 0]
+ # Get reason, actor, inserted_at
+ reason, actor_id, inserted_at = self.watch_reasons[message.author.id]
+
+ # Setting up the default author_field
+ author_field = message.author.nick or message.author.name
+
+ # When we're dealing with a talent-pool header, add nomination info to the author field
+ if destination == self.bot.get_channel(Channels.talent_pool):
+ log.trace("We're sending a header to the talent-pool; let's add nomination info")
+ # If a reason was provided, both should be known
+ if actor_id and inserted_at:
+ # Parse actor name
+ guild: GuildConfig = self.bot.get_guild(GuildConfig.id)
+ actor_as_member = guild.get_member(actor_id)
+ actor = actor_as_member.nick or actor_as_member.name
+
+ # Get time delta since insertion
+ date_time = parse_rfc1123(inserted_at).replace(tzinfo=None)
+ time_delta = time_since(date_time, precision="minutes", max_units=1)
+
+ # Adding nomination info to author_field
+ author_field = f"{author_field} (nominated {time_delta} by {actor})"
+
embed = Embed(description=f"{message.author.mention} in [#{message.channel.name}]({message.jump_url})")
- embed.set_author(name=message.author.nick or message.author.name, icon_url=message.author.avatar_url)
- embed.set_footer(text=f"Watch reason: {self.watch_reasons[message.author.id]}")
+ embed.set_author(name=author_field, icon_url=message.author.avatar_url)
+ embed.set_footer(text=f"Reason: {reason}")
await destination.send(embed=embed)
@staticmethod
@@ -217,6 +261,39 @@ class BigBrother:
await messages.send_attachments(message, destination)
+ async def _watch_user(self, ctx: Context, user: User, reason: str, channel_id: int):
+ post_data = {
+ 'user_id': str(user.id),
+ 'channel_id': str(channel_id)
+ }
+
+ async with self.bot.http_session.post(
+ URLs.site_bigbrother_api,
+ headers=self.HEADERS,
+ json=post_data
+ ) as response:
+ if response.status == 204:
+ if channel_id == Channels.talent_pool:
+ await ctx.send(f":ok_hand: added {user} to the <#{channel_id}>!")
+ else:
+ await ctx.send(f":ok_hand: will now relay messages sent by {user} in <#{channel_id}>")
+
+ channel = self.bot.get_channel(channel_id)
+ if channel is None:
+ log.error(
+ f"could not update internal cache, failed to find a channel with ID {channel_id}"
+ )
+ else:
+ self.watched_users[user.id] = channel
+
+ # Add a note (shadow warning) with the reason for watching
+ reason = f"{self.infraction_watch_prefix}{reason}"
+ await post_infraction(ctx, user, type="warning", reason=reason, hidden=True)
+ else:
+ data = await response.json()
+ error_reason = data.get('error_message', "no message provided")
+ await ctx.send(f":x: the API returned an error: {error_reason}")
+
@group(name='bigbrother', aliases=('bb',), invoke_without_command=True)
@with_role(Roles.owner, Roles.admin, Roles.moderator)
async def bigbrother_group(self, ctx: Context):
@@ -274,35 +351,7 @@ class BigBrother:
channel_id = Channels.big_brother_logs
- post_data = {
- 'user_id': str(user.id),
- 'channel_id': str(channel_id)
- }
-
- async with self.bot.http_session.post(
- URLs.site_bigbrother_api,
- headers=self.HEADERS,
- json=post_data
- ) as response:
- if response.status == 204:
- await ctx.send(f":ok_hand: will now relay messages sent by {user} in <#{channel_id}>")
-
- channel = self.bot.get_channel(channel_id)
- if channel is None:
- log.error(
- f"could not update internal cache, failed to find a channel with ID {channel_id}"
- )
- else:
- self.watched_users[user.id] = channel
- self.watch_reasons[user.id] = reason
-
- # Add a note (shadow warning) with the reason for watching
- reason = f"{self.infraction_watch_prefix}{reason}"
- await post_infraction(ctx, user, type="warning", reason=reason, hidden=True)
- else:
- data = await response.json()
- error_reason = data.get('error_message', "no message provided")
- await ctx.send(f":x: the API returned an error: {error_reason}")
+ await self._watch_user(ctx, user, reason, channel_id)
@bigbrother_group.command(name='unwatch', aliases=('uw',))
@with_role(Roles.owner, Roles.admin, Roles.moderator)
@@ -328,7 +377,45 @@ class BigBrother:
reason = data.get('error_message', "no message provided")
await ctx.send(f":x: the API returned an error: {reason}")
+ @bigbrother_group.command(name='nominate', aliases=('n',))
+ @with_role(Roles.owner, Roles.admin, Roles.moderator)
+ async def nominate_command(self, ctx: Context, user: User, *, reason: str):
+ """
+ Nominates a user for the helper role by adding them to the talent-pool channel
+
+ A `reason` for the nomination is required and will be added as a note to
+ the user's records.
+ """
+
+ # Note: This function is called from HelperNomination.nominate_command so that the
+ # !nominate command does not show up under "BigBrother" in the help embed, but under
+ # the header HelperNomination for users with the helper role.
+
+ channel_id = Channels.talent_pool
+
+ await self._watch_user(ctx, user, reason, channel_id)
+
+
+class HelperNomination:
+ def __init__(self, bot):
+ self.bot = bot
+
+ @command(name='nominate', aliases=('n',))
+ @with_role(Roles.owner, Roles.admin, Roles.moderator, Roles.helpers)
+ async def nominate_command(self, ctx: Context, user: User, *, reason: str):
+ """
+ Nominates a user for the helper role by adding them to the talent-pool channel
+
+ A `reason` for the nomination is required and will be added as a note to
+ the user's records.
+ """
+
+ cmd = self.bot.get_command("bigbrother nominate")
+
+ await ctx.invoke(cmd, user, reason=reason)
+
def setup(bot: Bot):
bot.add_cog(BigBrother(bot))
+ bot.add_cog(HelperNomination(bot))
log.info("Cog loaded: BigBrother")
diff --git a/bot/cogs/moderation.py b/bot/cogs/moderation.py
index e9acc27b9..6b90d43ab 100644
--- a/bot/cogs/moderation.py
+++ b/bot/cogs/moderation.py
@@ -132,6 +132,11 @@ class Moderation(Scheduler):
**`reason`:** The reason for the kick.
"""
+ if not await self.respect_role_hierarchy(ctx, user, 'kick'):
+ # Ensure ctx author has a higher top role than the target user
+ # Warning is sent to ctx by the helper method
+ return
+
response_object = await post_infraction(ctx, user, type="kick", reason=reason)
if response_object is None:
return
@@ -187,6 +192,12 @@ class Moderation(Scheduler):
**`reason`:** The reason for the ban.
"""
+ member = ctx.guild.get_member(user.id)
+ if not await self.respect_role_hierarchy(ctx, member, 'ban'):
+ # Ensure ctx author has a higher top role than the target user
+ # Warning is sent to ctx by the helper method
+ return
+
response_object = await post_infraction(ctx, user, type="ban", reason=reason)
if response_object is None:
return
@@ -370,6 +381,12 @@ class Moderation(Scheduler):
**`reason`:** The reason for the temporary ban.
"""
+ member = ctx.guild.get_member(user.id)
+ if not await self.respect_role_hierarchy(ctx, member, 'tempban'):
+ # Ensure ctx author has a higher top role than the target user
+ # Warning is sent to ctx by the helper method
+ return
+
response_object = await post_infraction(
ctx, user, type="ban", reason=reason, duration=duration
)
@@ -475,6 +492,11 @@ class Moderation(Scheduler):
**`reason`:** The reason for the kick.
"""
+ if not await self.respect_role_hierarchy(ctx, user, 'shadowkick'):
+ # Ensure ctx author has a higher top role than the target user
+ # Warning is sent to ctx by the helper method
+ return
+
response_object = await post_infraction(ctx, user, type="kick", reason=reason, hidden=True)
if response_object is None:
return
@@ -523,6 +545,12 @@ class Moderation(Scheduler):
**`reason`:** The reason for the ban.
"""
+ member = ctx.guild.get_member(user.id)
+ if not await self.respect_role_hierarchy(ctx, member, 'shadowban'):
+ # Ensure ctx author has a higher top role than the target user
+ # Warning is sent to ctx by the helper method
+ return
+
response_object = await post_infraction(ctx, user, type="ban", reason=reason, hidden=True)
if response_object is None:
return
@@ -662,6 +690,12 @@ class Moderation(Scheduler):
**`reason`:** The reason for the temporary ban.
"""
+ member = ctx.guild.get_member(user.id)
+ if not await self.respect_role_hierarchy(ctx, member, 'shadowtempban'):
+ # Ensure ctx author has a higher top role than the target user
+ # Warning is sent to ctx by the helper method
+ return
+
response_object = await post_infraction(
ctx, user, type="ban", reason=reason, duration=duration, hidden=True
)
@@ -1334,6 +1368,29 @@ class Moderation(Scheduler):
if User in error.converters:
await ctx.send(str(error.errors[0]))
+ async def respect_role_hierarchy(self, ctx: Context, target: Member, infraction_type: str) -> bool:
+ """
+ Check if the highest role of the invoking member is greater than that of the target member
+
+ If this check fails, a warning is sent to the invoking ctx
+
+ Implement as a method rather than a check in order to avoid having to reimplement parameter
+ checks & conversions in a dedicated check decorater
+ """
+
+ actor = ctx.author
+ target_is_lower = target.top_role < actor.top_role
+ if not target_is_lower:
+ log.info(
+ f"{actor} ({actor.id}) attempted to {infraction_type} "
+ f"{target} ({target.id}), who has an equal or higher top role"
+ )
+ await ctx.send(
+ f":x: {actor.mention}, you may not {infraction_type} someone with an equal or higher top role"
+ )
+
+ return target_is_lower
+
def setup(bot):
bot.add_cog(Moderation(bot))
diff --git a/bot/constants.py b/bot/constants.py
index 61f62b09c..0e0c1845b 100644
--- a/bot/constants.py
+++ b/bot/constants.py
@@ -351,6 +351,7 @@ class Channels(metaclass=YAMLGetter):
off_topic_3: int
python: int
reddit: int
+ talent_pool: int
userlog: int
verification: int
diff --git a/config-default.yml b/config-default.yml
index 14f9dabc5..d77f9d186 100644
--- a/config-default.yml
+++ b/config-default.yml
@@ -114,6 +114,7 @@ guild:
python: 267624335836053506
reddit: 458224812528238616
staff_lounge: &STAFF_LOUNGE 464905259261755392
+ talent_pool: &TALENT_POOL 534321732593647616
userlog: 528976905546760203
verification: 352442727016693763
@@ -202,6 +203,7 @@ filter:
- *BBLOGS
- *STAFF_LOUNGE
- *DEVTEST
+ - *TALENT_POOL
role_whitelist:
- *ADMIN_ROLE