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
"""
Affixes Cron
"""
import datetime
import time
import webhook
import conf
@ -11,8 +13,7 @@ week = (int(datetime.datetime.now().strftime("%V")) % len(conf.affix_rotation))
f = []
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.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 *
@ -9,102 +12,102 @@ icon_warcraftlogs = "<:Warcraftlogs:352756407164076034>"
min_mythic = 15
affixes = {
"Bullente": "<:m_teeming:352756406514089994>",
"Detonante": "<:m_bursting:352760092397010944>",
"Dolorosa": "<:m_grievous:352760092472377344>",
"Explosiva": "<:m_explosive:352760091981905932>",
"Furibunda": "<:m_raging:352756406492987394>",
"Inquieta": "<:m_skittish:352756406497181698>",
"Necrótica": "<:m_necro:352756406333472769>",
"Potenciante": "<:m_bolstering:352756406509633536>",
"Rebosante": "<:m_over:352756406463758337>",
"Reforzada": "<:m_forti:352756406497050624>",
"Sanguina": "<:m_sanguine:352756406153379844>",
"Sísmica": "<:m_quaking:352760093118300160>",
"Tiránica": "<:m_tyra:352756406279208964>",
"Volcánica": "<:m_volcanic:352756406341992449>"
"Bullente": "<:m_teeming:352756406514089994>",
"Detonante": "<:m_bursting:352760092397010944>",
"Dolorosa": "<:m_grievous:352760092472377344>",
"Explosiva": "<:m_explosive:352760091981905932>",
"Furibunda": "<:m_raging:352756406492987394>",
"Inquieta": "<:m_skittish:352756406497181698>",
"Necrótica": "<:m_necro:352756406333472769>",
"Potenciante": "<:m_bolstering:352756406509633536>",
"Rebosante": "<:m_over:352756406463758337>",
"Reforzada": "<:m_forti:352756406497050624>",
"Sanguina": "<:m_sanguine:352756406153379844>",
"Sísmica": "<:m_quaking:352760093118300160>",
"Tiránica": "<:m_tyra:352756406279208964>",
"Volcánica": "<:m_volcanic:352756406341992449>"
}
affix_human = {
"Bullente": "+ bichos",
"Detonante": "= Il'gynoth",
"Dolorosa": "Sangrado 90%",
"Explosiva": "Orbes de mierda",
"Furibunda": "Enrage 30%",
"Inquieta": "- Aggro",
"Necrótica": "- Sanación",
"Potenciante": "Se buffan al morir",
"Rebosante": "Overheal",
"Reforzada": "Bichos :muscle:",
"Sanguina": "Pozo al morir",
"Sísmica": "El puto quake",
"Tiránica": "Bosses :muscle:",
"Volcánica": "El puto volcanic"
"Bullente": "+ bichos",
"Detonante": "= Il'gynoth",
"Dolorosa": "Sangrado 90%",
"Explosiva": "Orbes de mierda",
"Furibunda": "Enrage 30%",
"Inquieta": "- Aggro",
"Necrótica": "- Sanación",
"Potenciante": "Se buffan al morir",
"Rebosante": "Overheal",
"Reforzada": "Bichos :muscle:",
"Sanguina": "Pozo al morir",
"Sísmica": "El puto quake",
"Tiránica": "Bosses :muscle:",
"Volcánica": "El puto volcanic"
}
affix_rotation = [
["Furibunda", "Volcánica", "Tiránica"],
["Bullente", "Explosiva", "Reforzada"],
["Potenciante", "Dolorosa", "Tiránica"],
["Sanguina", "Volcánica", "Reforzada"],
["Detonante", "Inquieta", "Tiránica"],
["Bullente", "Sísmica", "Reforzada"],
["Furibunda", "Necrótica", "Tiránica"],
["Potenciante", "Inquieta", "Reforzada"],
["Bullente", "Necrótica", "Tiránica"],
["Sanguina", "Dolorosa", "Reforzada"],
["Potenciante", "Explosiva", "Tiránica"],
["Detonante", "Sísmica", "Reforzada"]
["Furibunda", "Volcánica", "Tiránica"],
["Bullente", "Explosiva", "Reforzada"],
["Potenciante", "Dolorosa", "Tiránica"],
["Sanguina", "Volcánica", "Reforzada"],
["Detonante", "Inquieta", "Tiránica"],
["Bullente", "Sísmica", "Reforzada"],
["Furibunda", "Necrótica", "Tiránica"],
["Potenciante", "Inquieta", "Reforzada"],
["Bullente", "Necrótica", "Tiránica"],
["Sanguina", "Dolorosa", "Reforzada"],
["Potenciante", "Explosiva", "Tiránica"],
["Detonante", "Sísmica", "Reforzada"]
]
zones = {
"darkheart-thicket": "Arboleda Corazón Oscuro",
"court-of-stars": "Corte de las Estrellas",
"vault-of-the-wardens": "Cámara de las Celadoras",
"halls-of-valor": "Cámaras del Valor",
"maw-of-souls": "Fauce de Almas",
"neltharions-lair": "Guarida de Neltharion",
"the-arcway": "La Arquería",
"eye-of-azshara": "Ojo de Azshara",
"black-rook-hold": "Torreón Grajo Negro",
"cathedral-of-eternal-night": "Catedral de la Noche Eterna",
"return-to-karazhan-lower": "Regreso a Karazhan: inferior",
"return-to-karazhan-upper": "Regreso a Karazhan: superior",
"seat-of-the-triumvirate": "Trono del Triunvirato"
"darkheart-thicket": "Arboleda Corazón Oscuro",
"court-of-stars": "Corte de las Estrellas",
"vault-of-the-wardens": "Cámara de las Celadoras",
"halls-of-valor": "Cámaras del Valor",
"maw-of-souls": "Fauce de Almas",
"neltharions-lair": "Guarida de Neltharion",
"the-arcway": "La Arquería",
"eye-of-azshara": "Ojo de Azshara",
"black-rook-hold": "Torreón Grajo Negro",
"cathedral-of-eternal-night": "Catedral de la Noche Eterna",
"return-to-karazhan-lower": "Regreso a Karazhan: inferior",
"return-to-karazhan-upper": "Regreso a Karazhan: superior",
"seat-of-the-triumvirate": "Trono del Triunvirato"
}
timers = {
"black-rook-hold": ["39:00", "31:12", "23:25"],
"court-of-stars": ["30:00", "24:00", "18:00"],
"darkheart-thicket": ["30:00", "24:00", "18:00"],
"eye-of-azshara": ["35:00", "28:00", "21:00"],
"halls-of-valor": ["45:00", "36:00", "27:00"],
"maw-of-souls": ["24:00", "19:12", "14:24"],
"neltharions-lair": ["33:00", "27:24", "19:48"],
"the-arcway": ["45:00", "36:00", "27:00"],
"vault-of-the-wardens": ["33:00", "26: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-upper": ["39:00", "31:12", "23:24"],
"seat-of-the-triumvirate": ["35:00", "28:00", "21:00"]
"black-rook-hold": ["39:00", "31:12", "23:25"],
"court-of-stars": ["30:00", "24:00", "18:00"],
"darkheart-thicket": ["30:00", "24:00", "18:00"],
"eye-of-azshara": ["35:00", "28:00", "21:00"],
"halls-of-valor": ["45:00", "36:00", "27:00"],
"maw-of-souls": ["24:00", "19:12", "14:24"],
"neltharions-lair": ["33:00", "27:24", "19:48"],
"the-arcway": ["45:00", "36:00", "27:00"],
"vault-of-the-wardens": ["33:00", "26: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-upper": ["39:00", "31:12", "23:24"],
"seat-of-the-triumvirate": ["35:00", "28:00", "21:00"]
}
class_icons = {
"Character--WARRIOR": "<:class_warrior:352756406232809483>",
"Character--DRUID": "<:class_druid:352756406421815296>",
"Character--HUNTER": "<:class_hunter:352756406278946827>",
"Character--DEATHKNIGHT": "<:class_deathknight:352756406408970240>",
"Character--MAGE": "<:class_mage:352756406035808258>",
"Character--DEMONHUNTER": "<:class_demonhunter:352756406425878528>",
"Character--PRIEST": "<:class_priest:352756406299918337>",
"Character--PALADIN": "<:class_paladin:352756406446981130>",
"Character--SHAMAN": "<:class_shaman:352756406459432960>",
"Character--ROGUE": "<:class_rogue:352756406455107584>",
"Character--WARLOCK": "<:class_warlock:352756406476341248>",
"Character--MONK": "<:class_monk:352756406337798145>"
"Character--WARRIOR": "<:class_warrior:352756406232809483>",
"Character--DRUID": "<:class_druid:352756406421815296>",
"Character--HUNTER": "<:class_hunter:352756406278946827>",
"Character--DEATHKNIGHT": "<:class_deathknight:352756406408970240>",
"Character--MAGE": "<:class_mage:352756406035808258>",
"Character--DEMONHUNTER": "<:class_demonhunter:352756406425878528>",
"Character--PRIEST": "<:class_priest:352756406299918337>",
"Character--PALADIN": "<:class_paladin:352756406446981130>",
"Character--SHAMAN": "<:class_shaman:352756406459432960>",
"Character--ROGUE": "<:class_rogue:352756406455107584>",
"Character--WARLOCK": "<:class_warlock:352756406476341248>",
"Character--MONK": "<:class_monk:352756406337798145>"
}
#stop here!
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
import redis
import time
import requests
import sys
import redis
import requests
import webhook
import conf
@ -23,8 +23,8 @@ g = requests.get(url=bnet_guild).json()
if "members" not in g:
print("'members' not in g")
sys.exit()
print("'members' not in g")
sys.exit()
members = r.smembers("bot:members") # members database, used by other scripts
chars = set()
@ -32,84 +32,84 @@ chars = set()
# who join the guild, who leaves
for member in g["members"]:
chars.add(member["character"]["name"])
chars.add(member["character"]["name"])
for new in chars.difference(members):
r.sadd("bot:members", 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))
time.sleep(2)
r.sadd("bot:members", 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))
time.sleep(2)
for kick in members.difference(chars):
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))
time.sleep(2)
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))
time.sleep(2)
if "news" not in g:
print("'news' not in g")
sys.exit()
print("'news' not in g")
sys.exit()
g["news"].reverse()
r.zremrangebyscore("bot:guild", "-inf", now-(60*60*24*2))
for news in g["news"]:
fid = None
push = None
fid = None
push = None
if news["timestamp"]/1000 < now-(60*60*24): # oooold, check 1 day only
continue
if news["timestamp"]/1000 < now-(60*60*24): # oooold, check 1 day only
continue
if news["type"] in ["playerAchievement", "guildAchievement"]:
fid = "{} {} {}".format(news["type"], news["character"], news["achievement"]["title"])
push = ":medal: **{0}** gana el logro **{1}**!".format(news["character"], news["achievement"]["title"])
if news["type"] in ["playerAchievement", "guildAchievement"]:
fid = "{} {} {}".format(news["type"], 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:
continue
if fid is None or r.zadd("bot:guild", now, fid) == 0 or push is None:
continue
wh.send(push)
time.sleep(2) # prevent rate limit, for example with boss FK
wh.send(push)
time.sleep(2) # prevent rate limit, for example with boss FK
if "achievements" not in g:
print("'achievements' not in g")
sys.exit()
print("'achievements' not in g")
sys.exit()
def ach_to_list(data):
ret = []
ret = []
for d in data:
if "categories" in d:
ret.extend(ach_to_list(d["categories"]))
for d in data:
if "categories" in d:
ret.extend(ach_to_list(d["categories"]))
elif "achievements" in d:
ret.extend(ach_to_list(d["achievements"]))
elif "achievements" in d:
ret.extend(ach_to_list(d["achievements"]))
else:
ret.append(d)
else:
ret.append(d)
return ret
return ret
a = ach_to_list(a["achievements"])
achievements = [int(x) for x in r.smembers("bot:guild-ach")]
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)
if not ach or "title" not in ach:
continue
ach = next((item for item in a if item["id"] == new), None)
if not ach or "title" not in ach:
continue
title = ach["title"]
desc = ach["description"]
url = "http://es.wowhead.com/achievement={0}".format(new)
icon = "https://wow.zamimg.com/images/wow/icons/large/{0}.jpg".format(ach["icon"])
title = ach["title"]
desc = ach["description"]
url = "http://es.wowhead.com/achievement={0}".format(new)
icon = "https://wow.zamimg.com/images/wow/icons/large/{0}.jpg".format(ach["icon"])
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.send(":clap: La guild ha ganado un logro!")
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.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
"""
Loot notifications
"""
import redis
import time
import json
import requests
import traceback
import os
import redis
import requests
import webhook
import conf
@ -20,34 +23,34 @@ bnet_member = "https://{1}.api.battle.net/wow/character/dun%20modr/{0}?fields=fe
# legends database
items = {}
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:
items[item["item_id"]] = item
for item in js:
items[item["item_id"]] = item
members = r.smembers("bot:members") # i need all guild members
request = requests.Session()
for m in members:
try:
member = request.get(url=bnet_member.format(m, conf.battle_net_region, conf.battle_net_apikey)).json()
try:
member = request.get(url=bnet_member.format(m, conf.battle_net_region, conf.battle_net_apikey)).json()
if "feed" not in member:
continue
if "feed" not in member:
continue
for feed in member["feed"]:
if feed["type"] != "LOOT":
continue
for feed in member["feed"]:
if feed["type"] != "LOOT":
continue
fid = "{}-{}".format(m, feed["itemId"])
fid = "{}-{}".format(m, feed["itemId"])
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"]))
time.sleep(2)
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"]))
time.sleep(2)
except:
traceback.print_exc()
except:
traceback.print_exc()
"""
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
for zone, instance in conf.zones.items():
try:
page = requests.get(warcraft_api.format(zone))
hp = etree.HTMLParser(encoding=page.encoding)
tree = html.fromstring(page.content, parser=hp) # .decode(page.encoding)
try:
page = requests.get(warcraft_api.format(zone))
hp = etree.HTMLParser(encoding=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()')
if len(top) < 3:
print("no affix?")
continue
top = tree.xpath('//div[@class="Media-text"]/div[@class="font-semp-medium-white"]/text()')
if len(top) < 3:
print("no affix?")
continue
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[2] not in conf.affixes else conf.affixes[top[2]]
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[2] not in conf.affixes else conf.affixes[top[2]]
rows = tree.xpath('//div[@class="SortTable-body"]/div[@class="SortTable-row"]')
#print("rows", len(rows))
rows = tree.xpath('//div[@class="SortTable-body"]/div[@class="SortTable-row"]')
#print("rows", len(rows))
for row in rows:
#print("tiempo", row.xpath('./div[5]/text()'))
#print("row", html.tostring(row))
pos = row.xpath('./div[1]/text()')[0]
lvl = int(row.xpath('./div[2]/text()')[0])
record = row.xpath('./div[3]/text()')[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"]')
#print("row", pos, lvl, time, datee, len(team))
for row in rows:
#print("tiempo", row.xpath('./div[5]/text()'))
#print("row", html.tostring(row))
pos = row.xpath('./div[1]/text()')[0]
lvl = int(row.xpath('./div[2]/text()')[0])
record = row.xpath('./div[3]/text()')[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"]')
#print("row", pos, lvl, time, datee, len(team))
k = "{0}.{1}.{2}.{3}".format(zone, lvl, record, datee)
inguild = False
party = []
k = "{0}.{1}.{2}.{3}".format(zone, lvl, record, datee)
inguild = False
party = []
if lvl < conf.min_mythic or r.zadd("bot:m+", now, k) == 0:
continue
if lvl < conf.min_mythic or r.zadd("bot:m+", now, k) == 0:
continue
for player in team:
#print("player", html.tostring(player))
name = player.xpath('.//div[@class="Character-name"]/text()')[0]
url = str(player.xpath('./a/@href')[0])
clss = str(player.xpath('./a/@class')[0])
spec = ""
for key in conf.class_icons.keys():
if key in clss:
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("{1} {0}".format(name if "dun-modr" in url else "*{}*".format(name), spec))
for player in team:
#print("player", html.tostring(player))
name = player.xpath('.//div[@class="Character-name"]/text()')[0]
url = str(player.xpath('./a/@href')[0])
clss = str(player.xpath('./a/@class')[0])
spec = ""
for key in conf.class_icons.keys():
if key in clss:
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("{1} {0}".format(name if "dun-modr" in url else "*{}*".format(name), spec))
for member in members:
if "/{}".format(member).lower() in url and "dun-modr" in url:
inguild = True
for member in members:
if "/{}".format(member).lower() in url and "dun-modr" in url:
inguild = True
if inguild:
chests = 0
for timer in conf.timers[zone]:
delta = datetime.datetime.strptime(record, '%H:%M:%S') - datetime.datetime.strptime(timer, '%M:%S')
if delta.total_seconds() > 0:
break
chests += 1
if chests == 3:
delta = datetime.datetime.strptime(timer, '%M:%S') - datetime.datetime.strptime(record, '%H:%M:%S')
if inguild:
chests = 0
for timer in conf.timers[zone]:
delta = datetime.datetime.strptime(record, '%H:%M:%S') - datetime.datetime.strptime(timer, '%M:%S')
if delta.total_seconds() > 0:
break
chests += 1
if chests == 3:
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})".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))
#print(msg)
wh.clear_embeds()
wh.add_embed(webhook.embed(title=", ".join(party)))
wh.send(msg)
#tip = "(piedra +{0} por {1})".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))
#print(msg)
wh.clear_embeds()
wh.add_embed(webhook.embed(title=", ".join(party)))
wh.send(msg)
except:
traceback.print_exc()
time.sleep(1)
except:
traceback.print_exc()
time.sleep(1)

View File

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

51
rss.py
View File

@ -1,9 +1,12 @@
#! /usr/bin/python3
"""
RSS news
"""
import feedparser
import redis
import time
import traceback
import feedparser
import redis
import webhook
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é
url_feeds = [
"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.wowhead.com/news&rss",
"http://www.mmo-champion.com/external.php?do=rss&type=newcontent&sectionid=1&days=120&count=5"
]
for url in url_feeds:
try:
feed = feedparser.parse(url)
try:
feed = feedparser.parse(url)
if "items" not in feed or len(feed["items"]) < 3:
continue
if "items" not in feed or len(feed["items"]) < 3:
continue
for i in [0, 1, 2]: # 3 últimas noticias
entry = feed["items"][i]
fid = "{} {}".format(feed["feed"]["title"][0:20], entry["published"])
if r.zadd("bot:rss", now, fid) == 0:
continue
for i in [0, 1, 2]: # last 3 news
entry = feed["items"][i]
fid = "{} {}".format(feed["feed"]["title"][0:20], entry["published"])
if r.zadd("bot:rss", now, fid) == 0:
continue
if "wowhead.com/" in entry["link"]:
icon = conf.icon_wowhead
elif "mmo-champion.com/" in entry["link"]:
icon = conf.icon_mmoc
else:
icon = ":newspaper2:"
if "wowhead.com/" in entry["link"]:
icon = conf.icon_wowhead
elif "mmo-champion.com/" in entry["link"]:
icon = conf.icon_mmoc
else:
icon = ":newspaper2:"
wh.send("{2} [{0}](<{1}>)".format(entry["title"], entry["link"], icon))
time.sleep(2)
wh.send("{2} [{0}](<{1}>)".format(entry["title"], entry["link"], icon))
time.sleep(2)
except:
print(url)
traceback.print_exc()
except:
print(url)
traceback.print_exc()

View File

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

View File

@ -1,11 +1,14 @@
#! /usr/bin/python3
"""
WarcrafLogs notifications
"""
import redis
import time
import sys
import redis
import requests
import webhook
import conf
import sys
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()
if "error" in wl:
print(wl)
sys.exit()
print(wl)
sys.exit()
for report in wl:
if report["start"]/1000 < now-(60*60*24*7): # oooold, 7 day only
continue
if report["start"]/1000 < now-(60*60*24*7): # oooold, 7 day only
continue
if not r.zadd("bot:warcraftlogs", now, report["id"]):
continue
if not r.zadd("bot:warcraftlogs", now, report["id"]):
continue
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))
time.sleep(2)
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))
time.sleep(2)

View File

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

View File

@ -1,7 +1,6 @@
#! /usr/bin/python3
import redis
import time
import requests
import webhook
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()
if rank is not None and "realm_rank" in rank:
last = r.get("bot:wowprogress")
realm = rank["realm_rank"]
msg = None
last = r.get("bot:wowprogress")
realm = rank["realm_rank"]
msg = None
if last is None:
msg = ":arrow_right: La guild entra en el ranking de Dun Modr: **{0}**".format(realm)
if last is None:
msg = ":arrow_right: La guild entra en el ranking de Dun Modr: **{0}**".format(realm)
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))
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))
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))
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))
elif int(last) == int(realm):
msg = ":ok_hand: La guild se mantiene en el ranking de Dun Modr: **{0}**".format(realm)
elif int(last) == int(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:
wh.send(msg)
time.sleep(2)
if msg:
wh.send(msg)