lint, not full

This commit is contained in:
Sergio Álvarez 2017-12-13 12:37:31 +01:00
parent 1affbdd7a2
commit c48c57f7f0
11 changed files with 360 additions and 343 deletions

View File

@ -1,7 +1,9 @@
#! /usr/bin/python3 #! /usr/bin/python3
"""
Affixes Cron
"""
import datetime import datetime
import time
import webhook import webhook
import conf import conf
@ -11,8 +13,7 @@ week = (int(datetime.datetime.now().strftime("%V")) % len(conf.affix_rotation))
f = [] f = []
for s in conf.affix_rotation[week]: for s in conf.affix_rotation[week]:
f.append(webhook.field("{1} {0}".format(s, conf.affixes[s]), conf.affix_human[s], True)) f.append(webhook.field("{1} {0}".format(s, conf.affixes[s]), conf.affix_human[s], True))
wh.add_embed(webhook.embed(color=0x3f89ff, fields=f)) wh.add_embed(webhook.embed(color=0x3f89ff, fields=f))
wh.send("**[Affixes de esta semana](<https://mythicpl.us/>)**") wh.send("**[Affixes de esta semana](<https://mythicpl.us/>)**")
time.sleep(2)

161
conf.py
View File

@ -1,3 +1,6 @@
"""
config module
"""
from tokens import * from tokens import *
@ -9,102 +12,102 @@ icon_warcraftlogs = "<:Warcraftlogs:352756407164076034>"
min_mythic = 15 min_mythic = 15
affixes = { affixes = {
"Bullente": "<:m_teeming:352756406514089994>", "Bullente": "<:m_teeming:352756406514089994>",
"Detonante": "<:m_bursting:352760092397010944>", "Detonante": "<:m_bursting:352760092397010944>",
"Dolorosa": "<:m_grievous:352760092472377344>", "Dolorosa": "<:m_grievous:352760092472377344>",
"Explosiva": "<:m_explosive:352760091981905932>", "Explosiva": "<:m_explosive:352760091981905932>",
"Furibunda": "<:m_raging:352756406492987394>", "Furibunda": "<:m_raging:352756406492987394>",
"Inquieta": "<:m_skittish:352756406497181698>", "Inquieta": "<:m_skittish:352756406497181698>",
"Necrótica": "<:m_necro:352756406333472769>", "Necrótica": "<:m_necro:352756406333472769>",
"Potenciante": "<:m_bolstering:352756406509633536>", "Potenciante": "<:m_bolstering:352756406509633536>",
"Rebosante": "<:m_over:352756406463758337>", "Rebosante": "<:m_over:352756406463758337>",
"Reforzada": "<:m_forti:352756406497050624>", "Reforzada": "<:m_forti:352756406497050624>",
"Sanguina": "<:m_sanguine:352756406153379844>", "Sanguina": "<:m_sanguine:352756406153379844>",
"Sísmica": "<:m_quaking:352760093118300160>", "Sísmica": "<:m_quaking:352760093118300160>",
"Tiránica": "<:m_tyra:352756406279208964>", "Tiránica": "<:m_tyra:352756406279208964>",
"Volcánica": "<:m_volcanic:352756406341992449>" "Volcánica": "<:m_volcanic:352756406341992449>"
} }
affix_human = { affix_human = {
"Bullente": "+ bichos", "Bullente": "+ bichos",
"Detonante": "= Il'gynoth", "Detonante": "= Il'gynoth",
"Dolorosa": "Sangrado 90%", "Dolorosa": "Sangrado 90%",
"Explosiva": "Orbes de mierda", "Explosiva": "Orbes de mierda",
"Furibunda": "Enrage 30%", "Furibunda": "Enrage 30%",
"Inquieta": "- Aggro", "Inquieta": "- Aggro",
"Necrótica": "- Sanación", "Necrótica": "- Sanación",
"Potenciante": "Se buffan al morir", "Potenciante": "Se buffan al morir",
"Rebosante": "Overheal", "Rebosante": "Overheal",
"Reforzada": "Bichos :muscle:", "Reforzada": "Bichos :muscle:",
"Sanguina": "Pozo al morir", "Sanguina": "Pozo al morir",
"Sísmica": "El puto quake", "Sísmica": "El puto quake",
"Tiránica": "Bosses :muscle:", "Tiránica": "Bosses :muscle:",
"Volcánica": "El puto volcanic" "Volcánica": "El puto volcanic"
} }
affix_rotation = [ affix_rotation = [
["Furibunda", "Volcánica", "Tiránica"], ["Furibunda", "Volcánica", "Tiránica"],
["Bullente", "Explosiva", "Reforzada"], ["Bullente", "Explosiva", "Reforzada"],
["Potenciante", "Dolorosa", "Tiránica"], ["Potenciante", "Dolorosa", "Tiránica"],
["Sanguina", "Volcánica", "Reforzada"], ["Sanguina", "Volcánica", "Reforzada"],
["Detonante", "Inquieta", "Tiránica"], ["Detonante", "Inquieta", "Tiránica"],
["Bullente", "Sísmica", "Reforzada"], ["Bullente", "Sísmica", "Reforzada"],
["Furibunda", "Necrótica", "Tiránica"], ["Furibunda", "Necrótica", "Tiránica"],
["Potenciante", "Inquieta", "Reforzada"], ["Potenciante", "Inquieta", "Reforzada"],
["Bullente", "Necrótica", "Tiránica"], ["Bullente", "Necrótica", "Tiránica"],
["Sanguina", "Dolorosa", "Reforzada"], ["Sanguina", "Dolorosa", "Reforzada"],
["Potenciante", "Explosiva", "Tiránica"], ["Potenciante", "Explosiva", "Tiránica"],
["Detonante", "Sísmica", "Reforzada"] ["Detonante", "Sísmica", "Reforzada"]
] ]
zones = { zones = {
"darkheart-thicket": "Arboleda Corazón Oscuro", "darkheart-thicket": "Arboleda Corazón Oscuro",
"court-of-stars": "Corte de las Estrellas", "court-of-stars": "Corte de las Estrellas",
"vault-of-the-wardens": "Cámara de las Celadoras", "vault-of-the-wardens": "Cámara de las Celadoras",
"halls-of-valor": "Cámaras del Valor", "halls-of-valor": "Cámaras del Valor",
"maw-of-souls": "Fauce de Almas", "maw-of-souls": "Fauce de Almas",
"neltharions-lair": "Guarida de Neltharion", "neltharions-lair": "Guarida de Neltharion",
"the-arcway": "La Arquería", "the-arcway": "La Arquería",
"eye-of-azshara": "Ojo de Azshara", "eye-of-azshara": "Ojo de Azshara",
"black-rook-hold": "Torreón Grajo Negro", "black-rook-hold": "Torreón Grajo Negro",
"cathedral-of-eternal-night": "Catedral de la Noche Eterna", "cathedral-of-eternal-night": "Catedral de la Noche Eterna",
"return-to-karazhan-lower": "Regreso a Karazhan: inferior", "return-to-karazhan-lower": "Regreso a Karazhan: inferior",
"return-to-karazhan-upper": "Regreso a Karazhan: superior", "return-to-karazhan-upper": "Regreso a Karazhan: superior",
"seat-of-the-triumvirate": "Trono del Triunvirato" "seat-of-the-triumvirate": "Trono del Triunvirato"
} }
timers = { timers = {
"black-rook-hold": ["39:00", "31:12", "23:25"], "black-rook-hold": ["39:00", "31:12", "23:25"],
"court-of-stars": ["30:00", "24:00", "18:00"], "court-of-stars": ["30:00", "24:00", "18:00"],
"darkheart-thicket": ["30:00", "24:00", "18:00"], "darkheart-thicket": ["30:00", "24:00", "18:00"],
"eye-of-azshara": ["35:00", "28:00", "21:00"], "eye-of-azshara": ["35:00", "28:00", "21:00"],
"halls-of-valor": ["45:00", "36:00", "27:00"], "halls-of-valor": ["45:00", "36:00", "27:00"],
"maw-of-souls": ["24:00", "19:12", "14:24"], "maw-of-souls": ["24:00", "19:12", "14:24"],
"neltharions-lair": ["33:00", "27:24", "19:48"], "neltharions-lair": ["33:00", "27:24", "19:48"],
"the-arcway": ["45:00", "36:00", "27:00"], "the-arcway": ["45:00", "36:00", "27:00"],
"vault-of-the-wardens": ["33:00", "26:24", "19:48"], "vault-of-the-wardens": ["33:00", "26:24", "19:48"],
"cathedral-of-eternal-night": ["33:00", "27:24", "19:48"], "cathedral-of-eternal-night": ["33:00", "27:24", "19:48"],
"return-to-karazhan-lower": ["39:00", "31:12", "23:24"], "return-to-karazhan-lower": ["39:00", "31:12", "23:24"],
"return-to-karazhan-upper": ["39:00", "31:12", "23:24"], "return-to-karazhan-upper": ["39:00", "31:12", "23:24"],
"seat-of-the-triumvirate": ["35:00", "28:00", "21:00"] "seat-of-the-triumvirate": ["35:00", "28:00", "21:00"]
} }
class_icons = { class_icons = {
"Character--WARRIOR": "<:class_warrior:352756406232809483>", "Character--WARRIOR": "<:class_warrior:352756406232809483>",
"Character--DRUID": "<:class_druid:352756406421815296>", "Character--DRUID": "<:class_druid:352756406421815296>",
"Character--HUNTER": "<:class_hunter:352756406278946827>", "Character--HUNTER": "<:class_hunter:352756406278946827>",
"Character--DEATHKNIGHT": "<:class_deathknight:352756406408970240>", "Character--DEATHKNIGHT": "<:class_deathknight:352756406408970240>",
"Character--MAGE": "<:class_mage:352756406035808258>", "Character--MAGE": "<:class_mage:352756406035808258>",
"Character--DEMONHUNTER": "<:class_demonhunter:352756406425878528>", "Character--DEMONHUNTER": "<:class_demonhunter:352756406425878528>",
"Character--PRIEST": "<:class_priest:352756406299918337>", "Character--PRIEST": "<:class_priest:352756406299918337>",
"Character--PALADIN": "<:class_paladin:352756406446981130>", "Character--PALADIN": "<:class_paladin:352756406446981130>",
"Character--SHAMAN": "<:class_shaman:352756406459432960>", "Character--SHAMAN": "<:class_shaman:352756406459432960>",
"Character--ROGUE": "<:class_rogue:352756406455107584>", "Character--ROGUE": "<:class_rogue:352756406455107584>",
"Character--WARLOCK": "<:class_warlock:352756406476341248>", "Character--WARLOCK": "<:class_warlock:352756406476341248>",
"Character--MONK": "<:class_monk:352756406337798145>" "Character--MONK": "<:class_monk:352756406337798145>"
} }
#stop here! #stop here!
def battle_net_url(pattern): def battle_net_url(pattern):
return pattern.format(battle_net_region, battle_net_apikey) return pattern.format(battle_net_region, battle_net_apikey)

View File

@ -1,9 +1,9 @@
#! /usr/bin/python3 #! /usr/bin/python3
import redis
import time import time
import requests
import sys import sys
import redis
import requests
import webhook import webhook
import conf import conf
@ -23,8 +23,8 @@ g = requests.get(url=bnet_guild).json()
if "members" not in g: if "members" not in g:
print("'members' not in g") print("'members' not in g")
sys.exit() sys.exit()
members = r.smembers("bot:members") # members database, used by other scripts members = r.smembers("bot:members") # members database, used by other scripts
chars = set() chars = set()
@ -32,84 +32,84 @@ chars = set()
# who join the guild, who leaves # who join the guild, who leaves
for member in g["members"]: for member in g["members"]:
chars.add(member["character"]["name"]) chars.add(member["character"]["name"])
for new in chars.difference(members): for new in chars.difference(members):
r.sadd("bot:members", new) r.sadd("bot:members", new)
members.add(new) members.add(new)
wh.send(":inbox_tray: **[{0}](<https://www.wowprogress.com/character/eu/dun-modr/{0}>)** ha entrado a la guild! 🎉".format(new)) wh.send(":inbox_tray: **[{0}](<https://www.wowprogress.com/character/eu/dun-modr/{0}>)** ha entrado a la guild! 🎉".format(new))
time.sleep(2) time.sleep(2)
for kick in members.difference(chars): for kick in members.difference(chars):
r.srem("bot:members", kick) r.srem("bot:members", kick)
wh.send(":outbox_tray: **[{0}](<https://www.wowprogress.com/character/eu/dun-modr/{0}>)** ha salido a la guild :confused:".format(kick)) wh.send(":outbox_tray: **[{0}](<https://www.wowprogress.com/character/eu/dun-modr/{0}>)** ha salido a la guild :confused:".format(kick))
time.sleep(2) time.sleep(2)
if "news" not in g: if "news" not in g:
print("'news' not in g") print("'news' not in g")
sys.exit() sys.exit()
g["news"].reverse() g["news"].reverse()
r.zremrangebyscore("bot:guild", "-inf", now-(60*60*24*2)) r.zremrangebyscore("bot:guild", "-inf", now-(60*60*24*2))
for news in g["news"]: for news in g["news"]:
fid = None fid = None
push = None push = None
if news["timestamp"]/1000 < now-(60*60*24): # oooold, check 1 day only if news["timestamp"]/1000 < now-(60*60*24): # oooold, check 1 day only
continue continue
if news["type"] in ["playerAchievement", "guildAchievement"]: if news["type"] in ["playerAchievement", "guildAchievement"]:
fid = "{} {} {}".format(news["type"], news["character"], news["achievement"]["title"]) fid = "{} {} {}".format(news["type"], news["character"], news["achievement"]["title"])
push = ":medal: **{0}** gana el logro **{1}**!".format(news["character"], news["achievement"]["title"]) push = ":medal: **{0}** gana el logro **{1}**!".format(news["character"], news["achievement"]["title"])
if fid is None or r.zadd("bot:guild", now, fid) == 0 or push is None: if fid is None or r.zadd("bot:guild", now, fid) == 0 or push is None:
continue continue
wh.send(push) wh.send(push)
time.sleep(2) # prevent rate limit, for example with boss FK time.sleep(2) # prevent rate limit, for example with boss FK
if "achievements" not in g: if "achievements" not in g:
print("'achievements' not in g") print("'achievements' not in g")
sys.exit() sys.exit()
def ach_to_list(data): def ach_to_list(data):
ret = [] ret = []
for d in data: for d in data:
if "categories" in d: if "categories" in d:
ret.extend(ach_to_list(d["categories"])) ret.extend(ach_to_list(d["categories"]))
elif "achievements" in d: elif "achievements" in d:
ret.extend(ach_to_list(d["achievements"])) ret.extend(ach_to_list(d["achievements"]))
else: else:
ret.append(d) ret.append(d)
return ret return ret
a = ach_to_list(a["achievements"]) a = ach_to_list(a["achievements"])
achievements = [int(x) for x in r.smembers("bot:guild-ach")] achievements = [int(x) for x in r.smembers("bot:guild-ach")]
for new in set(g["achievements"]["achievementsCompleted"]).difference(achievements): for new in set(g["achievements"]["achievementsCompleted"]).difference(achievements):
r.sadd("bot:guild-ach", new) r.sadd("bot:guild-ach", new)
ach = next((item for item in a if item["id"] == new), None) ach = next((item for item in a if item["id"] == new), None)
if not ach or "title" not in ach: if not ach or "title" not in ach:
continue continue
title = ach["title"] title = ach["title"]
desc = ach["description"] desc = ach["description"]
url = "http://es.wowhead.com/achievement={0}".format(new) url = "http://es.wowhead.com/achievement={0}".format(new)
icon = "https://wow.zamimg.com/images/wow/icons/large/{0}.jpg".format(ach["icon"]) icon = "https://wow.zamimg.com/images/wow/icons/large/{0}.jpg".format(ach["icon"])
wh.clear_embeds() wh.clear_embeds()
wh.add_embed(webhook.embed(title=ach["title"], url="http://es.wowhead.com/achievement={0}".format(new), description=ach["description"], thumbnail=webhook.image(icon))) wh.add_embed(webhook.embed(title=ach["title"], url="http://es.wowhead.com/achievement={0}".format(new), description=ach["description"], thumbnail=webhook.image(icon)))
wh.send(":clap: La guild ha ganado un logro!") wh.send(":clap: La guild ha ganado un logro!")
time.sleep(2) time.sleep(2)

39
loot.py
View File

@ -1,11 +1,14 @@
#! /usr/bin/python3 #! /usr/bin/python3
"""
Loot notifications
"""
import redis
import time import time
import json import json
import requests
import traceback import traceback
import os import os
import redis
import requests
import webhook import webhook
import conf import conf
@ -20,34 +23,34 @@ bnet_member = "https://{1}.api.battle.net/wow/character/dun%20modr/{0}?fields=fe
# legends database # legends database
items = {} items = {}
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "items_legend.json"), 'r') as f: with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "items_legend.json"), 'r') as f:
js = json.load(f) js = json.load(f)
for item in js: for item in js:
items[item["item_id"]] = item items[item["item_id"]] = item
members = r.smembers("bot:members") # i need all guild members members = r.smembers("bot:members") # i need all guild members
request = requests.Session() request = requests.Session()
for m in members: for m in members:
try: try:
member = request.get(url=bnet_member.format(m, conf.battle_net_region, conf.battle_net_apikey)).json() member = request.get(url=bnet_member.format(m, conf.battle_net_region, conf.battle_net_apikey)).json()
if "feed" not in member: if "feed" not in member:
continue continue
for feed in member["feed"]: for feed in member["feed"]:
if feed["type"] != "LOOT": if feed["type"] != "LOOT":
continue continue
fid = "{}-{}".format(m, feed["itemId"]) fid = "{}-{}".format(m, feed["itemId"])
if feed["itemId"] in items and r.sadd("bot:legends", fid): if feed["itemId"] in items and r.sadd("bot:legends", fid):
wh.send(":tangerine: **{0}** pilla legendario! **[{1}](<http://es.wowhead.com/item={2}>)**".format(member["name"], items[feed["itemId"]]["name_eses"], feed["itemId"])) wh.send(":tangerine: **{0}** pilla legendario! **[{1}](<http://es.wowhead.com/item={2}>)**".format(member["name"], items[feed["itemId"]]["name_eses"], feed["itemId"]))
time.sleep(2) time.sleep(2)
except: except:
traceback.print_exc() traceback.print_exc()
""" """
Vamos a generar el archivo items_legend.json Vamos a generar el archivo items_legend.json

View File

@ -22,74 +22,74 @@ members = r.smembers("bot:members")
r.zremrangebyscore("bot:m+", "-inf", now-(60*60*24*7*2)) # 2 semanas r.zremrangebyscore("bot:m+", "-inf", now-(60*60*24*7*2)) # 2 semanas
for zone, instance in conf.zones.items(): for zone, instance in conf.zones.items():
try: try:
page = requests.get(warcraft_api.format(zone)) page = requests.get(warcraft_api.format(zone))
hp = etree.HTMLParser(encoding=page.encoding) hp = etree.HTMLParser(encoding=page.encoding)
tree = html.fromstring(page.content, parser=hp) # .decode(page.encoding) tree = html.fromstring(page.content, parser=hp) # .decode(page.encoding)
top = tree.xpath('//div[@class="Media-text"]/div[@class="font-semp-medium-white"]/text()') top = tree.xpath('//div[@class="Media-text"]/div[@class="font-semp-medium-white"]/text()')
if len(top) < 3: if len(top) < 3:
print("no affix?") print("no affix?")
continue continue
affix = "" if top[0] not in conf.affixes else conf.affixes[top[0]] affix = "" if top[0] not in conf.affixes else conf.affixes[top[0]]
affix += "" if top[1] not in conf.affixes else conf.affixes[top[1]] affix += "" if top[1] not in conf.affixes else conf.affixes[top[1]]
affix += "" if top[2] not in conf.affixes else conf.affixes[top[2]] affix += "" if top[2] not in conf.affixes else conf.affixes[top[2]]
rows = tree.xpath('//div[@class="SortTable-body"]/div[@class="SortTable-row"]') rows = tree.xpath('//div[@class="SortTable-body"]/div[@class="SortTable-row"]')
#print("rows", len(rows)) #print("rows", len(rows))
for row in rows: for row in rows:
#print("tiempo", row.xpath('./div[5]/text()')) #print("tiempo", row.xpath('./div[5]/text()'))
#print("row", html.tostring(row)) #print("row", html.tostring(row))
pos = row.xpath('./div[1]/text()')[0] pos = row.xpath('./div[1]/text()')[0]
lvl = int(row.xpath('./div[2]/text()')[0]) lvl = int(row.xpath('./div[2]/text()')[0])
record = row.xpath('./div[3]/text()')[0] record = row.xpath('./div[3]/text()')[0]
datee = row.xpath('./div[5]/text()')[0] #row.xpath('./div[5]/@data-value')[0] datee = row.xpath('./div[5]/text()')[0] #row.xpath('./div[5]/@data-value')[0]
team = row.xpath('./div[4]/div/div[@class="List-item gutter-tiny"]') team = row.xpath('./div[4]/div/div[@class="List-item gutter-tiny"]')
#print("row", pos, lvl, time, datee, len(team)) #print("row", pos, lvl, time, datee, len(team))
k = "{0}.{1}.{2}.{3}".format(zone, lvl, record, datee) k = "{0}.{1}.{2}.{3}".format(zone, lvl, record, datee)
inguild = False inguild = False
party = [] party = []
if lvl < conf.min_mythic or r.zadd("bot:m+", now, k) == 0: if lvl < conf.min_mythic or r.zadd("bot:m+", now, k) == 0:
continue continue
for player in team: for player in team:
#print("player", html.tostring(player)) #print("player", html.tostring(player))
name = player.xpath('.//div[@class="Character-name"]/text()')[0] name = player.xpath('.//div[@class="Character-name"]/text()')[0]
url = str(player.xpath('./a/@href')[0]) url = str(player.xpath('./a/@href')[0])
clss = str(player.xpath('./a/@class')[0]) clss = str(player.xpath('./a/@class')[0])
spec = "" spec = ""
for key in conf.class_icons.keys(): for key in conf.class_icons.keys():
if key in clss: if key in clss:
spec = conf.class_icons[key] spec = conf.class_icons[key]
#party.append("{2}{0}{1}".format(name, "" if "dun-modr" in url else " *({})*".format(url.split("/")[6]), roles[len(party)])) #party.append("{2}{0}{1}".format(name, "" if "dun-modr" in url else " *({})*".format(url.split("/")[6]), roles[len(party)]))
party.append("{1} {0}".format(name if "dun-modr" in url else "*{}*".format(name), spec)) party.append("{1} {0}".format(name if "dun-modr" in url else "*{}*".format(name), spec))
for member in members: for member in members:
if "/{}".format(member).lower() in url and "dun-modr" in url: if "/{}".format(member).lower() in url and "dun-modr" in url:
inguild = True inguild = True
if inguild: if inguild:
chests = 0 chests = 0
for timer in conf.timers[zone]: for timer in conf.timers[zone]:
delta = datetime.datetime.strptime(record, '%H:%M:%S') - datetime.datetime.strptime(timer, '%M:%S') delta = datetime.datetime.strptime(record, '%H:%M:%S') - datetime.datetime.strptime(timer, '%M:%S')
if delta.total_seconds() > 0: if delta.total_seconds() > 0:
break break
chests += 1 chests += 1
if chests == 3: if chests == 3:
delta = datetime.datetime.strptime(timer, '%M:%S') - datetime.datetime.strptime(record, '%H:%M:%S') delta = datetime.datetime.strptime(timer, '%M:%S') - datetime.datetime.strptime(record, '%H:%M:%S')
#tip = "(piedra +{0} por {1})".format(chests, delta) #tip = "(piedra +{0} por {1})".format(chests, delta)
tip = "(piedra +{0})".format(chests, delta) tip = "(piedra +{0})".format(chests, delta)
msg = ":mega: **[{0}](<{5}>) +{1}** hecha en **{2}** {3}, **rank {4}** de Dun Modr".format(instance, lvl, record, tip, pos, warcraft_api.format(zone)) msg = ":mega: **[{0}](<{5}>) +{1}** hecha en **{2}** {3}, **rank {4}** de Dun Modr".format(instance, lvl, record, tip, pos, warcraft_api.format(zone))
#print(msg) #print(msg)
wh.clear_embeds() wh.clear_embeds()
wh.add_embed(webhook.embed(title=", ".join(party))) wh.add_embed(webhook.embed(title=", ".join(party)))
wh.send(msg) wh.send(msg)
except: except:
traceback.print_exc() traceback.print_exc()
time.sleep(1) time.sleep(1)

View File

@ -1,4 +1,7 @@
#! /usr/bin/python3 #! /usr/bin/python3
"""
Raider.IO progress
"""
import redis import redis
import requests import requests
@ -18,26 +21,26 @@ slug = "antorus-the-burning-throne"
api = requests.get(url=rio_api).json() api = requests.get(url=rio_api).json()
if api is not None and "raid_rankings" in api and "raid_progression" and slug in api["raid_rankings"]: if api is not None and "raid_rankings" in api and "raid_progression" and slug in api["raid_rankings"]:
prev_rank = r.get("bot:raiderio") prev_rank = r.get("bot:raiderio")
rank = api["raid_rankings"][slug]["mythic"]["realm"] rank = api["raid_rankings"][slug]["mythic"]["realm"]
progress = api["raid_progression"][slug]["summary"] progress = api["raid_progression"][slug]["summary"]
msg = None msg = None
if prev_rank is None: if prev_rank is None:
msg = ":arrow_right: La guild entra en el ranking de Dun Modr: #**{0}**, {1}".format(rank, progress) msg = ":arrow_right: La guild entra en el ranking de Dun Modr: #**{0}**, {1}".format(rank, progress)
elif int(prev_rank) > int(rank): elif int(prev_rank) > int(rank):
msg = ":arrow_up: La guild sube en el ranking de Dun Modr: #**{0}** (+{1}), {2}".format(rank, int(prev_rank)-int(rank), progress) msg = ":arrow_up: La guild sube en el ranking de Dun Modr: #**{0}** (+{1}), {2}".format(rank, int(prev_rank)-int(rank), progress)
elif int(prev_rank) < int(rank): elif int(prev_rank) < int(rank):
msg = ":arrow_down: La guild baja en el ranking de Dun Modr: #**{0}** (-{1}), {2}".format(rank, int(rank)-int(prev_rank), progress) msg = ":arrow_down: La guild baja en el ranking de Dun Modr: #**{0}** (-{1}), {2}".format(rank, int(rank)-int(prev_rank), progress)
elif int(prev_rank) == int(rank): elif int(prev_rank) == int(rank):
msg = ":ok_hand: La guild se mantiene en el ranking de Dun Modr: #**{0}**, {1}".format(rank, progress) msg = ":ok_hand: La guild se mantiene en el ranking de Dun Modr: #**{0}**, {1}".format(rank, progress)
r.set("bot:raiderio", rank) r.set("bot:raiderio", rank)
if msg: if msg:
msg += " - [Raider.IO](<https://raider.io/guilds/eu/dun-modr/Mirrors>) - [WoWProgress](<https://www.wowprogress.com/guild/eu/dun-modr/Mirrors>)" msg += " - [Raider.IO](<https://raider.io/guilds/eu/dun-modr/Mirrors>) - [WoWProgress](<https://www.wowprogress.com/guild/eu/dun-modr/Mirrors>)"
wh.send(msg) wh.send(msg)

51
rss.py
View File

@ -1,9 +1,12 @@
#! /usr/bin/python3 #! /usr/bin/python3
"""
RSS news
"""
import feedparser
import redis
import time import time
import traceback import traceback
import feedparser
import redis
import webhook import webhook
import conf import conf
@ -15,33 +18,33 @@ r = redis.StrictRedis(host='localhost', charset="utf-8", decode_responses=True,
r.zremrangebyscore("bot:rss", "-inf", now-(60*60*24*30*3)) # 3 meses de caché r.zremrangebyscore("bot:rss", "-inf", now-(60*60*24*30*3)) # 3 meses de caché
url_feeds = [ url_feeds = [
"http://www.wowhead.com/news&rss", "http://www.wowhead.com/news&rss",
"http://www.mmo-champion.com/external.php?do=rss&type=newcontent&sectionid=1&days=120&count=5" "http://www.mmo-champion.com/external.php?do=rss&type=newcontent&sectionid=1&days=120&count=5"
] ]
for url in url_feeds: for url in url_feeds:
try: try:
feed = feedparser.parse(url) feed = feedparser.parse(url)
if "items" not in feed or len(feed["items"]) < 3: if "items" not in feed or len(feed["items"]) < 3:
continue continue
for i in [0, 1, 2]: # 3 últimas noticias for i in [0, 1, 2]: # last 3 news
entry = feed["items"][i] entry = feed["items"][i]
fid = "{} {}".format(feed["feed"]["title"][0:20], entry["published"]) fid = "{} {}".format(feed["feed"]["title"][0:20], entry["published"])
if r.zadd("bot:rss", now, fid) == 0: if r.zadd("bot:rss", now, fid) == 0:
continue continue
if "wowhead.com/" in entry["link"]: if "wowhead.com/" in entry["link"]:
icon = conf.icon_wowhead icon = conf.icon_wowhead
elif "mmo-champion.com/" in entry["link"]: elif "mmo-champion.com/" in entry["link"]:
icon = conf.icon_mmoc icon = conf.icon_mmoc
else: else:
icon = ":newspaper2:" icon = ":newspaper2:"
wh.send("{2} [{0}](<{1}>)".format(entry["title"], entry["link"], icon)) wh.send("{2} [{0}](<{1}>)".format(entry["title"], entry["link"], icon))
time.sleep(2) time.sleep(2)
except: except:
print(url) print(url)
traceback.print_exc() traceback.print_exc()

View File

@ -1,9 +1,12 @@
#! /usr/bin/python3 #! /usr/bin/python3
"""
Streams Cron
"""
import redis
import time import time
import requests
import sys import sys
import redis
import requests
import webhook import webhook
import conf import conf
@ -20,12 +23,12 @@ r.zremrangebyscore("bot:twitch", "-inf", now-(60*15))
t = requests.get(url=twitch_api).json() t = requests.get(url=twitch_api).json()
if "streams" not in t: if "streams" not in t:
print(t) print(t)
sys.exit() sys.exit()
for stream in t["streams"]: for stream in t["streams"]:
if r.zadd("bot:twitch", now, stream["channel"]["name"]) == 0: if r.zadd("bot:twitch", now, stream["channel"]["name"]) == 0:
continue continue
wh.send("{3} **{0}** está stremeando: [{2}](<{1}>)".format(stream["channel"]["name"], stream["channel"]["url"], stream["channel"]["status"], conf.icon_twitch)) wh.send("{3} **{0}** está stremeando: [{2}](<{1}>)".format(stream["channel"]["name"], stream["channel"]["url"], stream["channel"]["status"], conf.icon_twitch))
time.sleep(2) time.sleep(2)

View File

@ -1,11 +1,14 @@
#! /usr/bin/python3 #! /usr/bin/python3
"""
WarcrafLogs notifications
"""
import redis
import time import time
import sys
import redis
import requests import requests
import webhook import webhook
import conf import conf
import sys
now = time.time() now = time.time()
@ -19,16 +22,16 @@ wl_api = "https://www.warcraftlogs.com/v1/reports/guild/mirrors/dun-modr/eu?api_
wl = requests.get(url=wl_api).json() wl = requests.get(url=wl_api).json()
if "error" in wl: if "error" in wl:
print(wl) print(wl)
sys.exit() sys.exit()
for report in wl: for report in wl:
if report["start"]/1000 < now-(60*60*24*7): # oooold, 7 day only if report["start"]/1000 < now-(60*60*24*7): # oooold, 7 day only
continue continue
if not r.zadd("bot:warcraftlogs", now, report["id"]): if not r.zadd("bot:warcraftlogs", now, report["id"]):
continue continue
url = "https://www.warcraftlogs.com/reports/{0}".format(report["id"]) url = "https://www.warcraftlogs.com/reports/{0}".format(report["id"])
wh.send("{3} Logs! **[{2}](<{1}>)** por **{0}**".format(report["owner"], url, report["title"], conf.icon_warcraftlogs)) wh.send("{3} Logs! **[{2}](<{1}>)** por **{0}**".format(report["owner"], url, report["title"], conf.icon_warcraftlogs))
time.sleep(2) time.sleep(2)

View File

@ -10,89 +10,89 @@ now = time.time()
# https://discordapp.com/developers/docs/resources/webhook#execute-webhook # https://discordapp.com/developers/docs/resources/webhook#execute-webhook
class Webhook(): class Webhook():
def __init__(self, url, **kwargs): def __init__(self, url, **kwargs):
self.url = url self.url = url
self.wh = { self.wh = {
#"username": kwargs.get("username", None), #"username": kwargs.get("username", None),
#"avatar_url": kwargs.get("avatar_url", None), #"avatar_url": kwargs.get("avatar_url", None),
"content": None, "content": None,
"embeds": [] "embeds": []
} }
self.requests = requests.Session() self.requests = requests.Session()
def add_embed(self, embed): def add_embed(self, embed):
self.wh["embeds"].append(embed) self.wh["embeds"].append(embed)
def clear_embeds(self): def clear_embeds(self):
self.wh["embeds"] = [] self.wh["embeds"] = []
def send(self, content=None, tts=False): def send(self, content=None, tts=False):
self.wh["content"] = content self.wh["content"] = content
self.wh["tts"] = tts self.wh["tts"] = tts
#print(self.wh) #print(self.wh)
#return True # BORRAR ESTO #return True # BORRAR ESTO
r = self.requests.post(self.url, json=self.wh) r = self.requests.post(self.url, json=self.wh)
if "X-RateLimit-Remaining" in r.headers and int(r.headers["X-RateLimit-Remaining"]) <= 1: if "X-RateLimit-Remaining" in r.headers and int(r.headers["X-RateLimit-Remaining"]) <= 1:
wait = int(r.headers["X-RateLimit-Reset"])-int(now) wait = int(r.headers["X-RateLimit-Reset"])-int(now)
raise Exception("RateLimit {0}/{1}, reset in ~{2}s".format(r.headers["X-RateLimit-Remaining"], r.headers["X-RateLimit-Limit"], wait)) raise Exception("RateLimit {0}/{1}, reset in ~{2}s".format(r.headers["X-RateLimit-Remaining"], r.headers["X-RateLimit-Limit"], wait))
"""rl = "RateLimit {0}/{1}, reset in ~{2}s".format(r.headers["X-RateLimit-Remaining"], r.headers["X-RateLimit-Limit"], wait) """rl = "RateLimit {0}/{1}, reset in ~{2}s".format(r.headers["X-RateLimit-Remaining"], r.headers["X-RateLimit-Limit"], wait)
if wait < 600: if wait < 600:
print(rl) print(rl)
time.sleep(wait+1) time.sleep(wait+1)
else: else:
raise Exception(rl)""" raise Exception(rl)"""
if r.text != "": if r.text != "":
raise Exception("Webhook error: {0}".format(r.text)) raise Exception("Webhook error: {0}".format(r.text))
return True return True
# https://discordapp.com/developers/docs/resources/channel#embed-object # https://discordapp.com/developers/docs/resources/channel#embed-object
def embed(**kwargs): def embed(**kwargs):
return { return {
"title": kwargs.get("title", None), "title": kwargs.get("title", None),
"description": kwargs.get("description", None), "description": kwargs.get("description", None),
"url": kwargs.get("url", None), "url": kwargs.get("url", None),
"color": kwargs.get("color", None), "color": kwargs.get("color", None),
"image": kwargs.get("image", None), "image": kwargs.get("image", None),
"thumbnail": kwargs.get("thumbnail", None), "thumbnail": kwargs.get("thumbnail", None),
"footer": kwargs.get("footer", None), "footer": kwargs.get("footer", None),
"fields": kwargs.get("fields", []) "fields": kwargs.get("fields", [])
} }
def field(name, value, inline=False): def field(name, value, inline=False):
return { return {
"name": name, "name": name,
"value": value, "value": value,
"inline": inline "inline": inline
} }
def image(url, w=50, h=50): def image(url, w=50, h=50):
return { return {
"url": url, "url": url,
"width": w, "width": w,
"height": h "height": h
} }
def thumbnail(url, w=50, h=50): def thumbnail(url, w=50, h=50):
return { return {
"url": url, "url": url,
"width": w, "width": w,
"height": h "height": h
} }
def footer(text, icon_url): def footer(text, icon_url):
return { return {
"text": text, "text": text,
"icon_url": icon_url "icon_url": icon_url
} }
__all__ = ["Webhook", "embed", "field", "footer"] __all__ = ["Webhook", "embed", "field", "footer"]

View File

@ -1,7 +1,6 @@
#! /usr/bin/python3 #! /usr/bin/python3
import redis import redis
import time
import requests import requests
import webhook import webhook
import conf import conf
@ -17,24 +16,23 @@ wp_api = "http://www.wowprogress.com/guild/eu/dun-modr/Mirrors/json_rank"
rank = requests.get(url=wp_api).json() rank = requests.get(url=wp_api).json()
if rank is not None and "realm_rank" in rank: if rank is not None and "realm_rank" in rank:
last = r.get("bot:wowprogress") last = r.get("bot:wowprogress")
realm = rank["realm_rank"] realm = rank["realm_rank"]
msg = None msg = None
if last is None: if last is None:
msg = ":arrow_right: La guild entra en el ranking de Dun Modr: **{0}**".format(realm) msg = ":arrow_right: La guild entra en el ranking de Dun Modr: **{0}**".format(realm)
elif int(last) > int(rank["realm_rank"]): elif int(last) > int(rank["realm_rank"]):
msg = ":arrow_up: La guild sube en el ranking de Dun Modr: **{0}** (+{1})".format(realm, int(last)-int(realm)) msg = ":arrow_up: La guild sube en el ranking de Dun Modr: **{0}** (+{1})".format(realm, int(last)-int(realm))
elif int(last) < int(realm): elif int(last) < int(realm):
msg = ":arrow_down: La guild baja en el ranking de Dun Modr: **{0}** (-{1})".format(realm, int(realm)-int(last)) msg = ":arrow_down: La guild baja en el ranking de Dun Modr: **{0}** (-{1})".format(realm, int(realm)-int(last))
elif int(last) == int(realm): elif int(last) == int(realm):
msg = ":ok_hand: La guild se mantiene en el ranking de Dun Modr: **{0}**".format(realm) msg = ":ok_hand: La guild se mantiene en el ranking de Dun Modr: **{0}**".format(realm)
r.set("bot:wowprogress", realm) r.set("bot:wowprogress", realm)
if msg: if msg:
wh.send(msg) wh.send(msg)
time.sleep(2)