Skip to content

Commit 353d4b2

Browse files
committed
1 parent 6fd66a4 commit 353d4b2

File tree

3 files changed

+220
-0
lines changed

3 files changed

+220
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
// Autor: Héctor Adán
2+
// GitHub: https://github.com/hectorio23
3+
4+
#include <iostream>
5+
#include <vector>
6+
#include <string>
7+
#include <curl/curl.h>
8+
#include <json/json.h> // Incluye la biblioteca JSONcpp (debe estar instalada)
9+
10+
// Función callback para manejar la respuesta HTTP y almacenarla en una cadena
11+
size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* s) {
12+
s->append((char*)contents, size * nmemb);
13+
return size * nmemb;
14+
}
15+
16+
// Realiza la solicitud HTTP a la API de Twitch y devuelve la respuesta como cadena
17+
std::string make_request(const std::string& url, const std::string& auth_token) {
18+
CURL* curl;
19+
CURLcode res;
20+
std::string response_string;
21+
22+
curl = curl_easy_init();
23+
if (curl) {
24+
struct curl_slist* headers = NULL;
25+
headers = curl_slist_append(headers, ("Authorization: Bearer " + auth_token).c_str());
26+
headers = curl_slist_append(headers, "Client-ID: YOUR_CLIENT_ID");
27+
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
28+
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
29+
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
30+
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string);
31+
32+
res = curl_easy_perform(curl);
33+
curl_easy_cleanup(curl);
34+
}
35+
return response_string;
36+
}
37+
38+
// Procesa la respuesta JSON para obtener el número de seguidores y la fecha de creación
39+
void process_data(const std::vector<std::string>& participants, const std::string& auth_token) {
40+
Json::CharReaderBuilder readerBuilder;
41+
Json::Value root;
42+
std::string errs;
43+
44+
for (const auto& user : participants) {
45+
std::string url = "https://api.twitch.tv/helix/users?login=" + user;
46+
std::string response = make_request(url, auth_token);
47+
48+
// Parseamos la respuesta JSON
49+
std::stringstream ss(response);
50+
if (Json::parseFromStream(readerBuilder, ss, &root, &errs)) {
51+
const auto& data = root["data"];
52+
if (!data.empty()) {
53+
const std::string userId = data[0]["id"].asString();
54+
const std::string creationDate = data[0]["created_at"].asString();
55+
56+
// Solicitar el número de seguidores para este usuario
57+
std::string followers_url = "https://api.twitch.tv/helix/users/follows?to_id=" + userId;
58+
std::string followers_response = make_request(followers_url, auth_token);
59+
60+
Json::Value followers_root;
61+
std::stringstream ss_followers(followers_response);
62+
if (Json::parseFromStream(readerBuilder, ss_followers, &followers_root, &errs)) {
63+
int total_followers = followers_root["total"].asInt();
64+
65+
// Imprime la información del usuario
66+
std::cout << "Usuario: " << user << "\n";
67+
std::cout << "Seguidores: " << total_followers << "\n";
68+
std::cout << "Fecha de creación: " << creationDate << "\n\n";
69+
} else {
70+
std::cerr << "Error al parsear la respuesta de seguidores de " << user << ": " << errs << "\n";
71+
}
72+
} else {
73+
std::cout << "El usuario " << user << " no existe en Twitch.\n\n";
74+
}
75+
} else {
76+
std::cerr << "Error al parsear la respuesta de Twitch para " << user << ": " << errs << "\n";
77+
}
78+
}
79+
}
80+
81+
int main() {
82+
std::vector<std::string> participants = {"user1", "user2", "user3"}; // Lista de participantes
83+
std::string auth_token = "YOUR_AUTH_TOKEN"; // Debes usar un token válido
84+
85+
process_data(participants, auth_token);
86+
87+
return 0;
88+
}
89+
90+
// Para cmpilar el programa en un sistema tipo UNIX usa la siguiente instruccion
91+
// g++ -std=c++11 -lcurl -ljsoncpp -o twitch_ranking twitch_ranking.cpp
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// Autor: Héctor Adán
2+
// GitHub: https://github.com/hectorio23
3+
4+
// npm install axios
5+
const axios = require('axios');
6+
7+
// Función para obtener datos de un usuario de Twitch.
8+
async function getTwitchUserData(username, authToken) {
9+
const headers = {
10+
'Client-ID': 'YOUR_CLIENT_ID',
11+
'Authorization': `Bearer ${authToken}`
12+
};
13+
14+
try {
15+
const response = await axios.get(`https://api.twitch.tv/helix/users?login=${username}`, { headers });
16+
if (response.data.data.length > 0) {
17+
const user = response.data.data[0];
18+
const followers = await getTwitchFollowers(user.id, authToken);
19+
return { username, followers, created_at: user.created_at };
20+
} else {
21+
return { username, followers: null, created_at: null };
22+
}
23+
} catch (error) {
24+
console.error(`Error fetching data for ${username}:`, error);
25+
}
26+
}
27+
28+
// Función para obtener el número de seguidores de un usuario de Twitch.
29+
async function getTwitchFollowers(userId, authToken) {
30+
const headers = {
31+
'Client-ID': 'YOUR_CLIENT_ID',
32+
'Authorization': `Bearer ${authToken}`
33+
};
34+
35+
const response = await axios.get(`https://api.twitch.tv/helix/users/follows?to_id=${userId}`, { headers });
36+
return response.data.total;
37+
}
38+
39+
// Genera el ranking por seguidores y por antigüedad.
40+
async function generateRankings(participants, authToken) {
41+
const userData = await Promise.all(participants.map(user => getTwitchUserData(user, authToken)));
42+
43+
// Ranking por seguidores.
44+
const byFollowers = userData.filter(u => u.followers !== null).sort((a, b) => b.followers - a.followers);
45+
46+
// Ranking por antigüedad.
47+
const byCreationDate = userData.filter(u => u.created_at !== null).sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
48+
49+
return { byFollowers, byCreationDate };
50+
}
51+
52+
// Ejemplo de uso.
53+
(async () => {
54+
const participants = ["user1", "user2", "user3"];
55+
const authToken = "YOUR_AUTH_TOKEN";
56+
57+
const { byFollowers, byCreationDate } = await generateRankings(participants, authToken);
58+
59+
console.log("Ranking por seguidores:");
60+
byFollowers.forEach(user => console.log(`${user.username} - ${user.followers} seguidores`));
61+
62+
console.log("\nRanking por antigüedad:");
63+
byCreationDate.forEach(user => console.log(`${user.username} - Creado el ${user.created_at}`));
64+
})();
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# Autor: Héctor Adán
2+
# GitHub: https://github.com/hectorio23
3+
4+
import requests
5+
6+
# Función para obtener datos de un usuario de Twitch.
7+
def get_twitch_user_data(username, auth_token):
8+
url = f"https://api.twitch.tv/helix/users?login={username}"
9+
headers = {
10+
'Client-ID': 'YOUR_CLIENT_ID',
11+
'Authorization': f'Bearer {auth_token}'
12+
}
13+
response = requests.get(url, headers=headers)
14+
15+
if response.status_code == 200:
16+
data = response.json()['data']
17+
if data:
18+
return {
19+
'username': username,
20+
'followers': get_twitch_followers(data[0]['id'], auth_token),
21+
'created_at': data[0]['created_at']
22+
}
23+
else:
24+
return {'username': username, 'followers': None, 'created_at': None}
25+
else:
26+
raise Exception(f"Error in API request: {response.status_code}")
27+
28+
# Función para obtener el número de seguidores de un usuario de Twitch.
29+
def get_twitch_followers(user_id, auth_token):
30+
url = f"https://api.twitch.tv/helix/users/follows?to_id={user_id}"
31+
headers = {
32+
'Client-ID': 'YOUR_CLIENT_ID',
33+
'Authorization': f'Bearer {auth_token}'
34+
}
35+
response = requests.get(url, headers=headers)
36+
if response.status_code == 200:
37+
return response.json()['total']
38+
return None
39+
40+
# Genera el ranking por seguidores y por antigüedad.
41+
def generate_rankings(participants, auth_token):
42+
user_data = [get_twitch_user_data(user, auth_token) for user in participants]
43+
44+
# Ranking por seguidores.
45+
by_followers = sorted([u for u in user_data if u['followers'] is not None], key=lambda x: x['followers'], reverse=True)
46+
47+
# Ranking por antigüedad.
48+
by_creation_date = sorted([u for u in user_data if u['created_at'] is not None], key=lambda x: x['created_at'])
49+
50+
return by_followers, by_creation_date
51+
52+
# Ejemplo de uso:
53+
if __name__ == "__main__":
54+
participants = ["user1", "user2", "user3"]
55+
auth_token = "YOUR_AUTH_TOKEN"
56+
57+
followers_ranking, creation_ranking = generate_rankings(participants, auth_token)
58+
59+
print("Ranking por seguidores:")
60+
for user in followers_ranking:
61+
print(f"{user['username']} - {user['followers']} seguidores")
62+
63+
print("\nRanking por antigüedad:")
64+
for user in creation_ranking:
65+
print(f"{user['username']} - Creado el {user['created_at']}")

0 commit comments

Comments
 (0)