Skip to content

Commit

Permalink
[Runesca[e 1.5.2 Update Runemetrics autopost formatting
Browse files Browse the repository at this point in the history
- Humanize number on the xp in runemetrics posts.
- Flesh out the embed using title, description, and author if embeds are allowed.
- Hide the metrics url with the author in the embed which makes more sense.
closes #335
  • Loading branch information
TrustyJAID committed May 30, 2024
1 parent a4ca5de commit b284200
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 47 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ TrustyJAID's Cogs for [Red-DiscordBot](https://github.com/Cog-Creators/Red-Disc
| Rekt | 1.0.0 | <details><summary>Get REKT</summary>Are you REKT?</details> | TrustyJAID |
| ReTrigger | 2.28.2 | <details><summary>Trigger events via Regular Expressions!</summary>Trigger events based on regex! Check out <https://regex101.com/> and <https://github.com/TrustyJAID/Trusty-cogs/blob/master/retrigger/README.md> for help setting up the cog. Note: This cog can become quite resource heavy. Optional features are available if the requirements are present such as pillow for image resizing and pytesseract to scan images for text (OCR).</details> | TrustyJAID |
| RoleTools | 1.5.12 | <details><summary>Various role related tools.</summary>Various role utility commands. Including Reaction roles, Sticky roles, and Auto role.</details> | TrustyJAID |
| runescape | 1.5.1 | <details><summary>Show your Runescape stats in discord!</summary>A cog to grab Runescape and OSRS stats and profile information.</details> | TrustyJAID |
| runescape | 1.5.2 | <details><summary>Show your Runescape stats in discord!</summary>A cog to grab Runescape and OSRS stats and profile information.</details> | TrustyJAID |
| ServerStats | 1.8.0 | <details><summary>A plethora of potentially useful commands for any bot owner.</summary>A plethora of potentially useful commands for any bot owner. Includes a way to track the bot joining new servers, find cheaters on global economies, get user avatars and even larger emojis.</details> | TrustyJAID and Preda |
| Spotify | 1.7.3 | <details><summary>Control Spotify through Discord!</summary>This cog allows you to control Spotify via OAuth through the bot on discord. Use `[p]spotify` to see available commands.</details> | TrustyJAID and NeuroAssassin |
| Starboard | 2.6.0 | <details><summary>Starboard</summary>Create a starboard channel to save those amazing posts!</details> | TrustyJAID |
Expand Down
70 changes: 64 additions & 6 deletions runescape/profile.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import json
import re
from collections import deque
from dataclasses import dataclass
from datetime import datetime
Expand All @@ -14,11 +15,16 @@
from redbot.core.utils.chat_formatting import humanize_number, pagify
from tabulate import tabulate

from .helpers import HEADERS
from .helpers import HEADERS, IMAGE_URL
from .xp import ELITE_XP, XP_TABLE

log = getLogger("red.trusty-cogs.runescape")

LVL_RE = re.compile(r"Levelled Up (\w+)", flags=re.I)
XP_RE = re.compile(r"(?P<xp>\d+)XP IN (.+)", flags=re.I)
KILLED_RE = re.compile(r"(?:I )?(?:killed|defeated) (?:\d+ |the )?([a-z \-,]+)", flags=re.I)
FOUND_RE = re.compile(r"I found (?:a pair of|some|a|an) (.+)", flags=re.I)


class APIError(Exception):
pass
Expand Down Expand Up @@ -188,6 +194,52 @@ def from_json(cls, data: dict):
id=activity_id,
)

def _get_image_details_text(self):
text = self.text
details = self.details
image_url = None
page = None
if match := KILLED_RE.search(self.text):
page = match.group(1).strip()
if page.endswith("s"):
page = page[:-1]
page = page.replace(" ", "_")
if "-" in page:
page = page.title()
else:
page = page.capitalize()
image_url = IMAGE_URL + page + ".png"
if match := XP_RE.search(self.text):
page = match.group(2).strip()
if xp := match.group("xp"):
number = humanize_number(int(xp))
text = self.text.replace(xp, number)
details = self.details.replace(xp, number)
image_url = IMAGE_URL + page.replace(" ", "_").capitalize() + ".png"
if match := LVL_RE.search(self.text):
page = match.group(1).strip()
image_url = IMAGE_URL + page.replace(" ", "_").capitalize() + ".png"
if match := FOUND_RE.search(self.text):
page = match.group(1).strip() + " detail"
image_url = IMAGE_URL + page.replace(" ", "_").capitalize() + ".png"
return text, details, image_url

def format_text(self, profile: Profile) -> str:
text, details, image_url = self._get_image_details_text()
ts = discord.utils.format_dt(self.date)
return f"{profile.name}: {text}\n{details}\n\n{ts}"

def embed(self, profile: Profile) -> discord.Embed:
url = f"https://apps.runescape.com/runemetrics/app/overview/player/{profile.name}"
# msg = f"{profile.name}: {activity.text}\n{activity.details}\n\n"
ts = discord.utils.format_dt(self.date)
text, details, image_url = self._get_image_details_text()
embed = discord.Embed(title=text, description=f"{details}\n\n{ts}")
embed.set_author(name=profile.name, url=profile.metrics, icon_url=profile.avatar)
if image_url is not None:
embed.set_thumbnail(url=image_url)
return embed


class Activities:
def __init__(self, *args, **kwargs):
Expand Down Expand Up @@ -354,6 +406,16 @@ def __str__(self):
skills_list.append([skill.name, level, humanize_number(xp), rank])
return tabulate(skills_list, headers=["Skill", "Level", "Experience", "Rank"])

@property
def avatar(self):
return "http://secure.runescape.com/m=avatar-rs/{}/chat.png".format(
self.name.replace(" ", "%20")
)

@property
def metrics(self):
return f"https://apps.runescape.com/runemetrics/app/overview/player/{self.name}"

def stats_table(self) -> str:
table = str(self)
top_row_len = len(table.split("\n")[1])
Expand All @@ -377,11 +439,7 @@ async def embed(self, details: Optional[PlayerDetails] = None) -> discord.Embed:
activities += f"[<t:{int(activity.date.timestamp())}>] {activity.details}\n"

# em.colour = int(teams[_teams.name]["home"].replace("#", ""), 16)
em.set_thumbnail(
url="http://secure.runescape.com/m=avatar-rs/{}/chat.png".format(
self.name.replace(" ", "%20")
)
)
em.set_thumbnail(url=self.avatar)
em.add_field(name="Combat Level", value=self.combatlevel)
em.add_field(name="Total Level", value=humanize_number(self.totalskill))
em.add_field(name="Total XP", value=humanize_number(self.totalxp))
Expand Down
46 changes: 6 additions & 40 deletions runescape/runescape.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import re
from datetime import datetime, timedelta, timezone
from typing import Dict, Literal, Optional

Expand All @@ -10,7 +9,6 @@
from redbot.core.bot import Red
from redbot.core.utils.chat_formatting import box

from .helpers import IMAGE_URL
from .menus import BaseMenu, GEChartPages, GESinglePages
from .profile import (
Activities,
Expand All @@ -29,19 +27,13 @@
log = getLogger("red.trusty-cogs.runescape")


LVL_RE = re.compile(r"Levelled Up (\w+)", flags=re.I)
XP_RE = re.compile(r"\d+XP IN (.+)", flags=re.I)
KILLED_RE = re.compile(r"(?:I )?(?:killed|defeated) (?:\d+ |the )?([a-z \-,]+)", flags=re.I)
FOUND_RE = re.compile(r"I found (?:a pair of|some|a|an) (.+)", flags=re.I)


class Runescape(commands.Cog):
"""
Display Runescape account info
"""

__author__ = ["TrustyJAID"]
__version__ = "1.5.1"
__version__ = "1.5.2"

def __init__(self, bot):
self.bot: Red = bot
Expand Down Expand Up @@ -117,48 +109,22 @@ async def check_new_metrics(self):
async def post_activity(
self, profile: Profile, channels: Dict[str, int], activity: Activity
) -> None:
url = f"https://apps.runescape.com/runemetrics/app/overview/player/{profile.name}"
msg = f"{profile.name}: {activity.text}\n{activity.details}\n\n"
image_url = None
page = None
if match := KILLED_RE.search(activity.text):
page = match.group(1).strip()
if page.endswith("s"):
page = page[:-1]
page = page.replace(" ", "_")
if "-" in page:
page = page.title()
else:
page = page.capitalize()
image_url = IMAGE_URL + page + ".png"
if match := XP_RE.search(activity.text):
page = match.group(1).strip()
image_url = IMAGE_URL + page.replace(" ", "_").capitalize() + ".png"
if match := LVL_RE.search(activity.text):
page = match.group(1).strip()
image_url = IMAGE_URL + page.replace(" ", "_").capitalize() + ".png"
if match := FOUND_RE.search(activity.text):
page = match.group(1).strip() + " detail"
image_url = IMAGE_URL + page.replace(" ", "_").capitalize() + ".png"
embed = activity.embed(profile)
text = activity.format_text(profile)

for channel_id, guild_id in channels.items():
guild = self.bot.get_guild(guild_id)
if not guild:
continue
channel = guild.get_channel(int(channel_id))
if not channel:
if not channel or isinstance(channel, (discord.ForumChannel, discord.CategoryChannel)):
continue
if not channel.permissions_for(guild.me).send_messages:
continue
if channel.permissions_for(guild.me).embed_links:
em = discord.Embed(
description=f"[{msg}]({url})\n\n" + discord.utils.format_dt(activity.date)
)
if image_url:
em.set_thumbnail(url=image_url)
await channel.send(embed=em)
await channel.send(embed=embed)
else:
await channel.send(msg + "\n\n" + discord.utils.format_dt(activity.date))
await channel.send(text)

@check_new_metrics.before_loop
async def before_checking_metrics(self):
Expand Down

0 comments on commit b284200

Please sign in to comment.