fix(commands:peeringdb|Network): fix timeout

This commit is contained in:
Romain J 2021-04-23 00:52:23 +02:00
parent 2e7934148e
commit 5b7c905ac8
4 changed files with 75 additions and 78 deletions

View file

@ -130,7 +130,7 @@ class Logs(commands.Cog):
dt = datetime.datetime.utcfromtimestamp(record.created) dt = datetime.datetime.utcfromtimestamp(record.created)
msg = ( msg = (
f"{emoji} `[{dt:%Y-%m-%d %H:%M:%S}] " f"{emoji} `[{dt:%Y-%m-%d %H:%M:%S}] "
f"{await shorten(self.bot.session, record.msg, 1500)}`" f"{await shorten(record.msg, 1500)}`"
) )
await self.webhook("gateway").send(msg) await self.webhook("gateway").send(msg)

View file

@ -134,19 +134,18 @@ async def get_ipinfo_result(apikey: str, ip: str) -> dict:
cache=Cache.MEMORY, cache=Cache.MEMORY,
namespace="network", namespace="network",
) )
async def get_crimeflare_result( async def get_crimeflare_result(ip: str) -> Optional[str]:
session: aiohttp.ClientSession, ip: str
) -> Optional[str]:
try: try:
async with session.post( async with aiohttp.ClientSession() as cs:
"http://www.crimeflare.org:82/cgi-bin/cfsearch.cgi", async with cs.post(
data=f"cfS={ip}", "http://www.crimeflare.org:82/cgi-bin/cfsearch.cgi",
timeout=aiohttp.ClientTimeout(total=15), data=f"cfS={ip}",
) as s: timeout=aiohttp.ClientTimeout(total=21),
result = re.search(r"(\d*\.\d*\.\d*\.\d*)", await s.text()) ) as s:
result = re.search(r"(\d*\.\d*\.\d*\.\d*)", await s.text())
if result: if result:
return result.group() return result.group()
except (aiohttp.ClientError, asyncio.exceptions.TimeoutError): except (aiohttp.ClientError, asyncio.exceptions.TimeoutError):
pass pass
@ -223,15 +222,14 @@ async def get_pydig_result(
cache=Cache.MEMORY, cache=Cache.MEMORY,
namespace="network", namespace="network",
) )
async def get_peeringdb_net_result( async def get_peeringdb_net_result(asn: str) -> dict:
session: aiohttp.ClientSession, asn: str
) -> dict:
try: try:
async with session.get( async with aiohttp.ClientSession() as cs:
f"https://peeringdb.com/api/net?asn={asn}", async with cs.get(
timeout=aiohttp.ClientTimeout(total=8), f"https://peeringdb.com/api/net?asn={asn}",
) as s: timeout=aiohttp.ClientTimeout(total=21),
return await s.json() ) as s:
return await s.json()
except (asyncio.exceptions.TimeoutError,): except (asyncio.exceptions.TimeoutError,):
pass pass

View file

@ -143,9 +143,7 @@ class Network(commands.Cog):
ctx: ContextPlus, ctx: ContextPlus,
ip: DomainConverter, ip: DomainConverter,
): ):
crimeflare_result = await get_crimeflare_result( crimeflare_result = await get_crimeflare_result(str(ip))
self.bot.session, str(ip)
)
if crimeflare_result: if crimeflare_result:
alt_ctx = await copy_context_with( alt_ctx = await copy_context_with(
@ -175,38 +173,39 @@ class Network(commands.Cog):
"5": 0x343A40, "5": 0x343A40,
} }
async with self.bot.session.get( async with aiohttp.ClientSession() as cs:
str(ip), async with cs.get(
headers=headers, str(ip),
timeout=aiohttp.ClientTimeout(total=8), headers=headers,
) as s: timeout=aiohttp.ClientTimeout(total=8),
e = discord.Embed( ) as s:
title=f"Headers : {ip}", e = discord.Embed(
color=colors.get(str(s.status)[0], 0x6C757D), title=f"Headers : {ip}",
) color=colors.get(str(s.status)[0], 0x6C757D),
e.add_field( )
name="Status", value=f"```{s.status}```", inline=True e.add_field(
) name="Status", value=f"```{s.status}```", inline=True
e.set_thumbnail(url=f"https://http.cat/{s.status}") )
e.set_thumbnail(url=f"https://http.cat/{s.status}")
headers = dict(s.headers.items()) headers = dict(s.headers.items())
headers.pop("Set-Cookie", headers) headers.pop("Set-Cookie", headers)
fail = False fail = False
for key, value in headers.items(): for key, value in headers.items():
fail, output = await shorten(ctx.session, value, 50, fail) fail, output = await shorten(value, 50, fail)
if output["link"]: if output["link"]:
value = _( value = _(
"[show all]({})", ctx, self.bot.config "[show all]({})", ctx, self.bot.config
).format(output["link"]) ).format(output["link"])
else: else:
value = f"```\n{output['text']}```" value = f"```\n{output['text']}```"
e.add_field(name=key, value=value, inline=True) e.add_field(name=key, value=value, inline=True)
await ctx.send(embed=e) await ctx.send(embed=e)
except ( except (
ClientConnectorError, ClientConnectorError,
InvalidURL, InvalidURL,
@ -260,25 +259,26 @@ class Network(commands.Cog):
@command_extra(name="isdown", aliases=["is_down", "down?"], deletable=True) @command_extra(name="isdown", aliases=["is_down", "down?"], deletable=True)
async def _isdown(self, ctx: ContextPlus, domain: IPConverter): async def _isdown(self, ctx: ContextPlus, domain: IPConverter):
try: try:
async with self.bot.session.get( async with aiohttp.ClientSession() as cs:
f"https://isitdown.site/api/v3/{domain}", async with cs.get(
timeout=aiohttp.ClientTimeout(total=8), f"https://isitdown.site/api/v3/{domain}",
) as s: timeout=aiohttp.ClientTimeout(total=8),
json = await s.json() ) as s:
json = await s.json()
if json["isitdown"]: if json["isitdown"]:
title = _("Down...", ctx, self.bot.config) title = _("Down...", ctx, self.bot.config)
color = 0xDC3545 color = 0xDC3545
else: else:
title = _("Up!", ctx, self.bot.config) title = _("Up!", ctx, self.bot.config)
color = 0x28A745 color = 0x28A745
e = discord.Embed(title=title, color=color) e = discord.Embed(title=title, color=color)
e.set_thumbnail( e.set_thumbnail(
url=f"https://http.cat/{json['response_code']}" url=f"https://http.cat/{json['response_code']}"
) )
await ctx.send(embed=e) await ctx.send(embed=e)
except ( except (
ClientConnectorError, ClientConnectorError,
@ -297,9 +297,7 @@ class Network(commands.Cog):
async def _peeringdb(self, ctx: ContextPlus, asn: ASConverter): async def _peeringdb(self, ctx: ContextPlus, asn: ASConverter):
check_asn_or_raise(str(asn)) check_asn_or_raise(str(asn))
data: dict = ( data: dict = (await get_peeringdb_net_result(str(asn)))["data"]
await get_peeringdb_net_result(self.bot.session, str(asn))
)["data"]
if not data: if not data:
return await ctx.send( return await ctx.send(
@ -344,7 +342,7 @@ class Network(commands.Cog):
) )
if data["notes"]: if data["notes"]:
output = (await shorten(self.bot.session, data["notes"], 550))[1] output = (await shorten(data["notes"], 550))[1]
e.description = output["text"] e.description = output["text"]
if data["created"]: if data["created"]:
e.timestamp = datetime.strptime( e.timestamp = datetime.strptime(

View file

@ -28,7 +28,7 @@ def typing(func):
async def shorten( async def shorten(
session, text: str, length: int, fail: bool = False text: str, length: int, fail: bool = False
) -> tuple[bool, dict]: ) -> tuple[bool, dict]:
output: Dict[str, str] = {"text": text[:length], "link": ""} output: Dict[str, str] = {"text": text[:length], "link": ""}
@ -37,14 +37,15 @@ async def shorten(
if not fail: if not fail:
try: try:
async with session.post( async with aiohttp.ClientSession() as cs:
"https://paste.ramle.be/documents", async with cs.post(
data=text.encode(), "https://paste.ramle.be/documents",
timeout=aiohttp.ClientTimeout(total=0.300), data=text.encode(),
) as r: timeout=aiohttp.ClientTimeout(total=0.300),
output[ ) as r:
"link" output[
] = f"https://paste.ramle.be/{(await r.json())['key']}" "link"
] = f"https://paste.ramle.be/{(await r.json())['key']}"
except (aiohttp.ClientError, asyncio.exceptions.TimeoutError): except (aiohttp.ClientError, asyncio.exceptions.TimeoutError):
fail = True fail = True