fix(commands:peeringdb|Network): fix false results

This commit is contained in:
Romain J 2021-04-23 23:47:35 +02:00
parent 5b7c905ac8
commit b9f6c6cb0a
2 changed files with 43 additions and 11 deletions

View file

@ -223,18 +223,39 @@ async def get_pydig_result(
namespace="network", namespace="network",
) )
async def get_peeringdb_net_result(asn: str) -> dict: async def get_peeringdb_net_result(asn: str) -> dict:
# Q. why this and not ?asn=
# A. better do one request and save in cache than execute new
# request every time
@cached(
ttl=24 * 3600,
serializer=PickleSerializer(),
cache=Cache.MEMORY,
namespace="network",
)
async def _local_cache() -> dict:
try: try:
async with aiohttp.ClientSession() as cs: async with aiohttp.ClientSession() as cs:
async with cs.get( async with cs.get(
f"https://peeringdb.com/api/net?asn={asn}", "https://peeringdb.com/api/net",
timeout=aiohttp.ClientTimeout(total=21), timeout=aiohttp.ClientTimeout(total=21),
) as s: ) as s:
return await s.json() return await s.json()
except (asyncio.exceptions.TimeoutError,): except asyncio.exceptions.TimeoutError:
pass pass
return {"data": []} return {"data": []}
result = await _local_cache()
if not result["data"]:
return result
for data in result["data"]:
if data.get("asn", None) == int(asn):
return {"data": [data]}
return {"data": []}
def check_ip_version_or_raise(version: str) -> bool | NoReturn: def check_ip_version_or_raise(version: str) -> bool | NoReturn:
if version in ("4", "6", "None"): if version in ("4", "6", "None"):

View file

@ -8,7 +8,7 @@ import aiohttp
import discord import discord
from aiohttp import ClientConnectorError, InvalidURL from aiohttp import ClientConnectorError, InvalidURL
from jishaku.models import copy_context_with from jishaku.models import copy_context_with
from discord.ext import commands from discord.ext import commands, tasks
from ipinfo.exceptions import RequestQuotaExceededError from ipinfo.exceptions import RequestQuotaExceededError
from structured_config import ConfigFile from structured_config import ConfigFile
from tuxbot.cogs.Network.functions.converters import ( from tuxbot.cogs.Network.functions.converters import (
@ -62,6 +62,7 @@ class Network(commands.Cog):
str(cogs_data_path("Network") / "config.yaml"), str(cogs_data_path("Network") / "config.yaml"),
NetworkConfig, NetworkConfig,
).config ).config
self._update_peering_db.start() # pylint: disable=no-member
async def cog_command_error(self, ctx: ContextPlus, error): async def cog_command_error(self, ctx: ContextPlus, error):
if isinstance( if isinstance(
@ -81,6 +82,16 @@ class Network(commands.Cog):
async def cog_before_invoke(self, ctx: ContextPlus): async def cog_before_invoke(self, ctx: ContextPlus):
await ctx.trigger_typing() await ctx.trigger_typing()
def cog_unload(self):
self._update_peering_db.cancel() # pylint: disable=no-member
@tasks.loop(hours=24.0)
async def _update_peering_db(self):
await get_peeringdb_net_result(str(1))
logging.log(logging.INFO, "_update_peering_db")
self.bot.console.log("[Network]: _update_peering_db")
# ========================================================================= # =========================================================================
# ========================================================================= # =========================================================================
@ -349,4 +360,4 @@ class Network(commands.Cog):
data["created"], "%Y-%m-%dT%H:%M:%SZ" data["created"], "%Y-%m-%dT%H:%M:%SZ"
) )
await ctx.send(embed=e) await ctx.send(f"https://www.peeringdb.com/net/{data['id']}", embed=e)