Skip to content

Commit

Permalink
Merge pull request #363 from HullSeals/enhancement/halpy-361
Browse files Browse the repository at this point in the history
[Halpy-361] Update multiple dispatch commands to be able to use caseIDs and co
  • Loading branch information
Rixxan authored May 14, 2024
2 parents 4ecc364 + d23d59e commit 21faaa7
Show file tree
Hide file tree
Showing 5 changed files with 120 additions and 57 deletions.
8 changes: 4 additions & 4 deletions data/help/commands.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"aliases": [
"syslookup"
],
"arguments": "[System Name]",
"arguments": "[System/CMDR/caseID]",
"use": "Check if a system exists in EDSM"
},
"locate": {
Expand All @@ -24,17 +24,17 @@
},
"landmark": {
"aliases": [],
"arguments": "[EDSM Valid Location]",
"arguments": "[System/CMDR/caseID]",
"use": "Check if a given point is nearby a given Landmark System"
},
"dssa": {
"aliases": [],
"arguments": "[EDSM Valid Location]",
"arguments": "[System/CMDR/caseID]",
"use": "Check for the closest DSSA carrier to a given location."
},
"diversion": {
"aliases": [],
"arguments": "[EDSM Valid Location]",
"arguments": "[System/CMDR/caseID]",
"use": "Calculate the 5 closest FDEV-placed structures with repair capability to given location."
},
"coords": {
Expand Down
159 changes: 111 additions & 48 deletions halpybot/commands/edsm.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@
from ..packages.case import get_case


async def differentiate(ctx: Context, args: List[str]) -> Points:
async def diff_handler(
ctx: Context, args: List[str], single_arg: bool = False
) -> Points:
"""
Differentiate if a given set of two systems are CMDRs, Cases, or Systems.
Expand All @@ -42,33 +44,47 @@ async def differentiate(ctx: Context, args: List[str]) -> Points:
args (List): A list of arguments from the bot.
Returns:
Points (Points): A Points object containing two Point objects and an optional Jump range
Points (Points): A Points object containing one or two Point objects and an optional Jump range
Raises:
DifferentiateArgsIssue: Arguments are malformed
"""
# Parse System/CMDR/caseID from string
list_to_str = " ".join([str(elem) for elem in args])
list_points: List[str] = list_to_str.split(":")
if len(list_points) < 2:
if single_arg: # Handle single argument commands
if len(list_points): # Point provided
point_a: Point = Point(list_points[0].strip())
points: Points = Points(point_a)
else: # No point provided
await ctx.reply("Please provide a point to look up.")
raise DifferentiateArgsIssue
if not point_a.name: # No point provided
await ctx.reply("Please provide a point to look up.")
raise DifferentiateArgsIssue
elif len(list_points) < 2: # Multi-argument command but less than 2 points provided
await ctx.reply("Please provide two points to look up, separated by a :")
raise DifferentiateArgsIssue
point_a: Point = Point(list_points[0].strip())
point_b: Point = Point(list_points[1].strip())
points: Points = Points(point_a, point_b)
else: # Handle multi-argument command with two points provided
point_a: Point = Point(list_points[0].strip())
point_b: Point = Point(list_points[1].strip())
points: Points = Points(point_a, point_b)
if not point_a.name or not point_b.name: # One or both points are missing
await ctx.reply("Please provide two points to look up, separated by a :")
raise DifferentiateArgsIssue

if not point_a.name or not point_b.name:
await ctx.reply("Please provide two points to look up, separated by a :")
raise DifferentiateArgsIssue
# Differentiate points
points.point_a = await differentiate(ctx=ctx, input=points.point_a.name)
if points.point_b: # Multi-argument command
points.point_b = await differentiate(ctx=ctx, input=points.point_b.name)

# Define Jump Count
if len(list_points) == 3:
try:
# Parse Jump Range if provided
if len(list_points) == 3: # Jump Range provided
try: # Attempt to parse Jump Range
points.jump_range = float(
re.sub("(?i)LY", "", "".join(list_points[2])).strip()
)
except ValueError as val_err:
# Jump Range must not be formatted correctly
except ValueError as val_err: # Jump Range must not be formatted correctly
await ctx.reply(
"The Jump Range must be given as digits with an optional decimal point."
)
Expand All @@ -77,30 +93,43 @@ async def differentiate(ctx: Context, args: List[str]) -> Points:
# Jump Range has values that don't really make sense
await ctx.reply("The Jump Range must be between 10 LY and 500 LY.")
raise DifferentiateArgsIssue

for point in [point_a, point_b]:
# Check if Point is CaseID
try:
case: Case = await get_case(ctx, point.name)
temp_point = case.system
temp_pretty = f"Case {case.board_id} ({case.client_name} in {case.system})"
except KeyError:
temp_point = "".join(point.name).strip()
temp_pretty = await sys_cleaner(point.name)
# Check if point is CMDR
try:
loc_cmdr = await Commander.location(name=point.name)
# Looks like CMDR's back on the menu, boys!
if loc_cmdr and loc_cmdr.system is not None:
temp_point = await sys_cleaner(loc_cmdr.system)
temp_pretty = f"{await sys_cleaner(point.name)} (in {temp_point})"
except EDSMLookupError:
logger.warning("EDSM appears to be down! Trying to continue regardless...")
await ctx.reply("Warning! EDSM appears to be down. Trying to continue.")
point.name, point.pretty = temp_point, temp_pretty
return points


async def differentiate(ctx: Context, input: str) -> Points:
"""
Differentiate if a given input is a CMDR, Case, or System.
Args:
ctx (Context): The Bot Context
input (str): A string to differentiate
Returns:
Point (Point): A Point object containing the system name and a formatted name
"""
point: Point = Point(input)
# Check if Point is CaseID
try:
case: Case = await get_case(ctx, point.name)
temp_point = case.system
temp_pretty = f"Case {case.board_id} ({case.client_name} in {case.system})"
except KeyError:
temp_point = "".join(point.name).strip()
temp_pretty = await sys_cleaner(point.name)
# Check if point is CMDR
try:
loc_cmdr = await Commander.location(name=point.name)
# Looks like CMDR's back on the menu,
if loc_cmdr and loc_cmdr.system is not None:
temp_point = await sys_cleaner(loc_cmdr.system)
temp_pretty = f"{await sys_cleaner(point.name)} (in {temp_point})"
except EDSMLookupError:
logger.warning("EDSM appears to be down! Trying to continue regardless...")
await ctx.reply("Warning! EDSM appears to be down. Trying to continue.")
point.name, point.pretty = temp_point, temp_pretty
return point


@Commands.command("lookup", "syslookup")
@sys_exceptions
async def cmd_systemlookup(ctx: Context, cleaned_sys, cache_override):
Expand All @@ -110,9 +139,19 @@ async def cmd_systemlookup(ctx: Context, cleaned_sys, cache_override):
Usage: !lookup <--new> [system name]
Aliases: syslookup
"""
if await GalaxySystem.exists(name=cleaned_sys, cache_override=cache_override):
return await ctx.reply(f"System {cleaned_sys} exists in EDSM")
return await ctx.reply(f"System {cleaned_sys} not found in EDSM")
try:
# Process provided arguments
points: Points = await diff_handler(
ctx=ctx, args=cleaned_sys.split(), single_arg=True
)
except DifferentiateArgsIssue:
# Arguments were malformed, user has already been informed, abort
return await ctx.reply("Error encountered in Lookup command, not continuing")
if await GalaxySystem.exists(
name=points.point_a.name, cache_override=cache_override
):
return await ctx.reply(f"System {points.point_a.name} exists in EDSM")
return await ctx.reply(f"System {points.point_a.name} not found in EDSM")


@Commands.command("locatecmdr", "cmdrlookup", "locate")
Expand Down Expand Up @@ -143,7 +182,7 @@ async def cmd_distlookup(ctx: Context, args: List[str], cache_override):
"""
try:
# Process provided arguments
points: Points = await differentiate(ctx=ctx, args=args)
points: Points = await diff_handler(ctx=ctx, args=args)
except DifferentiateArgsIssue:
# Arguments were malformed, user has already been informed, abort
return await ctx.reply("Error encountered in Dist command, not continuing")
Expand Down Expand Up @@ -173,21 +212,29 @@ async def cmd_landmarklookup(ctx: Context, cleaned_sys, cache_override):
Usage: !landmark <--new> [system/cmdr]
Aliases: n/a
"""
try:
# Process provided arguments
points: Points = await diff_handler(
ctx=ctx, args=cleaned_sys.split(), single_arg=True
)
except DifferentiateArgsIssue:
# Arguments were malformed, user has already been informed, abort
return await ctx.reply("Error encountered in Landmark command, not continuing")
try:
landmark, distance, direction = await checklandmarks(
edsm_sys_name=cleaned_sys, cache_override=cache_override
edsm_sys_name=points.point_a.name, cache_override=cache_override
)
return await ctx.reply(
f"The closest landmark system is {landmark}, {distance} LY {direction} of {cleaned_sys}."
f"The closest landmark system is {landmark}, {distance} LY {direction} of {points.point_a.pretty}."
)
except NoNearbyEDSM:
dssa, distance, direction = await checkdssa(
edsm_sys_name=cleaned_sys, cache_override=cache_override
edsm_sys_name=points.point_a.name, cache_override=cache_override
)
return await ctx.reply(
f"No major landmark systems within 10,000 LY of {cleaned_sys}.\n"
f"No major landmark systems within 10,000 LY of {points.point_a.pretty}.\n"
f"The closest DSSA Carrier is in {dssa}, {distance} LY "
f"{direction} of {cleaned_sys}."
f"{direction} of {points.point_a.pretty}."
)


Expand All @@ -201,12 +248,20 @@ async def cmd_dssalookup(ctx: Context, cleaned_sys, cache_override):
Aliases: n/a
File Last Updated: 2021-03-22 w/ 93 Carrier
"""
try:
# Process provided arguments
points: Points = await diff_handler(
ctx=ctx, args=cleaned_sys.split(), single_arg=True
)
except DifferentiateArgsIssue:
# Arguments were malformed, user has already been informed, abort
return await ctx.reply("Error encountered in DSSA command, not continuing")
dssa, distance, direction = await checkdssa(
edsm_sys_name=cleaned_sys, cache_override=cache_override
edsm_sys_name=points.point_a.name, cache_override=cache_override
)
return await ctx.reply(
f"The closest DSSA Carrier is in {dssa}, {distance} LY {direction} of "
f"{cleaned_sys}."
f"{points.point_a.pretty}."
)


Expand Down Expand Up @@ -239,11 +294,19 @@ async def cmd_diversionlookup(ctx: Context, cleaned_sys, cache_override):
Aliases: n/a
File Last Updated: 2022-05-23 w/ 7,384 Qualified Stations
"""
try:
# Process provided arguments
points: Points = await diff_handler(
ctx=ctx, args=cleaned_sys.split(), single_arg=True
)
except DifferentiateArgsIssue:
# Arguments were malformed, user has already been informed, abort
return await ctx.reply("Error encountered in Diversion command, not continuing")
first, second, third, fourth, fifth = await diversions(
edsm_sys_name=cleaned_sys, cache_override=cache_override
edsm_sys_name=points.point_a.name, cache_override=cache_override
)
return await ctx.reply(
f"Closest Diversion Stations to {cleaned_sys}:\n"
f"Closest Diversion Stations to {points.point_a.pretty}:\n"
f"1st: {first.name}, {float(first.item):,} LY {first.local_direction} in {first.system_name} "
f"({first.dist_star} LS from entry)\n"
f"2nd: {second.name}, {float(second.item):,} LY {second.local_direction} in {second.system_name} "
Expand Down
4 changes: 2 additions & 2 deletions halpybot/commands/spansh.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from typing import List
from loguru import logger
from halpybot import config
from .edsm import differentiate
from .edsm import diff_handler
from ..packages.exceptions import DifferentiateArgsIssue
from ..packages.utils import spansh, dist_exceptions
from ..packages.command import Commands, get_help_text
Expand All @@ -31,7 +31,7 @@ async def cmd_spansh(ctx: Context, args: List[str], cache_override):
return await ctx.reply("Unable to comply. SPANSH module not enabled.")
try:
# Process provided arguments
points: Points = await differentiate(ctx=ctx, args=args)
points: Points = await diff_handler(ctx=ctx, args=args)
except DifferentiateArgsIssue:
# Arguments were malformed, user has already been informed, abort
return await ctx.reply("Error encountered in Dist command, not continuing")
Expand Down
2 changes: 1 addition & 1 deletion halpybot/halpyconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ class Spansh(BaseModel):

enabled: bool = False
efficiency: int = 60
calculations_timeout: int = 20
calculations_timeout: int = 60
uri: AnyHttpUrl = "https://spansh.co.uk"

@property
Expand Down
4 changes: 2 additions & 2 deletions halpybot/packages/models/edsm_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,8 @@ class Point:

@define()
class Points:
"""A pair of valid EDSM Points"""
"""One or two valid EDSM Points and an optional jump range"""

point_a: Point
point_b: Point
point_b: Optional[Point] = None
jump_range: Optional[float] = None

0 comments on commit 21faaa7

Please sign in to comment.