Skip to content

Commit

Permalink
Merge pull request #192 from vipyrsec/error-handling
Browse files Browse the repository at this point in the history
Add error handling to task
  • Loading branch information
Robin5605 authored Nov 11, 2023
2 parents ba0c602 + 4e1925b commit 08e6eee
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 27 deletions.
2 changes: 2 additions & 0 deletions src/bot/dragonfly_services.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ async def _update_token(self: Self) -> None:
"password": self.password,
}
async with self.session.post(self.auth_url, json=auth_dict) as response:
response.raise_for_status()
data = await response.json()
self.token = data["access_token"]
self.token_expires_at = datetime.now(tz=UTC) + timedelta(seconds=data["expires_in"])
Expand Down Expand Up @@ -124,6 +125,7 @@ async def make_request(
args["json"] = json

async with self.session.request(**args) as response:
response.raise_for_status()
return await response.json()

async def get_scanned_packages(
Expand Down
43 changes: 16 additions & 27 deletions src/bot/exts/dragonfly/dragonfly.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import aiohttp
import discord
import sentry_sdk
from discord.ext import commands, tasks

from bot.bot import Bot
Expand Down Expand Up @@ -162,12 +163,12 @@ def _build_all_packages_scanned_embed(scan_results: list[PackageScanResult]) ->
async def run(
bot: Bot,
*,
since: datetime,
alerts_channel: discord.abc.Messageable,
logs_channel: discord.abc.Messageable,
score: int,
) -> None:
"""Script entrypoint."""
since = datetime.now(tz=UTC) - timedelta(seconds=DragonflyConfig.interval)
scan_results = await bot.dragonfly_services.get_scanned_packages(since=since)
for result in scan_results:
if result.score >= score:
Expand All @@ -188,6 +189,7 @@ def __init__(self: Self, bot: Bot) -> None:
"""Initialize the Dragonfly cog."""
self.bot = bot
self.score_threshold = DragonflyConfig.threshold
self.since = datetime.now(tz=UTC) - timedelta(seconds=DragonflyConfig.interval)
super().__init__()

@tasks.loop(seconds=DragonflyConfig.interval)
Expand All @@ -199,38 +201,25 @@ async def scan_loop(self: Self) -> None:
alerts_channel = self.bot.get_channel(DragonflyConfig.alerts_channel_id)
assert isinstance(alerts_channel, discord.abc.Messageable)

await run(
self.bot,
logs_channel=logs_channel,
alerts_channel=alerts_channel,
score=self.score_threshold,
)
try:
await run(
self.bot,
since=self.since,
logs_channel=logs_channel,
alerts_channel=alerts_channel,
score=self.score_threshold,
)
except Exception as e:
log.exception("An error occured in the scan loop task. Skipping run.")
sentry_sdk.capture_exception(e)
else:
self.since = datetime.now(tz=UTC)

@scan_loop.before_loop
async def before_scan_loop(self: Self) -> None:
"""Wait until the bot is ready."""
await self.bot.wait_until_ready()

@scan_loop.error
async def scan_loop_error(self: Self, exc: BaseException) -> None:
"""Log any errors that occur in the scan loop."""
logs_channel = self.bot.get_channel(DragonflyConfig.logs_channel_id)
assert isinstance(logs_channel, discord.abc.Messageable)

if core_devs_role := logs_channel.guild.get_role(Roles.core_developers):
mention = core_devs_role.mention
else:
mention = ""

embed = discord.Embed(
title="Error in task",
description=f"```{type(exc).__name__}: {exc}```",
color=discord.Color.red(),
)
await logs_channel.send(mention, embed=embed)

raise exc

@commands.has_role(Roles.vipyr_security)
@commands.command()
async def start(self: Self, ctx: commands.Context) -> None:
Expand Down

0 comments on commit 08e6eee

Please sign in to comment.