Browse Source

basic idea of merging zkill/killstream (using common function to generate embeds -> less duplicated code)

pull/1/head
sirgje 3 years ago
parent
commit
77e213e306
No known key found for this signature in database GPG Key ID: 9F326B1EC4A97073
  1. 1
      bot.py
  2. 57
      cogs/killstream.py
  3. 147
      cogs/zkill.py

1
bot.py

@ -40,7 +40,6 @@ initial_cogs = (
"cogs.memberjoin",
"cogs.eft",
"cogs.killstream",
"cogs.zkill",
"cogs.units",
"cogs.esiprice",
)

57
cogs/killstream.py

@ -2,7 +2,11 @@ import asyncio
import json
import hashlib
import logging
import re
from discord.errors import Forbidden
import aiohttp
import pendulum
from discord import DMChannel
from discord.ext import tasks, commands
from discord.colour import Color
from discord.embeds import Embed
@ -61,6 +65,11 @@ class Killstream(commands.Cog):
await self.bot.redis.execute(
"expire", kill_key, 60 * 30
) # Expire after an 30mins to save space
e = await self.generate_killmail_embed(losstype, killpackage)
announce_chan = get(self.bot.get_all_channels(), id=channel)
return await announce_chan.send(embed=e)
async def generate_killmail_embed(self, losstype, killpackage) -> Embed:
e = Embed(
title=f"{losstype} Alert",
url=f'https://zkillboard.com/kill/{killpackage["killmail_id"]}/',
@ -151,8 +160,7 @@ class Killstream(commands.Cog):
e.set_footer(
text=f"killed {pendulum.parse(killpackage['killmail_time']).diff_for_humans()}"
)
announce_chan = get(self.bot.get_all_channels(), id=channel)
return await announce_chan.send(embed=e)
return e
def __kill_key(self, kill_id, channel_id):
hash = hashlib.md5()
@ -344,6 +352,51 @@ class Killstream(commands.Cog):
async def before_killstream(self):
await self.bot.wait_until_ready()
@commands.Cog.listener()
async def on_message(self, message):
# need a permission system to delete other people's messages
if not message.guild:
return
# we are only interested in single killmails for now, battle reports will still rely on zkill for the embed
r = re.findall("https?://zkillboard.com/kill/\d+", message.content)
if not r:
return
for found in r:
report = await message.channel.send("Loading...")
k = re.match(
"(?P<url>https?://zkillboard.com)/kill/(?P<killid>\d+)/?", found
)
killid = k.group("killid").strip("/")
try:
# Fetch killmail information from zKill
async with self.bot.session.get("https://zkillboard.com/api/killID/{}/".format(killid)) as resp:
text = await resp.text()
zkb = json.loads(text)[0]
# Fetch killmail data from ESI
km = await self.bot.esi.kill_lookup(kill_id=killid, kill_hash=zkb["zkb"]["hash"])
km["zkb"] = zkb["zkb"]
e = await self.generate_killmail_embed('Kill', km)
e.colour = Color.from_rgb(0, 0, 0) # make it black cuz why not
await report.edit(content=None, embed=e)
# if we dont suppress the original embed right away (before an embed exists maybe?)
# then it shouldnt get suck being present and has the added bonus of keeping the original
# embed should ours fail to generate
try:
await message.edit(suppress=True)
except Forbidden:
await report.edit(
content="To avoid the double post, give me the manage_messages permission "
"and I can suppress the original zkill embed :)",
embed=e,
)
except:
await report.delete()
def setup(bot):
bot.add_cog(Killstream(bot))

147
cogs/zkill.py

@ -1,147 +0,0 @@
import logging
import aiohttp
import re
from discord.ext import commands
from discord import DMChannel
from discord.colour import Color
from discord.embeds import Embed
from discord.errors import Forbidden
import pendulum
log = logging.getLogger(__name__)
class Zkill(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
if (
type(message.channel) == DMChannel
): # can't delete embeds in dm's so dont try
return
# we are only interested in single killmails for now, battle reports will still rely on zkill for the embed
r = re.findall("https?://zkillboard.com/kill/\d+", message.content)
if r:
for found in r:
report = await message.channel.send("Loading...")
k = re.match(
"(?P<url>https?://zkillboard.com)/kill/(?P<killid>\d+)/?", found
)
killid = k.group("killid").strip("/")
async with aiohttp.ClientSession() as session:
async with session.get(
"https://zkillboard.com/api/killID/{}/".format(killid)
) as resp:
try:
zkb = await resp.json()
except aiohttp.client_exceptions.ContentTypeError:
await report.delete()
return
km = await self.bot.esi.kill_lookup(
kill_id=killid, kill_hash=zkb[0]["zkb"]["hash"]
)
e = Embed(
title="Killmail Report",
url=f"https://zkillboard.com/kill/{killid}/",
)
e.set_thumbnail(
url=f"https://imageserver.eveonline.com/Render/{km['victim']['ship_type_id']}_64.png"
)
try:
vic_name_sheet = await self.bot.esi.character_sheet(
character_id=km["victim"]["character_id"]
)
except KeyError:
# no char id means a corp lost an asset, set name to blank for a cheap ez fix
vic_name_sheet = {"name": ""}
vic_corp_sheet = await self.bot.esi.corporation_sheet(
corporation_id=km["victim"]["corporation_id"]
)
affiliation_name = f"**{vic_corp_sheet['name']}**"
if "alliance_id" in km["victim"]:
vic_alliance_sheet = await self.bot.esi.alliance_sheet(
alliance_id=km["victim"]["alliance_id"]
)
affiliation_name = (
f"{vic_corp_sheet['name']}, **{vic_alliance_sheet['name']}**"
)
ship_info = await self.bot.esi.ship_info(
ship_id=km["victim"]["ship_type_id"]
)
# THREE ESI CALLS FOR REGION KILL ME
sysinfo = await self.bot.esi.system_info(
system_id=km["solar_system_id"]
)
constellation = await self.bot.esi.constellation_info(
constellation_id=sysinfo["constellation_id"]
)
region = await self.bot.esi.region_info(
region_id=constellation["region_id"]
)
e.description = "{victim} ({affiliation_info}) lost their {ship} in {system} ({region})".format(
victim=vic_name_sheet["name"],
affiliation_info=affiliation_name,
ship=ship_info["name"],
system=sysinfo["name"],
region=region["name"],
)
for killer in km["attackers"]:
if killer["final_blow"] and "character_id" in killer:
killer_name_sheet = await self.bot.esi.character_sheet(
character_id=killer["character_id"]
)
killer_corp_sheet = await self.bot.esi.corporation_sheet(
corporation_id=killer["corporation_id"]
)
affiliation_name = f"**{killer_corp_sheet['name']}**"
if "alliance_id" in killer:
killer_alliance_sheet = await self.bot.esi.alliance_sheet(
alliance_id=killer["alliance_id"]
)
affiliation_name = f"{killer_corp_sheet['name']}, **{killer_alliance_sheet['name']}**"
killer_ship_info = await self.bot.esi.ship_info(
ship_id=killer["ship_type_id"]
)
e.description += "\nFinal blow by {killer} ({affiliation_name}) flying a {ship}".format(
killer=killer_name_sheet["name"],
affiliation_name=affiliation_name,
ship=killer_ship_info["name"],
)
break
e.add_field(
name="Total Value", value=f'{zkb[0]["zkb"]["totalValue"]:,.2f}'
)
e.add_field(name="Total Attackers", value=len(km["attackers"]))
e.set_footer(
text=f"killed {pendulum.parse(km['killmail_time']).diff_for_humans()}"
)
e.colour = Color.from_rgb(0, 0, 0) # make it black cuz why not
await report.edit(content=None, embed=e)
# if we dont suppress the original embed right away (before an embed exists maybe?)
# then it shouldnt get suck being present and has the added bonus of keeping the original
# embed should ours fail to generate
try:
await message.edit(suppress=True)
except Forbidden:
await report.edit(
content="To avoid the double post, give me the manage_messages permission "
"and I can suppress the original zkill embed :)",
embed=e,
)
return
def setup(bot):
bot.add_cog(Zkill(bot))
Loading…
Cancel
Save