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

Commit

Permalink
Merge 0b0e634 into 2e04106
Browse files Browse the repository at this point in the history
  • Loading branch information
TimJentzsch authored Jun 22, 2023
2 parents 2e04106 + 0b0e634 commit cc294cc
Show file tree
Hide file tree
Showing 4 changed files with 163 additions and 1 deletion.
2 changes: 2 additions & 0 deletions blossom/api/slack/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from blossom.api.slack.commands.migrate_user import migrate_user_cmd
from blossom.api.slack.commands.ping import ping_cmd
from blossom.api.slack.commands.reset import reset_cmd
from blossom.api.slack.commands.subinfo import subinfo_cmd
from blossom.api.slack.commands.unclaim import unclaim_cmd
from blossom.api.slack.commands.unwatch import unwatch_cmd
from blossom.api.slack.commands.warnings import warnings_cmd
Expand Down Expand Up @@ -64,6 +65,7 @@ def process_command(data: Dict) -> None:
"migrate": migrate_user_cmd,
"ping": ping_cmd,
"reset": reset_cmd,
"subinfo": subinfo_cmd,
"unwatch": unwatch_cmd,
"warnings": warnings_cmd,
"watch": watch_cmd,
Expand Down
119 changes: 119 additions & 0 deletions blossom/api/slack/commands/subinfo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
from datetime import datetime, timedelta

from django.db.models import Count
from django.utils import timezone

from blossom.api.models import Submission
from blossom.api.slack import client
from blossom.api.slack.utils import parse_subreddit
from blossom.authentication.models import BlossomUser
from blossom.strings import translation

i18n = translation()


QUEUE_TIMEOUT = timedelta(hours=18)


def subinfo_cmd(channel: str, message: str) -> None:
"""Send info about a subreddit to slack."""
parsed_message = message.split()
if len(parsed_message) == 1:
# The subreddit name is missing
client.chat_postMessage(
channel=channel,
text=i18n["slack"]["errors"]["unknown_username"].format(
action="subinfo", argument="<subreddit>"
),
)
return

elif len(parsed_message) == 2:
subreddit = parse_subreddit(parsed_message[1])

# Check if the sub exists in our system
sub_submissions = Submission.objects.filter(feed_iexact=f"/r/{subreddit}")

if sub_submissions.count() == 0:
client.chat_postMessage(
channel=channel,
text=i18n["slack"]["errors"]["unknown_subreddit"].format(
subreddit=subreddit,
),
)
return

# Get the correct capitalization for the subreddit
subreddit = parse_subreddit(sub_submissions.first().feed)

msg = sub_info_text(subreddit)
else:
msg = i18n["slack"]["errors"]["too_many_params"]

client.chat_postMessage(channel=channel, text=msg)


def sub_info_text(subreddit: str) -> str:
"""Get the info message for the given subreddit."""
prefixed_sub = f"/r/{subreddit}"

queue_timeout = datetime.now(tz=timezone.utc) - QUEUE_TIMEOUT

# Submission info

query_all = Submission.objects.filter(removed_from_queue=False)
query_sub = query_all.filter(feed__iexact=prefixed_sub)
query_all_queue = query_all.filter(created_at__gte=queue_timeout, archived=False)
query_sub_queue = query_all_queue.filter(feed__iexact=prefixed_sub)

total_all = query_all.count()
total_sub = query_sub.count()
total_percentage = total_sub / total_all if total_all > 0.0 else 0.0

queue_all = query_all_queue.count()
queue_sub = query_sub_queue.count()
queue_percentage = queue_all / queue_sub if queue_sub > 0.0 else 0.0

submission_info = i18n["slack"]["subinfo"]["submission_info"].format(
total_sub=total_sub,
total_percentage=total_percentage,
queue_sub=queue_sub,
queue_percentage=queue_percentage,
)

# Transcription info

query_all_transcribed = query_all.filter(completed_by__isnull=False)
query_sub_transcribed = query_sub.filter(completed_by__isnull=False)

transcribed_all = query_all_transcribed.count()
transcribed_sub = query_sub_transcribed.count()
transcribed_percentage_transcriptions = transcribed_sub / transcribed_all
transcribed_percentage_sub_submissions = transcribed_sub / total_sub

transcription_info = i18n["slack"]["subinfo"]["transcription_info"].format(
transcribed_sub=transcribed_sub,
transcribed_percentage_transcriptions=transcribed_percentage_transcriptions,
transcribed_percentage_sub_submissions=transcribed_percentage_sub_submissions,
)

# Volunteer info

volunteers_all = BlossomUser.objects.filter(is_bot=False).count()
volunteers_sub = Submission.objects.filter(
completed_by__isnull=False, feed__iexact=prefixed_sub
).aggregate(Count("completed_by__id", distinct=True))["completed_by__id__count"]
volunteer_percentage = volunteers_sub / volunteers_all

volunteer_info = i18n["slack"]["subinfo"]["volunteer_info"].format(
volunteer_sub=volunteers_sub,
volunteer_percentage=volunteer_percentage,
)

# Putting it all together
return i18n["slack"]["subinfo"]["message"].format(
subreddit=subreddit,
submission_info=submission_info,
transcription_info=transcription_info,
volunteer_info=volunteer_info,
)
22 changes: 22 additions & 0 deletions blossom/api/slack/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
BOLD_REGEX = re.compile(r"\*(?P<content>[^*]+)\*")

USERNAME_REGEX = re.compile(r"(?:/?u/)?(?P<username>\S+)")
SUBREDDIT_REGEX = re.compile(r"(?:/?r/)?(?P<subreddit>\S+)")


def extract_text_from_link(text: str) -> str:
Expand Down Expand Up @@ -56,6 +57,27 @@ def extract_link(m: Match) -> str:
return text


def parse_subreddit(text: str) -> str:
"""Parse a subreddit argument of a Slack command to the name of the sub (without prefix).
This takes care of link formatting, bold formatting and the r/ prefix.
"""
# Remove link formatting
subreddit = extract_text_from_link(text)

# Remove bold formatting
bold_match = BOLD_REGEX.match(subreddit)
if bold_match:
subreddit = bold_match.group("content")

# Remove u/ prefix
prefix_match = SUBREDDIT_REGEX.match(subreddit)
if prefix_match:
subreddit = prefix_match.group("subreddit")

return subreddit


def parse_user(text: str) -> Tuple[Optional[BlossomUser], str]:
"""Parse a username argument of a Slack command to a user object.
Expand Down
21 changes: 20 additions & 1 deletion blossom/strings/en_US.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ Help is on the way!
`@Blossom info <username>`: Get information about a user.
`@Blossom migrate <source> <target>`: Creates a request to migrate the gamma count of the source to the target. Needs verification.
`@Blossom reset <username>`: Toggle CoC status of user.
`@Blossom subinfo <subreddit>`: Get information about the given subreddit.
`@Blossom submissions`: Get all submissions from a given date range.
`@Blossom unclaim <url>`: Forcibly unclaim the post with the given Reddit URL from the user.
`@Blossom unwatch <username>`: Reset check percentage.
Expand All @@ -68,8 +69,10 @@ message_parse_error="Sorry, something went wrong and I couldn't parse your messa
empty_message_error="Sorry, I wasn't able to get text out of that. Try again."
too_many_params="Too many parameters; please try again."
missing_username="I don't see a username in your request -- make sure you're formatting your request as \"@Blossom {action} {argument}\". Example: \"@Blossom dadjoke @itsthejoker\""
missing_subreddit="I don't see a subreddit in your request -- make sure you're formatting your request as \"@Blossom {action} {argument}\""
missing_multiple_usernames="This command uses multiple usernames -- make sure you're formatting your command as \"@Blossom {action} {argument} {argument} ...\"."
unknown_username="Sorry, I couldn't find a user with the name `u/{username}`. Please check your spelling."
unknown_subreddit="Sorry, there is no subreddit `r/{subreddit}` in our system. Please check your spelling (case-insensitive)."
unknown_payload="Received unknown payload from Slack with key I don't recognize. Unknown key: {}"
invalid_url="Sorry, `{url}` is not a valid Reddit URL. Please provide a Reddit link to a ToR post, partner post or transcription."

Expand Down Expand Up @@ -116,4 +119,20 @@ warnings="u/{username} has *{count} warning(s)*:\n\n{warning_list}"
no_warnings="u/{username} does not have a warning yet!"

[slack.submissions]
no_submissions="Sorry, no submissions were returned for *{username}* in the date range of *{start}* to *{end}*."
no_submissions="Sorry, no submissions were returned for *{username}* in the date range of *{start}* to *{end}*."

[slack.subinfo]
message="""Info about *<https://reddit.com/r/{subreddit}|r/{subreddit}>*:
{submission_info}
{transcription_info}
{volunteer_info}"""
submission_info="""*Submissions*:
- Total: {total_sub:,g} ({total_percentage:.2%} of submissions)
- Queue: {queue_sub:,g} ({queue_percentage:.2%} of queue)"""
transcription_info="""*Transcriptions*:
- Total: {transcribed_sub:,g} ({transcribed_percentage_transcriptions:.2%} of transcriptions, {transcribed_percentage_sub_submissions:.2%} of sub submissions)"""
volunteer_info="""*Volunteers*:
- Total: {volunteers_sub:,g} ({volunteer_percentage:.2%} of volunteers)"""

0 comments on commit cc294cc

Please sign in to comment.