|
| 1 | +""" |
| 2 | +/* |
| 3 | + * EJERCICIO: |
| 4 | + * ¡Rubius tiene su propia skin en Fortnite! |
| 5 | + * Y va a organizar una competición para celebrarlo. |
| 6 | + * Esta es la lista de participantes: |
| 7 | + * https://x.com/Rubiu5/status/1840161450154692876 |
| 8 | + * |
| 9 | + * Desarrolla un programa que obtenga el número de seguidores en |
| 10 | + * Twitch de cada participante, la fecha de creación de la cuenta |
| 11 | + * y ordene los resultados en dos listados. |
| 12 | + * - Usa el API de Twitch: https://dev.twitch.tv/docs/api/reference |
| 13 | + * (NO subas las credenciales de autenticación) |
| 14 | + * - Crea un ranking por número de seguidores y por antigüedad. |
| 15 | + * - Si algún participante no tiene usuario en Twitch, debe reflejarlo. |
| 16 | + */ |
| 17 | +""" |
| 18 | +import requests |
| 19 | +import datetime |
| 20 | +import os |
| 21 | + |
| 22 | +# NO subas las credenciales de autenticación |
| 23 | +os.environ["TWITCH_CLIENT_ID"] = "tu-id-de-twitch" |
| 24 | +os.environ["TWITCH_CLIENT_SECRET"] = "tu-key-secret-de-twitch" |
| 25 | + |
| 26 | + |
| 27 | +id = os.environ.get("TWITCH_CLIENT_ID") |
| 28 | +secret = os.environ.get("TWITCH_CLIENT_SECRET") |
| 29 | + |
| 30 | +# Clase para el token de acceso |
| 31 | +class Token: |
| 32 | + def __init__(self,id,secret) -> None: |
| 33 | + self.id = id |
| 34 | + self.secret = secret |
| 35 | + self.token = self.generate_token() |
| 36 | + def generate_token(self): |
| 37 | + url = "https://id.twitch.tv/oauth2/token" |
| 38 | + params = { |
| 39 | + "client_id": self.id, |
| 40 | + "client_secret": self.secret, |
| 41 | + "grant_type": "client_credentials" |
| 42 | + } |
| 43 | + |
| 44 | + response = requests.post(url,params=params) |
| 45 | + |
| 46 | + if response.status_code == 200: |
| 47 | + return response.json()["access_token"] |
| 48 | + |
| 49 | + else: |
| 50 | + response = response.json() |
| 51 | + print(f"Error: {response['status']}\n{response['message']}") |
| 52 | + return None |
| 53 | + |
| 54 | + |
| 55 | +class Participante: |
| 56 | + lista_participantes = [] |
| 57 | + mas_antiguo = [] |
| 58 | + mas_seguido = [] |
| 59 | + token = Token(id,secret) |
| 60 | + def __init__(self,nombre) -> None: |
| 61 | + self.nombre = nombre |
| 62 | + self.fecha_registro = None |
| 63 | + self.seguidores = 0 |
| 64 | + self.tiempo_total = 0 |
| 65 | + self.id = None |
| 66 | + |
| 67 | + Participante.lista_participantes.append(self) |
| 68 | + |
| 69 | + # Ordene los resultados en dos listados |
| 70 | + def ordenar_mas_antiguo(self): |
| 71 | + Participante.mas_antiguo = sorted(Participante.lista_participantes, key=lambda p: p.tiempo_total, reverse=True) |
| 72 | + |
| 73 | + def ordenar_mas_seguido(self): |
| 74 | + Participante.mas_seguido = sorted(Participante.lista_participantes, key=lambda p: p.seguidores, reverse=True) |
| 75 | + |
| 76 | + |
| 77 | + # Crea un ranking por número de seguidores y por antigüedad |
| 78 | + def mostrar_tabla_mas_antiguo(self): |
| 79 | + print("RANKING DE MAS ANTIGUOS") |
| 80 | + print("-"*50) |
| 81 | + for position, participante in enumerate(Participante.mas_antiguo): |
| 82 | + if participante.fecha_registro is None: |
| 83 | + print(f"{position+1}. {participante.nombre.upper()} no tiene cuenta de Twitch") |
| 84 | + else: |
| 85 | + print(f"{position+1}. {participante.nombre.upper()} creado el {participante.fecha_registro}") |
| 86 | + print("-"*30) |
| 87 | + print() |
| 88 | + print() |
| 89 | + def mostrar_tabla_mas_seguido(self): |
| 90 | + print("RANKING DE MAS SEGUIDOS") |
| 91 | + print("-"*50) |
| 92 | + for position, participante in enumerate(Participante.mas_seguido): |
| 93 | + if participante.seguidores == 0: |
| 94 | + print(f"{position+1}. {participante.nombre.upper()} no tiene seguidores o cuenta de Twitch") |
| 95 | + else: |
| 96 | + print(f"{position+1}. {participante.nombre.upper()} con {participante.seguidores} seguidores") |
| 97 | + print("-"*30) |
| 98 | + print() |
| 99 | + print() |
| 100 | + |
| 101 | + # Desarrolla un programa que obtenga el número de seguidores en |
| 102 | + # Twitch de cada participante, la fecha de creación de la cuenta |
| 103 | + def obtener_datos(self): |
| 104 | + # Usa el API de Twitch |
| 105 | + |
| 106 | + url = f"https://api.twitch.tv/helix/users?login={self.nombre}" |
| 107 | + headers = { |
| 108 | + 'Client-ID': Participante.token.id, |
| 109 | + 'Authorization': f'Bearer {Participante.token.token}', |
| 110 | + } |
| 111 | + |
| 112 | + response = requests.get(url, headers=headers) |
| 113 | + |
| 114 | + if response.status_code == 200 and len(response.json()["data"]) > 0: |
| 115 | + datos = response.json() |
| 116 | + self.id = datos["data"][0]["id"] |
| 117 | + # Obtenga la fecha de creación de la cuenta |
| 118 | + fecha_regisro = datos["data"][0]["created_at"][0:10] |
| 119 | + self.fecha_registro = datetime.datetime.strptime(fecha_regisro, "%Y-%m-%d").strftime("%d/%m/%Y") |
| 120 | + self.tiempo_total = datetime.datetime.now() - datetime.datetime.strptime(self.fecha_registro, "%d/%m/%Y") |
| 121 | + self.tiempo_total = self.tiempo_total.days |
| 122 | + |
| 123 | + print(f"Usuario {self.nombre.upper()} registrado") |
| 124 | + else: |
| 125 | + # Si algún participante no tiene usuario en Twitch, debe reflejarlo |
| 126 | + print(f"No se encontro el usuario {self.nombre.upper()}") |
| 127 | + self.tiempo_total = 0 |
| 128 | + |
| 129 | + |
| 130 | + # Obtenga el número de seguidores |
| 131 | + def obtener_seguidores(self): |
| 132 | + if self.id is None: |
| 133 | + self.seguidores = 0 |
| 134 | + else: |
| 135 | + url = f"https://api.twitch.tv/helix/channels/followers" |
| 136 | + |
| 137 | + params = { |
| 138 | + "broadcaster_id": self.id |
| 139 | + } |
| 140 | + headers = { |
| 141 | + 'Client-ID': Participante.token.id, |
| 142 | + 'Authorization': f'Bearer {Participante.token.token}', |
| 143 | + } |
| 144 | + |
| 145 | + response = requests.get(url, headers=headers,params=params) |
| 146 | + |
| 147 | + if response.status_code == 200: |
| 148 | + response = response.json() |
| 149 | + self.seguidores = response['total'] |
| 150 | + |
| 151 | + else: |
| 152 | + print(f"Error: {response.status_code}\n{response.json()['message']}") |
| 153 | + self.seguidores = 0 |
| 154 | + |
| 155 | + |
| 156 | + |
| 157 | + |
| 158 | + |
| 159 | +# Pruebas |
| 160 | + |
| 161 | +lista = [ |
| 162 | + "littleragergirl","ache","AdriContreras4","agustin51","alexby11","ampeterby7", |
| 163 | + "tvandeR","arigameplays","arigeli_","auronplay","axozer","beniju03","bycalitos", |
| 164 | + "byviruzz","carreraaa","celopan","srcheeto","crystalmolly","darioemehache", |
| 165 | + "dheylo","djmariio","doble","elvisayomastercard","elyas360","folagorlives", |
| 166 | + "thegrefg","guanyar","hika","hiperop","ibai","ibelky_","illojuan","imantado", |
| 167 | + "irinaisasia","jesskiu","jopa","jordiwild","kenaisouza","keroro","kiddkeo", |
| 168 | + "kikorivera","knekro","kokorok","kronnozomber","leviathan","lolkilla","lola_lolita", |
| 169 | + "lolito","luzu","mangel","mayichi","meelo","missasofia","mixwell","mrjagger", |
| 170 | + "nategentile","nexxuz","nissaxter","ollie","orslok","outconsumer","papigavi", |
| 171 | + "paracetamor","patica","paulagonu","pausenpaii","perxita","plex","polispol", |
| 172 | + "quackity","recuerdop","reven","rivers","robertpg","roier","rojuu","rubius", |
| 173 | + "shadoune","silithur","spreen","spursito","staxx","suzyrox","vicens","vituber", |
| 174 | + "werlyb","xavi","xcrystal","xokas","zarcort","zeling","zorman" |
| 175 | +] |
| 176 | + |
| 177 | +for i in lista: |
| 178 | + p = Participante(i) |
| 179 | + p.obtener_datos() |
| 180 | + p.obtener_seguidores() |
| 181 | + |
| 182 | +Participante.ordenar_mas_antiguo(Participante) |
| 183 | +Participante.ordenar_mas_seguido(Participante) |
| 184 | + |
| 185 | +Participante.mostrar_tabla_mas_seguido(Participante) |
| 186 | +Participante.mostrar_tabla_mas_antiguo(Participante) |
0 commit comments