# GAMEMONITORING > REST API GAMEMONITORING zwraca dane JSON o serwerach, graczach, wpisach, historii online i głosach. Ta strona opisuje podstawy integracji i pierwsze żądanie. Parametry i testowanie żądań są dostępne na stronach metod. - [API GAMEMONITORING](https://gamemonitoring.pl/developers/docs/api.md) - [GAMEMONITORING MCP](https://gamemonitoring.pl/developers/docs/mcp.md) - [Dodaj serwer](https://gamemonitoring.pl/developers/docs/api/servers/__post.md) - [Serwer](https://gamemonitoring.pl/developers/docs/api/servers/:server_id/__get.md) - [Gracze serwera](https://gamemonitoring.pl/developers/docs/api/servers/:server_id/players/__get.md) - [Posty ze wzmianką o serwerze](https://gamemonitoring.pl/developers/docs/api/servers/:server_id/posts/__get.md) - [Wykres liczby graczy serwera](https://gamemonitoring.pl/developers/docs/api/servers/:server_id/stats/players_online/__get.md) - [Głosy serwera](https://gamemonitoring.pl/developers/docs/api/servers/:server_id/votes/__get.md) - [Wykres głosów serwera](https://gamemonitoring.pl/developers/docs/api/servers/:server_id/votes/chart/__get.md) - [Najaktywniej głosujący na serwer](https://gamemonitoring.pl/developers/docs/api/servers/:server_id/votes/top/__get.md) - [Wykres liczby graczy projektu](https://gamemonitoring.pl/developers/docs/api/projects/:project_id/stats/players_online/__get.md) - [Głosy projektu](https://gamemonitoring.pl/developers/docs/api/projects/:project_id/votes/__get.md) - [Wykres głosów projektu](https://gamemonitoring.pl/developers/docs/api/projects/:project_id/votes/chart/__get.md) - [Najaktywniej głosujący na projekt](https://gamemonitoring.pl/developers/docs/api/projects/:project_id/votes/top/__get.md) - [Głos](https://gamemonitoring.pl/developers/docs/api/votes/:vote_id/__get.md) - [Potwierdź przetworzenie głosu](https://gamemonitoring.pl/developers/docs/api/votes/:vote_id/claim/__post.md) - [Profil użytkownika](https://gamemonitoring.pl/developers/docs/api/users/:id/__get.md) - [Potwierdź własność konta](https://gamemonitoring.pl/developers/docs/api/users/verify-code/__post.md) - [Webhook](https://gamemonitoring.pl/developers/docs/webhook.md) - [Nagrody za głosy](https://gamemonitoring.pl/developers/docs/webhook/vote.md) - [Adresy IP systemu](https://gamemonitoring.pl/developers/docs/ips.md) - [OpenAPI](https://gamemonitoring.pl/developers/docs/openapi.json) - [Pełna dokumentacja](https://gamemonitoring.pl/developers/docs/llms-full.txt) - [GAMEMONITORING MCP](https://api.gamemonitoring.net/mcp) --- # API GAMEMONITORING REST API GAMEMONITORING zwraca dane JSON o serwerach, graczach, wpisach, historii online i głosach. Ta strona opisuje podstawy integracji i pierwsze żądanie. Parametry i testowanie żądań są dostępne na stronach metod. ## Adres bazowy https://api.gamemonitoring.pl ## Pierwsze żądanie Zacznij od publicznych danych serwera. Identyfikator serwera znajdziesz na końcu adresu jego strony w GAMEMONITORING. ```bash curl --header 'Accept: application/json' 'https://api.gamemonitoring.pl/servers/1' ``` ## Wybierz metodę - [POST /servers — Dodaj serwer](https://gamemonitoring.pl/developers/docs/api/servers/__post.md) - [GET /servers/{server_id} — Serwer](https://gamemonitoring.pl/developers/docs/api/servers/:server_id/__get.md) - [GET /servers/{server_id}/players — Gracze serwera](https://gamemonitoring.pl/developers/docs/api/servers/:server_id/players/__get.md) - [GET /servers/{server_id}/posts — Posty ze wzmianką o serwerze](https://gamemonitoring.pl/developers/docs/api/servers/:server_id/posts/__get.md) - [GET /servers/{server_id}/stats/players_online — Wykres liczby graczy serwera](https://gamemonitoring.pl/developers/docs/api/servers/:server_id/stats/players_online/__get.md) - [GET /servers/{server_id}/votes — Głosy serwera](https://gamemonitoring.pl/developers/docs/api/servers/:server_id/votes/__get.md) - [GET /servers/{server_id}/votes/chart — Wykres głosów serwera](https://gamemonitoring.pl/developers/docs/api/servers/:server_id/votes/chart/__get.md) - [GET /servers/{server_id}/votes/top — Najaktywniej głosujący na serwer](https://gamemonitoring.pl/developers/docs/api/servers/:server_id/votes/top/__get.md) - [GET /projects/{project_id}/stats/players_online — Wykres liczby graczy projektu](https://gamemonitoring.pl/developers/docs/api/projects/:project_id/stats/players_online/__get.md) - [GET /projects/{project_id}/votes — Głosy projektu](https://gamemonitoring.pl/developers/docs/api/projects/:project_id/votes/__get.md) - [GET /projects/{project_id}/votes/chart — Wykres głosów projektu](https://gamemonitoring.pl/developers/docs/api/projects/:project_id/votes/chart/__get.md) - [GET /projects/{project_id}/votes/top — Najaktywniej głosujący na projekt](https://gamemonitoring.pl/developers/docs/api/projects/:project_id/votes/top/__get.md) - [GET /votes/{vote_id} — Głos](https://gamemonitoring.pl/developers/docs/api/votes/:vote_id/__get.md) - [POST /votes/{vote_id}/claim — Potwierdź przetworzenie głosu](https://gamemonitoring.pl/developers/docs/api/votes/:vote_id/claim/__post.md) - [GET /users/{id} — Profil użytkownika](https://gamemonitoring.pl/developers/docs/api/users/:id/__get.md) - [POST /users/verify-code — Potwierdź własność konta](https://gamemonitoring.pl/developers/docs/api/users/verify-code/__post.md) ## Wersje API Wersję API można wybrać za pomocą opcjonalnego parametru zapytania v. Obecna wersja to 1.0.0. Wersja określa dostępne ścieżki, pola żądania i format odpowiedzi. Bez v używana jest najniższa obsługiwana wersja. Po jej wycofaniu kolejna najniższa wersja staje się domyślna. Podaj v, aby zachować ustalony kontrakt. Nieprawidłowa, powtórzona lub nieobsługiwana wersja zwraca HTTP 400; dla nieobsługiwanej wersji dostępne wartości są w error.data.supported_versions. ## Przekazywanie parametrów ID podaje się w ścieżce: server_id i project_id to numeryczne ID GAMEMONITORING, a vote_id identyfikuje głos. Zastąp parametry w nawiasach klamrowych konkretnymi wartościami. Filtry, okresy i paginację podaje się po ? w URL. Koduj wartości przez URLSearchParams lub funkcję swojej biblioteki, szczególnie nicki i tekst wyszukiwania. Aby dodać serwer, wyślij JSON z Content-Type: application/json. connect to publiczny host:port, a steam_app_id to Steam App ID gry. query jest potrzebny, gdy port zapytań różni się od portu połączenia. ## Format danych HTTP 200 umieszcza wynik w response: obiekt, tablicę lub obiekt z items zależnie od metody. Sprawdź schemat metody; pusta lista sama w sobie nie jest błędem. Pola mogą być null lub nie występować. To nie to samo co 0, false czy pusty tekst; obsłuż brak danych osobno. created_at, expires_at i last_update używają czasu Unix w sekundach. Dla JavaScript Date pomnóż przez 1000; dla filtrów podziel Date.now() przez 1000 i zaokrąglij w dół. Przechowuj 64-bitowe identyfikatory Steam jako tekst. Konwersja na JavaScript Number może utracić precyzję. ID serwera GAMEMONITORING i Steam App ID gry to różne identyfikatory. ## Błędy i ponawianie żądań Sprawdzaj status HTTP i obiekt error: code zawiera kod, message opis, a data dodatkowe dane, jeśli są dostępne. Tekst zależy od regionu i może się zmieniać; nie używaj go jako warunku w kodzie. Przed ponowieniem popraw parametry lub uprawnienia. Obsłuż też błędy sieci i odpowiedzi proxy, które mogą nie zawierać JSON. Dane pochodzą z ostatniego zapytania do serwera i mogą być buforowane. Sprawdzaj last_update, stosuj rozsądny odstęp odświeżania i buforuj wynik w integracji. Częste pytania do API nie przyspieszają aktualizacji serwera gry. ## Głosowanie i Webhook Skonfiguruj Webhook projektu, aby reagować na nowy głos. Sprawdź signature, pomiń testy is_test=true i użyj event_id jako vote_id do pobrania głosu z API. Sprawdź entity_type i entity_id, a zdarzenie przetwarzaj raz według pary event_type + event_id. Potwierdzaj zdarzenia testowe odpowiedzią 2xx bez przyznawania nagrody. ## Pomoc z integracją Zgłaszając błąd, podaj metodę HTTP, ścieżkę, parametry, czas żądania, status HTTP i zwrócony error. Te dane pomagają odtworzyć problem. ## OpenAPI ```json { "openapi": "3.1.1", "info": { "title": "GAMEMONITORING", "version": "1.0.0" }, "paths": { "/servers": { "post": { "operationId": "createServer", "summary": "Dodaj serwer", "description": "Dodaje serwer na podstawie adresu połączenia lub zwraca istniejący serwer.", "parameters": [ { "$ref": "#/components/parameters/ApiVersion" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "properties": { "connect": { "type": "string", "minLength": 1, "example": "198.51.100.24:27015" }, "steam_app_id": { "type": "integer", "minimum": 0, "example": 730 }, "query": { "type": "integer", "minimum": 10, "maximum": 65535, "example": 27016 } }, "required": [ "connect", "steam_app_id" ] }, "example": { "connect": "198.51.100.24:27015", "steam_app_id": 730 } } } }, "responses": { "200": { "description": "Created or existing server", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ServerCreateResult" }, "example": { "response": { "connect": "198.51.100.24:27015", "game": 730, "id": 100001, "name": "Example Arena", "request": "198.51.100.24:27016", "status": true } } } } }, "400": { "description": "Missing game or address, invalid address or offline server" }, "403": { "description": "Blocked address" }, "409": { "description": "Query address is already in use" }, "503": { "description": "Server creation service is unavailable" }, "504": { "$ref": "#/components/responses/QueryTimeout" }, "default": { "$ref": "#/components/responses/UnexpectedError" } } } }, "/servers/{server_id}": { "get": { "operationId": "getServer", "summary": "Serwer", "description": "Zwraca publiczne dane serwera.", "parameters": [ { "$ref": "#/components/parameters/ApiVersion" }, { "name": "server_id", "in": "path", "required": true, "schema": { "type": "integer", "minimum": 1, "example": 1 } } ], "responses": { "200": { "description": "Server details response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ServerEnvelope" }, "example": { "response": { "steam_id": "90123456789012345", "domain": null, "id": 1, "ip": "198.51.100.24", "port": 27015, "query": 27015, "project_id": 42, "color": 0, "city": "Prague", "description": "[]", "game": 730, "boosts": 3, "last_offline": 1782751200, "last_online": 1783201200, "icon": null, "name": "Example CS2 Server", "connect": "198.51.100.24:27015", "request": "198.51.100.24:27015", "map": "de_mirage", "gamemode": "Counter-Strike 2", "version": "1.41.6.5", "numplayers": 12, "maxplayers": 64, "bots": 0, "secured": true, "private": false, "country": "CZ", "status": true, "votes": 128, "points": 2450, "add_date": 1701541119, "last_update": 1783201200, "ban_reason": null, "banned": false, "wipe": null, "official": null, "wipe_period": null, "next_wipe": null, "pve": null, "pvp": null, "list_hidden": false, "hide_address": false, "hide_query": false, "position_game": 12, "language": "en", "parked": false, "app": { "id": 2, "steam_id": 730, "name": "Counter-Strike 2", "url": "counter-strike-2" }, "mods": [ { "id": 5, "name": "Admin System" }, { "id": 14, "name": "Advertisement" }, { "id": 9, "name": "Admins" }, { "id": 3, "name": "Admin Commands" } ], "disabled_modules": [] } } } } }, "400": { "$ref": "#/components/responses/BadRequest" }, "404": { "$ref": "#/components/responses/NotFound" }, "503": { "$ref": "#/components/responses/ServiceUnavailable" }, "504": { "$ref": "#/components/responses/QueryTimeout" }, "default": { "$ref": "#/components/responses/UnexpectedError" } } } }, "/servers/{server_id}/players": { "get": { "operationId": "getServerPlayers", "summary": "Gracze serwera", "description": "Zwraca listę graczy serwera.", "parameters": [ { "$ref": "#/components/parameters/ApiVersion" }, { "name": "limit", "in": "query", "description": "Liczba elementów od 1 do 100, domyślnie 50", "schema": { "type": "integer", "minimum": 1, "maximum": 100, "default": 50, "example": 5 } }, { "$ref": "#/components/parameters/offset" }, { "name": "server_id", "in": "path", "required": true, "schema": { "type": "integer", "minimum": 1, "example": 1 } } ], "responses": { "200": { "description": "Server players", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ServerPlayersResult" }, "example": { "response": { "items": [ { "avatar": "no.jpg", "created": 1783200000, "last_online": 1783203600, "last_session_time": 0, "name": "NovaPlayer", "user": null, "username": null } ] } } } } }, "400": { "$ref": "#/components/responses/BadRequest" }, "503": { "$ref": "#/components/responses/ServiceUnavailable" }, "504": { "$ref": "#/components/responses/QueryTimeout" } } } }, "/servers/{server_id}/posts": { "get": { "operationId": "getServerPosts", "summary": "Posty ze wzmianką o serwerze", "description": "Zwraca publiczne posty z widoczną wzmianką o wskazanym serwerze.", "parameters": [ { "$ref": "#/components/parameters/ApiVersion" }, { "name": "before_created_at", "in": "query", "description": "Aby pobrać następną stronę, podaj `created_at` ostatniej publikacji w sekundach Unix i jej `id` w `before_id`. Zachowaj pozostałe filtry. Kursor działa, gdy nie podano `sort` ani `period`. Jeśli podano którykolwiek z tych parametrów, użyj `offset`.", "schema": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 } }, { "name": "before_id", "in": "query", "description": "ID publikacji kursora", "schema": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 } }, { "name": "conversation_post_id", "in": "query", "description": "ID publikacji w dyskusji", "schema": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 } }, { "name": "period", "in": "query", "description": "Użyj top, aby wybrać okres najlepszych publikacji.", "schema": { "type": "string", "const": "top" } }, { "name": "reply_to_post_id", "in": "query", "description": "ID publikacji nadrzędnej", "schema": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 } }, { "name": "root_only", "in": "query", "description": "Wartość 1 zwraca tylko publikacje główne", "schema": { "type": "number", "const": 1 } }, { "name": "sort", "in": "query", "description": "Kolejność publikacji. Dla najlepszych publikacji użyj helpful-desc.", "schema": { "type": "string" } }, { "name": "visibility", "in": "query", "description": "Ta operacja zwraca tylko publiczne publikacje.", "schema": { "type": "string", "const": "public" } }, { "name": "server_id", "in": "path", "required": true, "schema": { "type": "integer", "minimum": 1, "example": 1 } }, { "name": "limit", "in": "query", "description": "Liczba elementów od 1 do 100, domyślnie 20", "schema": { "type": "integer", "minimum": 1, "maximum": 100, "default": 20, "example": 5 } }, { "$ref": "#/components/parameters/offset" }, { "name": "search", "in": "query", "schema": { "type": "string", "maxLength": 120, "example": "admin" } } ], "responses": { "200": { "description": "Public posts mentioning the server", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ServerPostsResult" }, "example": { "response": [ { "id": 1001, "comment": "Great server! Thanks to the admin team.", "conversation_post_id": null, "language": "en", "moderation_needed": false, "replays": 0, "reply_to_post_id": null, "views": 25, "updated_at": null, "created_at": 1783200000, "translated_content": null, "user": { "avatar": "no.jpg", "id": 204801, "username": "demo_user" }, "images": [], "mentions": [ { "type": "server", "meta": { "game": { "id": 2, "name": "Counter-Strike 2", "steam_id": 730, "url": "counter-strike-2" }, "icon": null, "id": 1, "name": "Example CS2 Server" } } ], "reactions": [], "replays_items": [], "replays_items_count": 0 } ] } } } }, "400": { "$ref": "#/components/responses/BadRequest" }, "404": { "description": "Server not found" }, "503": { "$ref": "#/components/responses/ServiceUnavailable" }, "504": { "$ref": "#/components/responses/QueryTimeout" }, "default": { "$ref": "#/components/responses/UnexpectedError" } } } }, "/servers/{server_id}/stats/players_online": { "get": { "operationId": "getServerPlayerStats", "summary": "Wykres liczby graczy serwera", "description": "Zwraca wykres liczby graczy z minimum, średnią i maksimum dla każdego przedziału.", "parameters": [ { "$ref": "#/components/parameters/ApiVersion" }, { "name": "type", "in": "query", "description": "Okres statystyk: day, week lub month; domyślnie month", "schema": { "type": "string", "default": "month", "example": "week", "enum": [ "day", "week", "month" ] } }, { "name": "server_id", "in": "path", "required": true, "schema": { "type": "integer", "minimum": 1, "example": 1 } } ], "responses": { "200": { "description": "Player statistics grouped by time interval", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ServerPlayerStatsResult" }, "example": { "response": { "items": [ { "avg_players": 12, "date": 1783200000, "maps": [ "de_mirage" ], "max_players": 16, "min_players": 8, "x": 1783200000, "y": 16 } ] } } } } }, "400": { "$ref": "#/components/responses/BadRequest" }, "503": { "$ref": "#/components/responses/ServiceUnavailable" }, "504": { "$ref": "#/components/responses/QueryTimeout" }, "default": { "$ref": "#/components/responses/UnexpectedError" } } } }, "/servers/{server_id}/votes": { "get": { "operationId": "getServerVotes", "summary": "Głosy serwera", "description": "Zwraca listę głosów na wskazany serwer.", "parameters": [ { "$ref": "#/components/parameters/ApiVersion" }, { "name": "user_id", "in": "query", "description": "Identyfikator użytkownika", "schema": { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 } }, { "name": "server_id", "in": "path", "required": true, "schema": { "type": "integer", "minimum": 1, "example": 42 } }, { "$ref": "#/components/parameters/limit" }, { "$ref": "#/components/parameters/offset" }, { "$ref": "#/components/parameters/sort" }, { "$ref": "#/components/parameters/order" }, { "$ref": "#/components/parameters/claimed" }, { "$ref": "#/components/parameters/nickname" }, { "$ref": "#/components/parameters/created" }, { "$ref": "#/components/parameters/created__gt" }, { "$ref": "#/components/parameters/created__gte" }, { "$ref": "#/components/parameters/created__lt" }, { "$ref": "#/components/parameters/created__lte" }, { "$ref": "#/components/parameters/expire" }, { "$ref": "#/components/parameters/expire__gt" }, { "$ref": "#/components/parameters/expire__gte" }, { "$ref": "#/components/parameters/expire__lt" }, { "$ref": "#/components/parameters/expire__lte" } ], "security": [], "responses": { "200": { "description": "Successful response", "content": { "application/json": { "schema": { "type": "object", "properties": { "response": { "type": "array", "items": { "$ref": "#/components/schemas/VoteDetails" } } }, "required": [ "response" ] }, "example": { "response": [ { "claimed_at": null, "created_at": 1783200000, "entity_id": 42, "entity_type": "server", "expires_at": 1783243200, "id": "9824cabb-2203-437e-9b6c-aba43dde3e4b", "nickname": "NovaPlayer", "server": { "app": { "id": 2, "name": "Counter-Strike 2", "steam_id": 730, "url": "counter-strike-2" }, "game": 730, "icon": null, "id": 42, "name": "Example CS2 Server" }, "user": { "avatar": "no.jpg", "id": 204801, "username": "demo_user", "uuid": "d4f9c57e-7c8b-49c7-8d7e-b2f1a39f4a25", "connections": [] } } ] } } } }, "400": { "$ref": "#/components/responses/BadRequest" }, "503": { "$ref": "#/components/responses/ServiceUnavailable" }, "504": { "$ref": "#/components/responses/QueryTimeout" }, "default": { "$ref": "#/components/responses/UnexpectedError" } } } }, "/servers/{server_id}/votes/chart": { "get": { "operationId": "getServerVoteChart", "summary": "Wykres głosów serwera", "description": "Zwraca liczbę głosów według dni.", "security": [], "parameters": [ { "$ref": "#/components/parameters/ApiVersion" }, { "name": "server_id", "in": "path", "required": true, "schema": { "type": "integer", "minimum": 1, "example": 42 } }, { "$ref": "#/components/parameters/period" } ], "responses": { "200": { "description": "Successful response", "content": { "application/json": { "schema": { "type": "object", "properties": { "response": { "type": "array", "items": { "type": "object", "properties": { "x": { "type": [ "integer", "string" ] }, "y": { "type": [ "integer", "string" ] } } } } }, "required": [ "response" ] }, "example": { "response": [ { "x": 1800000000, "y": 10 } ] } } } }, "400": { "$ref": "#/components/responses/BadRequest" } } } }, "/servers/{server_id}/votes/top": { "get": { "operationId": "getServerTopVoters", "summary": "Najaktywniej głosujący na serwer", "description": "Zwraca użytkowników z największą liczbą głosów.", "security": [], "parameters": [ { "$ref": "#/components/parameters/ApiVersion" }, { "name": "server_id", "in": "path", "required": true, "schema": { "type": "integer", "minimum": 1, "example": 42 } }, { "$ref": "#/components/parameters/period" }, { "$ref": "#/components/parameters/limit" }, { "$ref": "#/components/parameters/offset" } ], "responses": { "200": { "description": "Successful response", "content": { "application/json": { "schema": { "type": "object", "properties": { "response": { "type": "array", "items": { "type": "object", "properties": { "counts": { "type": "object", "properties": { "active": { "type": [ "integer", "string" ] }, "total": { "type": [ "integer", "string" ] } } }, "last": { "type": "object", "properties": { "created_at": { "type": "integer" }, "expire_at": { "type": "integer" }, "nickname": { "type": "string" } } }, "user": { "type": "object", "properties": { "avatar": { "type": [ "string", "null" ] }, "username": { "type": "string" } } } } } } }, "required": [ "response" ] }, "example": { "response": [ { "counts": { "active": 2, "total": 10 }, "last": { "created_at": 1783200000, "expire_at": 1783243200, "nickname": "NovaPlayer" }, "user": { "avatar": "no.jpg", "username": "demo_user" } } ] } } } }, "400": { "$ref": "#/components/responses/BadRequest" } } } }, "/projects/{project_id}/stats/players_online": { "get": { "operationId": "getProjectPlayerStats", "summary": "Wykres liczby graczy projektu", "description": "Zwraca minimalną, średnią i maksymalną łączną liczbę graczy na serwerach projektu w każdym przedziale.", "security": [], "parameters": [ { "$ref": "#/components/parameters/ApiVersion" }, { "name": "type", "in": "query", "description": "Okres statystyk: day, week lub month; domyślnie month", "schema": { "type": "string", "default": "month", "example": "week", "enum": [ "day", "week", "month" ] } }, { "name": "project_id", "in": "path", "required": true, "schema": { "type": "integer", "minimum": 1, "example": 1 } } ], "responses": { "200": { "description": "Combined project player statistics grouped by time interval", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ProjectPlayerStatsResult" }, "example": { "response": { "items": [ { "avg_players": 12, "date": 1783200000, "max_players": 16, "min_players": 8, "x": 1783200000 } ] } } } } }, "400": { "$ref": "#/components/responses/BadRequest" }, "403": { "description": "Private project is not accessible to the requester" }, "404": { "description": "Project not found" } } } }, "/projects/{project_id}/votes": { "get": { "operationId": "getProjectVotes", "summary": "Głosy projektu", "description": "Zwraca głosy na projekt. Bez uwierzytelniania dostępne są tylko projekty publiczne.", "parameters": [ { "$ref": "#/components/parameters/ApiVersion" }, { "name": "user_id", "in": "query", "description": "Identyfikator użytkownika", "schema": { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 } }, { "name": "project_id", "in": "path", "required": true, "schema": { "type": "integer", "minimum": 1, "example": 42 } }, { "$ref": "#/components/parameters/limit" }, { "$ref": "#/components/parameters/offset" }, { "$ref": "#/components/parameters/sort" }, { "$ref": "#/components/parameters/order" }, { "$ref": "#/components/parameters/claimed" }, { "$ref": "#/components/parameters/nickname" }, { "$ref": "#/components/parameters/created" }, { "$ref": "#/components/parameters/created__gt" }, { "$ref": "#/components/parameters/created__gte" }, { "$ref": "#/components/parameters/created__lt" }, { "$ref": "#/components/parameters/created__lte" }, { "$ref": "#/components/parameters/expire" }, { "$ref": "#/components/parameters/expire__gt" }, { "$ref": "#/components/parameters/expire__gte" }, { "$ref": "#/components/parameters/expire__lt" }, { "$ref": "#/components/parameters/expire__lte" } ], "security": [], "responses": { "200": { "description": "Successful response", "content": { "application/json": { "schema": { "type": "object", "properties": { "response": { "type": "array", "items": { "$ref": "#/components/schemas/VoteDetails" } } }, "required": [ "response" ] }, "example": { "response": [ { "claimed_at": null, "created_at": 1783200000, "entity_id": 42, "entity_type": "project", "expires_at": 1785792000, "id": "7206f073-2f18-4660-91b8-bd947fbc4be2", "nickname": "NovaPlayer", "project": { "id": 42 }, "user": { "avatar": "no.jpg", "id": 204801, "username": "demo_user", "uuid": "d4f9c57e-7c8b-49c7-8d7e-b2f1a39f4a25", "connections": [] } } ] } } } }, "400": { "$ref": "#/components/responses/BadRequest" }, "403": { "description": "Private project is not accessible to the requester" }, "404": { "description": "Project not found" }, "503": { "$ref": "#/components/responses/ServiceUnavailable" }, "504": { "$ref": "#/components/responses/QueryTimeout" }, "default": { "$ref": "#/components/responses/UnexpectedError" } } } }, "/projects/{project_id}/votes/chart": { "get": { "operationId": "getProjectVoteChart", "summary": "Wykres głosów projektu", "description": "Zwraca dzienną liczbę głosów na projekt. Bez uwierzytelniania dostępne są tylko projekty publiczne.", "security": [], "parameters": [ { "$ref": "#/components/parameters/ApiVersion" }, { "name": "project_id", "in": "path", "required": true, "schema": { "type": "integer", "minimum": 1, "example": 42 } }, { "$ref": "#/components/parameters/period" } ], "responses": { "200": { "description": "Successful response", "content": { "application/json": { "schema": { "type": "object", "properties": { "response": { "type": "array", "items": { "type": "object", "properties": { "x": { "type": [ "integer", "string" ] }, "y": { "type": [ "integer", "string" ] } } } } }, "required": [ "response" ] }, "example": { "response": [ { "x": 1800000000, "y": 10 } ] } } } }, "400": { "$ref": "#/components/responses/BadRequest" }, "403": { "description": "Private project is not accessible to the requester" }, "404": { "description": "Project not found" } } } }, "/projects/{project_id}/votes/top": { "get": { "operationId": "getProjectTopVoters", "summary": "Najaktywniej głosujący na projekt", "description": "Zwraca użytkowników z największą liczbą głosów na projekt. Bez uwierzytelniania dostępne są tylko projekty publiczne.", "security": [], "parameters": [ { "$ref": "#/components/parameters/ApiVersion" }, { "name": "project_id", "in": "path", "required": true, "schema": { "type": "integer", "minimum": 1, "example": 42 } }, { "$ref": "#/components/parameters/period" }, { "$ref": "#/components/parameters/limit" }, { "$ref": "#/components/parameters/offset" } ], "responses": { "200": { "description": "Successful response", "content": { "application/json": { "schema": { "type": "object", "properties": { "response": { "type": "array", "items": { "type": "object", "properties": { "counts": { "type": "object", "properties": { "active": { "type": [ "integer", "string" ] }, "total": { "type": [ "integer", "string" ] } } }, "last": { "type": "object", "properties": { "created_at": { "type": "integer" }, "expire_at": { "type": "integer" }, "nickname": { "type": "string" } } }, "user": { "type": "object", "properties": { "avatar": { "type": [ "string", "null" ] }, "username": { "type": "string" } } } } } } }, "required": [ "response" ] }, "example": { "response": [ { "counts": { "active": 2, "total": 10 }, "last": { "created_at": 1783200000, "expire_at": 1785792000, "nickname": "NovaPlayer" }, "user": { "avatar": "no.jpg", "username": "demo_user" } } ] } } } }, "400": { "$ref": "#/components/responses/BadRequest" }, "403": { "description": "Private project is not accessible to the requester" }, "404": { "description": "Project not found" } } } }, "/votes/{vote_id}": { "get": { "operationId": "getVote", "summary": "Głos", "description": "Zwraca informacje o głosie według jego ID.", "parameters": [ { "$ref": "#/components/parameters/ApiVersion" }, { "name": "vote_id", "in": "path", "required": true, "schema": { "type": "string", "minLength": 1, "example": "9824cabb-2203-437e-9b6c-aba43dde3e4b" } } ], "responses": { "200": { "description": "Vote details response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/VoteDetailsEnvelope" }, "example": { "response": { "created_at": 1783200000, "expires_at": 1783243200, "id": "6f59a4a8-2f0f-4d96-a50a-9d7a21f4b812", "entity_id": 100001, "entity_type": "server", "nickname": "NovaPlayer", "server": { "app": { "id": 2400, "name": "Example Shooter", "steam_id": 111111, "url": "example-shooter" }, "game": 111111, "icon": null, "id": 100001, "name": "Example Arena" }, "user": { "avatar": "8f14e45f-e9a1-4f4d-a9f3-6d7b0d4a2c18.webp", "id": 204801, "username": "demo_user", "uuid": "d4f9c57e-7c8b-49c7-8d7e-b2f1a39f4a25", "connections": [ { "id": "100000000000000001", "name": "demo_user", "type": "discord", "url": "https://discord.com/users/100000000000000001" }, { "id": "76561198000000001", "name": "NovaPlayer", "type": "steam", "url": "https://steamcommunity.com/profiles/76561198000000001" } ] }, "claimed_at": null } } } } }, "400": { "$ref": "#/components/responses/BadRequest" }, "403": { "$ref": "#/components/responses/Forbidden" }, "404": { "$ref": "#/components/responses/NotFound" }, "503": { "$ref": "#/components/responses/ServiceUnavailable" }, "504": { "$ref": "#/components/responses/QueryTimeout" }, "default": { "$ref": "#/components/responses/UnexpectedError" } }, "security": [] } }, "/votes/{vote_id}/claim": { "post": { "operationId": "claimVote", "summary": "Potwierdź przetworzenie głosu", "description": "Oznacza głos jako przetworzony. Dostępne dla właściciela serwera lub projektu.", "security": [ { "AccountAPIKey": [] } ], "parameters": [ { "$ref": "#/components/parameters/ApiVersion" }, { "name": "vote_id", "in": "path", "required": true, "schema": { "type": "string", "minLength": 1, "example": "9824cabb-2203-437e-9b6c-aba43dde3e4b" } } ], "responses": { "200": { "description": "Successful response", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/VoteClaimResult" }, "example": { "response": { "success": true } } } } }, "400": { "$ref": "#/components/responses/BadRequest" }, "401": { "description": "Missing, invalid, expired or revoked credential." }, "403": { "description": "Missing API key scope, restricted account or entity ownership." }, "404": { "description": "Unknown vote or invalid entity association." }, "429": { "description": "Account claim quota exceeded: 12 000 per minute. Honor Retry-After." } } } }, "/users/{id}": { "get": { "operationId": "getPublicUser", "summary": "Profil użytkownika", "description": "Zwraca dane profilu użytkownika.", "security": [], "parameters": [ { "$ref": "#/components/parameters/ApiVersion" }, { "name": "id", "in": "path", "required": true, "description": "ID konta.", "schema": { "type": "string", "format": "uuid", "example": "ef57cc6f-f068-11ef-a5bf-d00d12c6f2dd" } } ], "responses": { "200": { "description": "User profile.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/UserProfileResult" }, "example": { "response": { "avatar": "447f9470-325b-4e0a-ada0-f4f1659ef805.png", "id": 1, "username": "GAMEMONITORING", "banner": "469ebf64-206c-4374-a742-7730ea227f95.webp", "connections": [ { "account_id": "76561197960287930", "account_level": 1, "id": 220354, "name": "Rabscuttle", "platform": { "icon": null, "id": 3, "name": "Steam", "url": "steam" } } ], "created": 1435235037, "last_online": 1793734264, "uuid": "ef57cc6f-f068-11ef-a5bf-d00d12c6f2dd" } } } } }, "400": { "$ref": "#/components/responses/BadRequest" }, "404": { "description": "User not found." } } } }, "/users/verify-code": { "post": { "operationId": "verifyUserCode", "summary": "Potwierdź własność konta", "description": "Aby potwierdzić własność konta GAMEMONITORING, użytkownik pobiera kod w sekcji „[Integracja](/settings/integration)”. Kod jest ważny przez 5 minut od wydania. Po udanej weryfikacji API zwraca identyfikator konta, dla którego wydano kod, i oznacza kod jako wykorzystany.", "security": [], "parameters": [ { "$ref": "#/components/parameters/ApiVersion" } ], "requestBody": { "required": true, "content": { "application/json": { "schema": { "type": "object", "additionalProperties": false, "required": [ "code" ], "properties": { "code": { "type": "string", "description": "Jednorazowy kod weryfikacji konta. Wielkość liter nie ma znaczenia.", "pattern": "^\\s*[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{4}(?:-[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{4}){2}\\s*$", "example": "7KMD-P9RX-3WHT" } } } } } }, "responses": { "200": { "description": "The stable GAMEMONITORING account ID.", "headers": { "Cache-Control": { "schema": { "type": "string" }, "example": "no-store" } }, "content": { "application/json": { "schema": { "type": "object", "additionalProperties": false, "required": [ "response" ], "properties": { "response": { "type": "object", "additionalProperties": false, "required": [ "id" ], "properties": { "id": { "type": "string", "format": "uuid" } } } } }, "example": { "response": { "id": "550e8400-e29b-41d4-a716-446655440000" } } } } }, "400": { "description": "Invalid request or code format." }, "404": { "description": "Unknown, expired or already redeemed code." }, "429": { "description": "Too many requests." }, "503": { "description": "A required service is temporarily unavailable." } } } } }, "components": { "schemas": { "ErrorEnvelope": { "type": "object", "required": [ "error" ], "properties": { "error": { "type": "object", "required": [ "code", "message" ], "properties": { "code": { "type": "integer", "description": "Kod odpowiedzi HTTP." }, "message": { "type": "string", "description": "Komunikat w języku API. Treść może się zmieniać; obsługuj błędy na podstawie kodu odpowiedzi." }, "data": { "description": "Dodatkowe szczegóły błędu, jeśli są dostępne." } } } } }, "Server": { "type": "object", "properties": { "add_date": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ], "description": "Czas Unix w sekundach (UTC)." }, "app": { "anyOf": [ { "type": "object", "properties": { "id": { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, "name": { "type": "string" }, "steam_id": { "description": "Steam App ID of the game. Use this as game_steam_id when searching servers.", "anyOf": [ { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "string" } ] }, { "type": "null" } ] }, "url": { "type": "string" } }, "additionalProperties": {} }, { "type": "null" } ] }, "color": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ] }, "connect": { "type": [ "string", "null" ] }, "country": { "type": [ "string", "null" ] }, "domain": { "type": [ "string", "null" ] }, "game": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ] }, "hide_address": { "anyOf": [ { "type": "boolean" }, { "type": "integer", "minimum": 0, "maximum": 1 } ] }, "hide_query": { "anyOf": [ { "type": "boolean" }, { "type": "integer", "minimum": 0, "maximum": 1 } ] }, "icon": { "type": [ "string", "null" ] }, "id": { "type": "integer", "minimum": 1, "maximum": 9007199254740991 }, "ip": { "type": [ "string", "null" ] }, "language": { "type": [ "string", "null" ] }, "last_update": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ], "description": "Czas Unix w sekundach (UTC)." }, "map": { "type": [ "string", "null" ] }, "maxplayers": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ] }, "name": { "type": [ "string", "null" ] }, "numplayers": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ] }, "official": { "anyOf": [ { "anyOf": [ { "type": "boolean" }, { "type": "integer", "minimum": 0, "maximum": 1 } ] }, { "type": "null" } ] }, "points": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ] }, "port": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ] }, "private": { "anyOf": [ { "anyOf": [ { "type": "boolean" }, { "type": "integer", "minimum": 0, "maximum": 1 } ] }, { "type": "null" } ] }, "project_id": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ] }, "pve": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ] }, "pvp": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ] }, "query": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ] }, "request": { "type": [ "string", "null" ] }, "secured": { "anyOf": [ { "anyOf": [ { "type": "boolean" }, { "type": "integer", "minimum": 0, "maximum": 1 } ] }, { "type": "null" } ] }, "status": { "anyOf": [ { "type": "boolean" }, { "type": "integer", "minimum": 0, "maximum": 1 } ] }, "steam_id": { "anyOf": [ { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "string" } ] }, { "type": "null" } ], "description": "Zachowuj identyfikatory tekstowe jako tekst, aby uniknąć utraty precyzji." }, "version": { "type": [ "string", "null" ] }, "votes": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ] }, "wipe": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ], "description": "Czas Unix w sekundach (UTC)." }, "ban_reason": { "type": [ "string", "null" ] }, "banned": { "anyOf": [ { "type": "boolean" }, { "type": "integer", "minimum": 0, "maximum": 1 } ] }, "boosts": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ] }, "bots": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ] }, "city": { "type": [ "string", "null" ] }, "description": { "type": [ "string", "null" ], "description": "Opis serwera jako lista bloków zakodowana w ciągu JSON." }, "disabled_modules": { "type": "array", "items": { "type": "string" } }, "gamemode": { "type": [ "string", "null" ] }, "hidden": { "anyOf": [ { "type": "boolean" }, { "type": "integer", "minimum": 0, "maximum": 1 } ] }, "last_offline": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ], "description": "Czas Unix w sekundach (UTC)." }, "last_online": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ], "description": "Czas Unix w sekundach (UTC)." }, "list_hidden": { "anyOf": [ { "type": "boolean" }, { "type": "integer", "minimum": 0, "maximum": 1 } ] }, "map_url": { "type": [ "string", "null" ] }, "mods": { "type": "array", "items": { "type": "object", "properties": { "id": { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, "name": { "type": "string" } }, "required": [ "id", "name" ], "additionalProperties": {} } }, "next_wipe": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ], "description": "Czas Unix w sekundach (UTC)." }, "parked": { "type": "boolean" }, "position_game": { "anyOf": [ { "type": "integer", "minimum": -9007199254740991, "maximum": 9007199254740991 }, { "type": "null" } ] }, "wipe_period": { "type": [ "string", "null" ] } }, "required": [ "id", "parked" ], "additionalProperties": {} }, "ServerEnvelope": { "type": "object", "required": [ "response" ], "properties": { "response": { "$ref": "#/components/schemas/Server", "description": "Poprawna odpowiedź zawiera wynik w response. Lista może być tablicą lub obiektem z items; sprawdź schemat tej operacji." } } }, "UserProfileResult": { "type": "object", "required": [ "response" ], "properties": { "response": { "type": "object", "required": [ "id", "uuid", "username", "avatar", "banner", "created", "last_online" ], "properties": { "id": { "type": "integer", "minimum": 1, "description": "Numeric profile ID." }, "uuid": { "type": "string", "format": "uuid", "description": "Account ID." }, "username": { "type": "string" }, "avatar": { "type": [ "string", "null" ] }, "banner": { "type": [ "string", "null" ] }, "created": { "type": [ "integer", "null" ] }, "last_online": { "type": [ "integer", "null" ] }, "connections": { "type": "array", "items": { "type": "object", "required": [ "id", "account_id", "account_level", "name" ], "properties": { "id": { "type": "integer", "minimum": 1 }, "account_id": { "type": "string" }, "account_level": { "type": [ "number", "null" ] }, "name": { "type": [ "string", "null" ] }, "platform": { "type": [ "object", "null" ], "required": [ "id", "name", "icon", "url" ], "properties": { "id": { "type": "integer", "minimum": 1 }, "name": { "type": "string" }, "icon": { "type": [ "string", "null" ] }, "url": { "type": [ "string", "null" ] } } } } } } } } } }, "ServerCreateResult": { "type": "object", "properties": { "response": { "type": "object", "properties": { "connect": { "type": [ "string", "null" ] }, "game": { "type": [ "integer", "null" ] }, "id": { "type": "integer", "minimum": 1 }, "name": { "type": [ "string", "null" ] }, "request": { "type": [ "string", "null" ] }, "status": { "type": [ "boolean", "null" ] } }, "required": [ "connect", "game", "id", "name", "request", "status" ] } }, "required": [ "response" ] }, "ServerPlayersResult": { "type": "object", "properties": { "response": { "type": "object", "properties": { "items": { "description": "Jeśli zapytanie do historii sesji nie zwróci graczy, `items` zawiera pełną listę graczy z ostatniego zapytania do serwera, o ile jest dostępna.", "type": "array", "items": { "type": "object", "properties": { "avatar": { "type": "string" }, "created": { "type": [ "number", "string", "null" ] }, "last_online": { "type": [ "number", "string", "null" ] }, "last_session_time": { "type": "number" }, "name": { "type": [ "number", "string", "null" ] }, "user": { "type": [ "object", "null" ], "properties": { "avatar": { "type": [ "string", "null" ] }, "username": { "type": [ "string", "null" ] } } }, "username": { "type": [ "string", "null" ] } }, "required": [ "avatar", "last_session_time", "username" ] } } }, "required": [ "items" ] } }, "required": [ "response" ] }, "ServerPostsResult": { "type": "object", "properties": { "response": { "type": "array", "items": { "type": "object", "additionalProperties": true } } }, "required": [ "response" ] }, "ServerPlayerStatsResult": { "type": "object", "properties": { "response": { "type": "object", "properties": { "items": { "type": "array", "items": { "type": "object", "properties": { "avg_players": { "type": "number" }, "date": { "type": "number" }, "maps": { "type": "array", "items": { "type": "string" } }, "max_players": { "type": "number" }, "min_players": { "type": "number" }, "x": { "type": "number" }, "y": { "type": "number" } }, "required": [ "avg_players", "date", "maps", "max_players", "min_players", "x", "y" ] } } }, "required": [ "items" ] } }, "required": [ "response" ] }, "ProjectPlayerStatsResult": { "type": "object", "properties": { "response": { "type": "object", "properties": { "items": { "type": "array", "items": { "type": "object", "properties": { "avg_players": { "type": "number" }, "date": { "type": "number" }, "max_players": { "type": "number" }, "min_players": { "type": "number" }, "x": { "type": "number" } }, "required": [ "avg_players", "date", "max_players", "min_players", "x" ] } } }, "required": [ "items" ] } }, "required": [ "response" ] }, "VoteDetailsEnvelope": { "type": "object", "properties": { "response": { "$ref": "#/components/schemas/VoteDetails" } } }, "VoteDetails": { "type": "object", "properties": { "id": { "type": "string", "example": "9824cabb-2203-437e-9b6c-aba43dde3e4b" }, "entity_id": { "type": "number", "description": "ID of the entity that received the vote.", "example": 1 }, "entity_type": { "type": "string", "description": "Type of the entity that received the vote.", "enum": [ "server", "project" ], "example": "server" }, "nickname": { "type": [ "string", "null" ], "example": "PlayerName" }, "created_at": { "type": "number", "example": 1710000000 }, "expires_at": { "type": "number", "example": 1710086400 }, "server": { "type": [ "object", "null" ], "description": "Present for `server` votes.", "properties": { "id": { "type": [ "number", "string", "null" ], "example": 1 }, "name": { "type": [ "string", "null" ], "example": "Public Server" }, "icon": { "type": [ "string", "null" ] }, "game": { "type": [ "number", "null" ], "example": 730 } } }, "project": { "type": [ "object", "null" ], "description": "Present for `project` votes.", "properties": { "id": { "type": "number", "example": 1 } } }, "user": { "type": [ "object", "null" ], "properties": { "id": { "type": [ "number", "string", "null" ] }, "uuid": { "type": [ "string", "null" ] }, "username": { "type": [ "string", "null" ] }, "avatar": { "type": [ "string", "null" ] } } }, "webhook": { "type": [ "object", "null" ], "description": "Present only when the requester can view webhook delivery details.", "properties": { "attempted_at": { "type": [ "number", "null" ] }, "event_id": { "type": [ "string", "null" ] }, "event_type": { "type": [ "string", "null" ], "enum": [ "server.vote", "project.vote", null ], "example": "project.vote" }, "is_test": { "type": [ "boolean", "null" ] }, "request_body": { "type": [ "object", "null" ] }, "response_body": {}, "response_code": { "type": [ "number", "string", "null" ] }, "status": { "type": [ "string", "null" ], "enum": [ "delivered", "failed", "no_result", "pending", null ] }, "url": { "type": [ "string", "null" ] } } }, "claimed_at": { "type": [ "integer", "null" ], "description": "Processing acknowledgement time in Unix seconds; null means unclaimed.", "example": null } } }, "VoteClaimResult": { "type": "object", "properties": { "response": { "type": "object", "properties": { "success": { "type": "boolean", "const": true } }, "required": [ "success" ] } }, "required": [ "response" ] } }, "parameters": { "ApiVersion": { "name": "v", "in": "query", "required": false, "description": "Wersja API. Bez v używana jest najniższa obsługiwana wersja. Podaj v=1.0.0, aby zachować opisany kontrakt. Nieprawidłowe, powtórzone lub nieobsługiwane wartości zwracają HTTP 400.", "schema": { "type": "string", "pattern": "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)$", "const": "1.0.0" } }, "created": { "name": "created", "in": "query", "description": "Filtruje według dokładnego czasu utworzenia głosu w sekundach Unix. Bez filtrów daty zapytanie obejmuje wszystkie zapisane głosy.", "schema": { "type": "integer", "example": 1800000000 } }, "created__gt": { "name": "created__gt", "in": "query", "description": "Data utworzenia, sekundy Unix >", "schema": { "type": "integer", "example": 1800000000 } }, "created__gte": { "name": "created__gte", "in": "query", "description": "Data utworzenia, sekundy Unix ≥", "schema": { "type": "integer", "example": 1800000000 } }, "created__lt": { "name": "created__lt", "in": "query", "description": "Data utworzenia, sekundy Unix <", "schema": { "type": "integer", "example": 1800000000 } }, "created__lte": { "name": "created__lte", "in": "query", "description": "Data utworzenia, sekundy Unix ≤", "schema": { "type": "integer", "example": 1800000000 } }, "expire": { "name": "expire", "in": "query", "description": "Data wygaśnięcia, sekundy Unix", "schema": { "type": "integer", "example": 1800000000 } }, "expire__gt": { "name": "expire__gt", "in": "query", "description": "Data wygaśnięcia, sekundy Unix >", "schema": { "type": "integer", "example": 1800000000 } }, "expire__gte": { "name": "expire__gte", "in": "query", "description": "Data wygaśnięcia, sekundy Unix ≥", "schema": { "type": "integer", "example": 1800000000 } }, "expire__lt": { "name": "expire__lt", "in": "query", "description": "Data wygaśnięcia, sekundy Unix <", "schema": { "type": "integer", "example": 1800000000 } }, "expire__lte": { "name": "expire__lte", "in": "query", "description": "Data wygaśnięcia, sekundy Unix ≤", "schema": { "type": "integer", "example": 1800000000 } }, "claimed": { "name": "claimed", "in": "query", "description": "Stan przetwarzania: 0 nieprzetworzone, 1 przetworzone; domyślnie wszystkie", "schema": { "type": "integer", "enum": [ 0, 1 ], "example": 0 } }, "limit": { "name": "limit", "in": "query", "description": "Liczba elementów od 1 do 1000, domyślnie 100", "schema": { "type": "integer", "minimum": 1, "maximum": 1000, "default": 100, "example": 100 } }, "offset": { "name": "offset", "in": "query", "description": "Liczba elementów do pominięcia od 0, domyślnie 0", "schema": { "type": "integer", "minimum": 0, "default": 0, "example": 0 } }, "order": { "name": "order", "in": "query", "schema": { "type": "string", "enum": [ "asc", "desc" ], "default": "desc", "example": "asc" } }, "sort": { "name": "sort", "in": "query", "schema": { "type": "string", "enum": [ "created", "expire" ], "default": "created", "example": "created" } }, "nickname": { "name": "nickname", "in": "query", "description": "Wyszukiwanie po fragmentach nicku głosującego, od 3 do 255 znaków", "schema": { "type": "string", "minLength": 3, "maxLength": 255, "example": "Player" } }, "server_id": { "name": "server_id", "in": "query", "schema": { "type": "integer", "example": 42 } }, "entity_type": { "name": "entity_type", "in": "query", "schema": { "type": "string", "enum": [ "server", "project" ], "example": "server" } }, "webhook_status": { "name": "webhook_status", "in": "query", "schema": { "type": "string", "enum": [ "delivered", "failed", "no_result", "pending" ], "example": "failed" } }, "period": { "name": "period", "in": "query", "description": "Okres według daty utworzenia głosu, domyślnie cała zachowana historia", "schema": { "type": "string", "enum": [ "24h", "7d", "30d", "90d" ], "example": "30d" } } }, "securitySchemes": { "AccountAPIKey": { "type": "http", "scheme": "bearer", "description": "Account API key: 43 base64url characters without a prefix. Claim requires votes:claim scope plus current ownership. Send only in Authorization: Bearer ." } }, "responses": { "BadRequest": { "description": "Nieprawidłowe parametry lub JSON. Sprawdź typy, wymagane pola i dozwolone wartości.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorEnvelope" }, "example": { "error": { "code": 400, "message": "Invalid request parameters." } } } } }, "Forbidden": { "description": "Dostęp zabroniony: adres jest zablokowany lub projekt nie jest publiczny.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorEnvelope" }, "example": { "error": { "code": 403, "message": "Access denied." } } } } }, "ServiceUnavailable": { "description": "Usługa jest tymczasowo niedostępna. Spróbuj później.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorEnvelope" }, "example": { "error": { "code": 503, "message": "Service temporarily unavailable." } } } } }, "QueryTimeout": { "description": "Przekroczono czas zapytania. Spróbuj później lub zawęź zapytanie.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorEnvelope" }, "example": { "error": { "code": 504, "message": "Query timed out." } } } } }, "NotFound": { "description": "Żądany zasób nie istnieje.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorEnvelope" }, "example": { "error": { "code": 404, "message": "Resource not found." } } } } }, "UnexpectedError": { "description": "Nieoczekiwany błąd serwera. Obiekt error zawiera rzeczywisty kod odpowiedzi.", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ErrorEnvelope" }, "example": { "error": { "code": 500, "message": "Internal server error." } } } } } } }, "servers": [ { "url": "https://api.gamemonitoring.pl" } ] } ``` https://gamemonitoring.pl/developers/docs/api.md --- # GAMEMONITORING MCP MCP (Model Context Protocol) daje agentom dostęp do gier, serwerów, ich statusu i liczby graczy w GAMEMONITORING. Wszystkie narzędzia służą do odczytu. Publiczny dostęp działa bez konta i klucza API. ## Połącz agenta Przy ręcznej konfiguracji wybierz Streamable HTTP i wklej adres URL. Cursor i VS Code umożliwiają bezpośrednią instalację. Dla klientów wiersza poleceń są gotowe komendy do skopiowania. ```text https://api.gamemonitoring.net/mcp ``` ### Codex ```bash codex mcp add gamemonitoring --url 'https://api.gamemonitoring.net/mcp' ``` ### Claude Code ```bash claude mcp add --scope user --transport http gamemonitoring 'https://api.gamemonitoring.net/mcp' ``` ### Gemini CLI ```bash gemini mcp add --scope user --transport http gamemonitoring 'https://api.gamemonitoring.net/mcp' ``` ### MCP JSON ```json { "mcpServers": { "gamemonitoring": { "url": "https://api.gamemonitoring.net/mcp" } } } ``` ### Przykładowe polecenie dla agenta ```text Znajdź w GAMEMONITORING trzy serwery Rust z największą liczbą graczy online. Pokaż adres i liczbę graczy na każdym serwerze. ``` ## Narzędzia MCP Zacznij od search_games. Użyj zwróconego steam_id jako game_steam_id do wyszukiwania, filtrowania i liczenia serwerów. Szczegóły serwera pobierzesz według jego identyfikatora GAMEMONITORING zwróconego przez search_servers. ### search_games Wyszukuje gry według nazwy, slugu lub Steam App ID. Zwraca steam_id, nazwę, slug oraz liczbę serwerów i graczy. ```json { "name": "Rust", "limit": 1 } ``` ### get_server_filters Zwraca mapy, wersje, kraje, języki, tryby gry i inne filtry. Podaj game_steam_id konkretnej gry lub pusty obiekt, aby pobrać wspólne filtry. ```json { "game_steam_id": 252490 } ``` ### search_servers Wyszukuje serwery według gry i filtrów. Obsługuje sortowanie, limit od 1 do 100 i offset. Podaj grę, aby zawęzić wyszukiwanie. ```json { "game_steam_id": 252490, "status": "online", "sort": "numplayers", "limit": 3 } ``` ### get_server Zwraca publiczne szczegóły i bieżący status dla liczbowego server_id. ```json { "server_id": 1 } ``` ### get_server_list_metadata Zlicza wszystkie pasujące serwery, serwery online i graczy online przy tych samych filtrach co wyszukiwanie serwerów. ```json { "game_steam_id": 252490, "status": "online" } ``` ## Format danych W poprawnej odpowiedzi tools/call pole result.structuredContent zawiera dane. result.content zawiera postać tekstową i odnośnik do źródłowego żądania REST. Błędy protokołu pojawiają się w polu error najwyższego poziomu. Gdy narzędzie zwróci błąd, result.isError ma wartość true nawet przy HTTP 200. Szczegóły znajdziesz w result.structuredContent.error, jeśli są dostępne. Po przekroczeniu limitu czasu zawęź wyszukiwanie według gry lub innych filtrów. https://gamemonitoring.pl/developers/docs/mcp.md --- # Webhook {#webhook} Webhook wysyła zdarzenie GAMEMONITORING do Twojego systemu po akcji na platformie. To zwykłe żądanie `POST` z body JSON, dzięki któremu strona, panel lub usługa gry może reagować automatycznie. Jeśli konfigurujesz nagrody za głosy, najpierw podłącz Webhook według tej instrukcji, a potem użyj osobnego scenariusza: [Nagrody za głosy](https://gamemonitoring.pl/developers/docs/webhook/vote#flow). ## Podłączenie {#connect} Ta konfiguracja łączy projekt GAMEMONITORING z handlerem i daje token podpisu do weryfikacji przychodzących żądań. 1. Otwórz [Moje projekty](https://gamemonitoring.pl/projects/my), utwórz projekt albo wybierz istniejący, a następnie przejdź do ustawień Webhook. 2. Utwórz publiczny endpoint HTTPS, który przyjmuje `POST` z `Content-Type: application/json` i nie przekierowuje żądań. 3. W ustawieniach Webhook wpisz pełny URL handlera, na przykład `https://panel.example.com/gamemonitoring-webhook`, i zapisz go. 4. Skopiuj token podpisu z tego samego bloku i wpisz go w skrypcie handlera. 5. W handlerze sprawdź `signature`, obsłuż potrzebne `event_type` i zwróć udaną odpowiedź `2xx` dopiero po przetworzeniu zdarzenia. Do lokalnego testowania możesz uruchomić handler na swoim komputerze i wystawić go przez publiczny URL HTTPS. Użyj [ngrok](https://ngrok.com) albo innej usługi tunelowania, a wygenerowany publiczny URL wpisz w ustawieniach Webhook. Po konfiguracji wyślij testowy Webhook z interfejsu i sprawdź status dostawy. Dla przykładowego URL serwer musi przyjmować `POST` na `/gamemonitoring-webhook`. Jeśli test się nie uda, zacznij od odpowiedzi handlera: `401` oznacza błąd podpisu, `403` albo strona weryfikacyjna HTML zwykle wskazuje WAF lub bot protection, a timeout oznacza, że URL jest niedostępny z internetu albo odpowiada za wolno. ## Wymagania handlera {#handler-requirements} - URL musi być dostępny z internetu. Lokalne adresy, sieci prywatne i URL z loginem lub hasłem nie są odpowiednie. - HTTPS jest zalecany dla produkcji. HTTP jest obsługiwany, ale słabiej chroni dane w transmisji. - Handler musi przyjmować metodę `POST` i body JSON bez przekierowań. - Zwracaj `2xx` dopiero po przetworzeniu zdarzenia przez Twój system. Zwykle wystarczy `204 No Content`. - Jeśli zdarzenia nie da się bezpiecznie przetworzyć, zwróć kod błędu. `3xx`, `4xx`, `5xx`, timeout i błąd połączenia są traktowane jako nieudana dostawa. - Jeśli używasz firewalla, bot protection lub allowlist, dodaj [adresy IP GAMEMONITORING](https://gamemonitoring.pl/developers/docs/ips) do wyjątków. - Nie zwracaj w treści odpowiedzi tokenów, stack trace, błędów SQL ani innych szczegółów wewnętrznych. Odpowiedź handlera jest widoczna w interfejsie, więc tekst błędu musi być bezpieczny i zrozumiały. ## Dane zdarzenia {#event-data} Każdy Webhook przychodzi z body JSON i podstawowymi polami: - `event_type` — jakie zdarzenie trzeba obsłużyć. - `event_id` — unikalny ID zdarzenia. Użyj go razem z `event_type` do idempotencji i ochrony przed ponowną dostawą. - `is_test` — oznacza testową dostawę z interfejsu. - `signature` — podpis body zdarzenia. **Przykład zdarzenia Webhook** ```json { "event_id": "9824cabb-2203-437e-9b6c-aba43dde3e4b", "event_type": "example.event", "is_test": false, "signature": "0ac4c97a5d934599dbd78985c4bcbb6926e77b4809d2be56333b1b25f638f064" } ``` Jak czytać przykład: `event_type` pokazuje, jakie zdarzenie trzeba obsłużyć; `event_id` jest potrzebne do idempotencji przed zmianą stanu; `is_test: true` oznacza techniczne sprawdzenie dostawy; `signature` nie jest daną biznesową i służy tylko do uwierzytelnienia żądania. Logika przetwarzania zależy od `event_type`. Dla `server.vote` i `project.vote` użyj osobnego scenariusza: [Nagrody za głosy](https://gamemonitoring.pl/developers/docs/webhook/vote#flow). Jeśli `is_test` ma wartość `true`, sprawdź podpis i zwróć `2xx`, ale nie zmieniaj salda, nie wydawaj przedmiotów i nie uruchamiaj operacji produkcyjnych. ## Przykład odpowiedzi handlera {#response-example} Każde przychodzące zdarzenie zakończ jednym jasnym wynikiem: - `204 No Content` — podpis jest poprawny, a zdarzenie zostało przetworzone albo bezpiecznie pominięte. Tę samą odpowiedź zwracaj dla testowej dostawy i dla zdarzenia już przetworzonego. - `400 Bad Request` — brakuje wymaganych pól. To oznacza błąd handlera albo nieoczekiwane body żądania; nie uruchamiaj logiki biznesowej. - `401 Unauthorized` — podpis jest nieprawidłowy. Nie wykonuj żądań API, nie zmieniaj bazy i nie wydawaj nagród. - `500 Internal Server Error` — baza, kolejka lub wewnętrzny system jest tymczasowo niedostępny. Dostawa pozostanie nieudana i można ją ponowić po usunięciu przyczyny. Przykład: jeśli handler odebrał zdarzenie, sprawdził podpis, zapisał `event_type` + `event_id` i przetworzył zdarzenie, może zwrócić `204`. Jeśli baza jest niedostępna i zdarzenia nie da się zapisać, lepiej zwrócić `500`, żeby dostawa nie została za wcześnie oznaczona jako udana. ## Weryfikacja podpisu {#signature} Podpis znajduje się w polu `signature`. Sprawdzaj go przed logiką biznesową, żądaniami API i zmianami w bazie. Do weryfikacji weź wszystkie pola body poza `signature`, posortuj klucze alfabetycznie i zbuduj ciąg `key=value` połączony przez `&`. Wartości boolean zapisuj jako `true` albo `false`. **Ciąg do podpisu** ```text event_id=9824cabb-2203-437e-9b6c-aba43dde3e4b&event_type=example.event&is_test=false ``` Dla przykładu powyżej ciąg podpisu buduje się tylko z `event_id`, `event_type` i `is_test`. Następnie oblicz `HMAC-SHA256` tokenem podpisu z ustawień Webhook i porównaj wynik z `signature` z żądania. Gotowe podpisy w przykładach są policzone dla tokena demonstracyjnego `paste-webhook-token-here`. W swoim handlerze użyj tokena z ustawień Webhook. W handlerze: - zbuduj ciąg do podpisu z posortowanych kluczy; - oblicz `HMAC-SHA256` tokenem podpisu; - porównaj wynik z `signature` funkcją o stałym czasie porównania: `hash_equals` w PHP, `timingSafeEqual` w Node.js albo `compare_digest` w Pythonie; - zwróć `401`, jeśli podpis jest nieprawidłowy. ## Krok 1. Podstawowy handler {#minimal-handler} Zacznij od handlera, który przyjmuje dowolny Webhook: czyta JSON, sprawdza `signature`, obsługuje testową dostawę, sprawdza podstawowe pola i zwraca `204`. Na tym etapie handler tylko potwierdza, że dostawa jest przyjmowana poprawnie. Logikę konkretnego zdarzenia dodaj po tym, gdy ten podstawowy przepływ działa. ### PHP ```php $isTest ? 'true' : 'false']); // Build the exact signing string: all body fields except signature, // sorted by key and joined as key=value pairs with &. $fields = array_values(array_filter(array_keys($event), fn($field) => $field !== 'signature')); sort($fields, SORT_STRING); // Calculate HMAC-SHA256 with the webhook token from your settings. $signing = implode('&', array_map(fn($field) => $field . '=' . (string) ($signingData[$field] ?? ''), $fields)); $expected = hash_hmac('sha256', $signing, $secret); $actual = (string) ($event['signature'] ?? ''); // Reject the request before doing any work when the signature is invalid. if (!hash_equals($expected, $actual)) { http_response_code(401); exit; } // Test deliveries must not change balance, inventory, roles, or production data. if ($isTest) { http_response_code(204); exit; } // Real deliveries must include an event type and a stable event id. $eventType = (string) ($event['event_type'] ?? ''); $eventId = (string) ($event['event_id'] ?? ''); if ($eventType === '' || $eventId === '') { http_response_code(400); exit; } // At this point the webhook is trusted. Add event-specific logic here. syslog(LOG_INFO, 'Accepted webhook event ' . $eventType . ' #' . $eventId); // 204 tells GAMEMONITORING that the delivery was accepted successfully. http_response_code(204); ``` ### JavaScript ```javascript const crypto = require('node:crypto') const express = require('express') const app = express() // Replace this token with the signing token from your GAMEMONITORING webhook settings. const secret = 'paste-webhook-token-here' // GAMEMONITORING sends JSON with Content-Type: application/json. app.use(express.json()) function isValidSignature(event) { // Build the exact signing string: all body fields except signature, // sorted by key and joined as key=value pairs with &. const fields = Object.keys(event).filter((field) => field !== 'signature').sort() const signing = fields.map((field) => field + '=' + String(event[field] ?? '')).join('&') // Calculate HMAC-SHA256 with the webhook token from your settings. const expected = crypto.createHmac('sha256', secret).update(signing).digest('hex') const actual = String(event.signature || '') // timingSafeEqual requires buffers with the same length. const expectedBuffer = Buffer.from(expected) const actualBuffer = Buffer.from(actual) return expectedBuffer.length === actualBuffer.length && crypto.timingSafeEqual(expectedBuffer, actualBuffer) } app.post('/gamemonitoring-webhook', (req, res) => { // Read the webhook payload parsed by express.json(). const event = req.body || {} // Reject the request before doing any work when the signature is invalid. if (!isValidSignature(event)) { return res.sendStatus(401) } // Test deliveries must not change balance, inventory, roles, or production data. if (event.is_test === true) { return res.sendStatus(204) } // Real deliveries must include an event type and a stable event id. const eventType = String(event.event_type || '') const eventId = String(event.event_id || '') if (!eventType || !eventId) { return res.sendStatus(400) } // At this point the webhook is trusted. Add event-specific logic here. console.log('Accepted webhook event ' + eventType + ' #' + eventId) // 204 tells GAMEMONITORING that the delivery was accepted successfully. return res.sendStatus(204) }) app.listen(3000) ``` ### Python ```python import hashlib import hmac from flask import Flask, abort, request app = Flask(__name__) # Replace this token with the signing token from your GAMEMONITORING webhook settings. secret = b'paste-webhook-token-here' def stringify(value): # GAMEMONITORING signs booleans as lowercase true/false strings. if isinstance(value, bool): return 'true' if value else 'false' return '' if value is None else str(value) def is_valid_signature(event): # Build the exact signing string: all body fields except signature, # sorted by key and joined as key=value pairs with &. fields = sorted(field for field in event.keys() if field != 'signature') signing = '&'.join(f'{field}={stringify(event.get(field))}' for field in fields) # Calculate HMAC-SHA256 with the webhook token from your settings. expected = hmac.new(secret, signing.encode(), hashlib.sha256).hexdigest() actual = str(event.get('signature') or '') return hmac.compare_digest(expected, actual) @app.post('/gamemonitoring-webhook') def gamemonitoring_webhook(): # Read and decode the JSON body sent by GAMEMONITORING. event = request.get_json(silent=True) or {} # Reject the request before doing any work when the signature is invalid. if not is_valid_signature(event): abort(401) # Test deliveries must not change balance, inventory, roles, or production data. if event.get('is_test') is True: return '', 204 # Real deliveries must include an event type and a stable event id. event_type = str(event.get('event_type') or '') event_id = str(event.get('event_id') or '') if not event_type or not event_id: abort(400) # At this point the webhook is trusted. Add event-specific logic here. app.logger.info('Accepted webhook event %s #%s', event_type, event_id) # 204 tells GAMEMONITORING that the delivery was accepted successfully. return '', 204 ``` ## Krok 2. Dodaj deduplikację {#deduplication} Webhook używa modelu at-least-once: to samo zdarzenie może przyjść więcej niż raz. Zanim handler zmieni stan Twojego systemu, zadbaj o idempotentność tej operacji po `event_type` + `event_id`. Najpierw utwórz tabelę, która zapisuje parę `event_type` i `event_id` z unikalnym kluczem. Jeśli rekord już istnieje, zdarzenie było już przetworzone. **Tabela przetworzonych zdarzeń Webhook** ```sql CREATE TABLE gamemonitoring_webhooks ( event_type varchar(64) NOT NULL, event_id varchar(100) NOT NULL, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (event_type, event_id) ); ``` Następnie rozszerz podstawowy handler: po sprawdzeniu podpisu i podstawowych pól zapisz `event_type` + `event_id`, a zmiany stanu wykonuj w tej samej transakcji. ### PHP ```php $isTest ? 'true' : 'false']); // Build the exact signing string: all body fields except signature, // sorted by key and joined as key=value pairs with &. $fields = array_values(array_filter(array_keys($event), fn($field) => $field !== 'signature')); sort($fields, SORT_STRING); // Calculate HMAC-SHA256 with the webhook token from your settings. $signing = implode('&', array_map(fn($field) => $field . '=' . (string) ($signingData[$field] ?? ''), $fields)); $expected = hash_hmac('sha256', $signing, $secret); $actual = (string) ($event['signature'] ?? ''); // Reject the request before doing any work when the signature is invalid. if (!hash_equals($expected, $actual)) { http_response_code(401); exit; } // Test deliveries must not change balance, inventory, roles, or production data. if ($isTest) { http_response_code(204); exit; } // Real deliveries must include an event type and a stable event id. $eventType = (string) ($event['event_type'] ?? ''); $eventId = (string) ($event['event_id'] ?? ''); if ($eventType === '' || $eventId === '') { http_response_code(400); exit; } // At this point the webhook is trusted. Deduplicate it before event-specific logic. $pdo = null; try { // Add your local database connection for deduplication and event-specific work. $pdo = new PDO('mysql:host=127.0.0.1;dbname=game;charset=utf8mb4', 'game', 'password', [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, ]); // Keep deduplication and the real state change in one transaction. // If any step fails, return 500 so the delivery can be retried. $pdo->beginTransaction(); // Store the event once. This requires the table to have a unique key on // (event_type, event_id). Duplicate deliveries affect zero rows. $deduplicate = $pdo->prepare('INSERT IGNORE INTO gamemonitoring_webhooks (event_type, event_id) VALUES (?, ?)'); $deduplicate->execute([$eventType, $eventId]); // The event was already processed earlier. Return success without changing // state again, because duplicate delivery is expected. if ($deduplicate->rowCount() === 0) { $pdo->commit(); http_response_code(204); exit; } // Add event-specific database changes here. Keep them after the // deduplication insert and inside this same transaction. // Commit only after deduplication and event-specific work both succeed. $pdo->commit(); // Log only newly processed real events after the transaction succeeds. syslog(LOG_INFO, 'Accepted webhook event ' . $eventType . ' #' . $eventId); http_response_code(204); } catch (Throwable $error) { // Roll back partial database work so the event can be retried safely. if ($pdo instanceof PDO && $pdo->inTransaction()) { $pdo->rollBack(); } // 500 keeps the delivery failed instead of marking unfinished work as done. http_response_code(500); } ``` ### JavaScript ```javascript const crypto = require('node:crypto') const express = require('express') const mysql = require('mysql2/promise') const app = express() // Replace this token with the signing token from your GAMEMONITORING webhook settings. const secret = 'paste-webhook-token-here' // Add your local database connection for deduplication and event-specific work. const db = mysql.createPool({ database: 'game', host: '127.0.0.1', password: 'password', user: 'game', }) // GAMEMONITORING sends JSON with Content-Type: application/json. app.use(express.json()) function isValidSignature(event) { // Build the exact signing string: all body fields except signature, // sorted by key and joined as key=value pairs with &. const fields = Object.keys(event).filter((field) => field !== 'signature').sort() const signing = fields.map((field) => field + '=' + String(event[field] ?? '')).join('&') // Calculate HMAC-SHA256 with the webhook token from your settings. const expected = crypto.createHmac('sha256', secret).update(signing).digest('hex') const actual = String(event.signature || '') // timingSafeEqual requires buffers with the same length. const expectedBuffer = Buffer.from(expected) const actualBuffer = Buffer.from(actual) return expectedBuffer.length === actualBuffer.length && crypto.timingSafeEqual(expectedBuffer, actualBuffer) } app.post('/gamemonitoring-webhook', async (req, res) => { // Read the webhook payload parsed by express.json(). const event = req.body || {} // Reject the request before doing any work when the signature is invalid. if (!isValidSignature(event)) { return res.sendStatus(401) } // Test deliveries must not change balance, inventory, roles, or production data. if (event.is_test === true) { return res.sendStatus(204) } // Real deliveries must include an event type and a stable event id. const eventType = String(event.event_type || '') const eventId = String(event.event_id || '') if (!eventType || !eventId) { return res.sendStatus(400) } // At this point the webhook is trusted. Deduplicate it before event-specific logic. let connection try { connection = await db.getConnection() // Keep deduplication and the real state change in one transaction. // If any step fails, return 500 so the delivery can be retried. await connection.beginTransaction() // Store the event once. This requires the table to have a unique key on // (event_type, event_id). Duplicate deliveries affect zero rows. const [deduplicate] = await connection.execute( 'INSERT IGNORE INTO gamemonitoring_webhooks (event_type, event_id) VALUES (?, ?)', [eventType, eventId], ) // The event was already processed earlier. Return success without changing // state again, because duplicate delivery is expected. if (deduplicate.affectedRows === 0) { await connection.commit() return res.sendStatus(204) } // Add event-specific database changes here. Keep them after the // deduplication insert and inside this same transaction. // Commit only after deduplication and event-specific work both succeed. await connection.commit() // Log only newly processed real events after the transaction succeeds. console.log('Accepted webhook event ' + eventType + ' #' + eventId) return res.sendStatus(204) } catch (error) { // Roll back partial database work so the event can be retried safely. if (connection) { await connection.rollback() } // 500 keeps the delivery failed instead of marking unfinished work as done. return res.sendStatus(500) } finally { // Return the connection to the pool. if (connection) { connection.release() } } }) app.listen(3000) ``` ### Python ```python import hashlib import hmac import pymysql from flask import Flask, abort, request app = Flask(__name__) # Replace this token with the signing token from your GAMEMONITORING webhook settings. secret = b'paste-webhook-token-here' # Add your local database connection for deduplication and event-specific work. db_config = { 'database': 'game', 'host': '127.0.0.1', 'password': 'password', 'user': 'game', } def stringify(value): # GAMEMONITORING signs booleans as lowercase true/false strings. if isinstance(value, bool): return 'true' if value else 'false' return '' if value is None else str(value) def is_valid_signature(event): # Build the exact signing string: all body fields except signature, # sorted by key and joined as key=value pairs with &. fields = sorted(field for field in event.keys() if field != 'signature') signing = '&'.join(f'{field}={stringify(event.get(field))}' for field in fields) # Calculate HMAC-SHA256 with the webhook token from your settings. expected = hmac.new(secret, signing.encode(), hashlib.sha256).hexdigest() actual = str(event.get('signature') or '') return hmac.compare_digest(expected, actual) @app.post('/gamemonitoring-webhook') def gamemonitoring_webhook(): # Read and decode the JSON body sent by GAMEMONITORING. event = request.get_json(silent=True) or {} # Reject the request before doing any work when the signature is invalid. if not is_valid_signature(event): abort(401) # Test deliveries must not change balance, inventory, roles, or production data. if event.get('is_test') is True: return '', 204 # Real deliveries must include an event type and a stable event id. event_type = str(event.get('event_type') or '') event_id = str(event.get('event_id') or '') if not event_type or not event_id: abort(400) # At this point the webhook is trusted. Deduplicate it before event-specific logic. connection = None try: connection = pymysql.connect(**db_config) connection.begin() # Keep deduplication and the real state change in one transaction. # If any step fails, return 500 so the delivery can be retried. with connection.cursor() as cursor: # Store the event once. This requires the table to have a unique key # on (event_type, event_id). Duplicate deliveries affect zero rows. cursor.execute( 'INSERT IGNORE INTO gamemonitoring_webhooks (event_type, event_id) VALUES (%s, %s)', (event_type, event_id), ) # The event was already processed earlier. Return success without # changing state again, because duplicate delivery is expected. if cursor.rowcount == 0: connection.commit() return '', 204 # Add event-specific database changes here. Keep them after the # deduplication insert and inside this same transaction. # Commit only after deduplication and event-specific work both succeed. connection.commit() # Log only newly processed real events after the transaction succeeds. app.logger.info('Accepted webhook event %s #%s', event_type, event_id) return '', 204 except Exception: # Roll back partial database work so the event can be retried safely. if connection: connection.rollback() # 500 keeps the delivery failed instead of marking unfinished work as done. abort(500) finally: # Close the database connection. if connection: connection.close() ``` Nie używaj nicku, ID użytkownika ani ID serwera jako klucza deduplikacji: jeden użytkownik może wywołać różne zdarzenia albo później powtórzyć dozwoloną akcję. Kluczem musi być `event_type` + `event_id`. Przykład: handler zmienił stan Twojego systemu, ale połączenie zerwało się przed otrzymaniem przez GAMEMONITORING `204`. Później dostawa zostaje ponowiona i to samo zdarzenie przychodzi jeszcze raz. Handler musi znaleźć zapisane `event_type` + `event_id`, pominąć ponowną zmianę stanu i zwrócić `204`. Jeśli handler tymczasowo nie może przetworzyć zdarzenia, zwróć odpowiedź z błędem. Po usunięciu przyczyny dostawę można ponowić z interfejsu, jeśli ponowienie jest dostępne dla tego zdarzenia. ## Testy i ponowna wysyłka {#tests-resend} Dostawa testowa (`is_test: true`) sprawdza URL, podpis i odpowiedź HTTP handlera. Handler musi przejść tę samą ścieżkę przetwarzania: odczytać JSON, sprawdzić `signature`, rozpoznać `is_test` i zwrócić udaną odpowiedź `2xx`. Zdarzenie testowe nie powinno zmieniać salda, ekwipunku, ról, subskrypcji ani innych danych produkcyjnych. Do testu wystarczą techniczny log i odpowiedź `204`. Jeśli dostawa zakończy się błędem, interfejs pokazuje status, kod HTTP i odpowiedź handlera. Po naprawieniu przyczyny nieudaną dostawę można wysłać ponownie, jeśli ponowienie jest dostępne dla tego zdarzenia. https://gamemonitoring.pl/developers/docs/webhook.md --- # Nagrody za głosy {#vote-rewards} Nagrody za głosy używają zdarzeń Webhook `server.vote` i `project.vote`: handler odbiera zdarzenie, pobiera dane głosu przez API i wydaje nagrodę tylko jeden raz. Najpierw skonfiguruj [Webhook projektu](https://gamemonitoring.pl/developers/docs/webhook#connect) i weryfikację [signature](https://gamemonitoring.pl/developers/docs/webhook#signature). Dane głosu są pobierane przez [GET /votes/:vote_id](https://gamemonitoring.pl/developers/docs/api/votes/:vote_id/__GET). ## Jak działa scenariusz {#flow} 1. Przyjmij zdarzenie Webhook i sprawdź [signature](https://gamemonitoring.pl/developers/docs/webhook#signature). Jeśli [is_test](https://gamemonitoring.pl/developers/docs/webhook#tests-resend) ma wartość `true`, zwróć `204` bez pobierania głosu i bez wydawania nagrody. 2. Upewnij się, że `event_type` to `server.vote` lub `project.vote`. 3. Użyj `event_id` jako ID głosu. 4. Pobierz dane głosu przez [GET /votes/:vote_id](https://gamemonitoring.pl/developers/docs/api/votes/:vote_id/__GET) i znajdź gracza w swoim systemie. 5. W jednej transakcji zastosuj [ochronę przed ponownym przetworzeniem](https://gamemonitoring.pl/developers/docs/webhook#deduplication) po `event_type` + `event_id` i wydaj nagrodę tylko dla nowego zdarzenia. 6. Jeśli nagrody nie da się bezpiecznie wydać, zwróć odpowiedź z błędem. Po usunięciu przyczyny [ponów dostawę](https://gamemonitoring.pl/developers/docs/webhook#tests-resend) z interfejsu. ## Przykład nagrody {#reward-example} Załóżmy, że gracz `PlayerName` zagłosował na serwer o ID `1`, a Twój system ma dodać mu `100` monet. 1. GAMEMONITORING wysyła Webhook z `event_type: server.vote` i `event_id: 9824cabb-2203-437e-9b6c-aba43dde3e4b`. 2. Handler sprawdza [signature](https://gamemonitoring.pl/developers/docs/webhook#signature). Jeśli podpis jest błędny, zwraca `401` i kończy. 3. Handler wywołuje `GET /votes/9824cabb-2203-437e-9b6c-aba43dde3e4b`, otrzymuje nick, serwer oraz użytkownika i znajduje lokalne konto. 4. W transakcji handler zapisuje `event_type` + `event_id` dla [ochrony przed ponownym przetworzeniem](https://gamemonitoring.pl/developers/docs/webhook#deduplication). 5. Dla nowego zdarzenia handler dodaje `100` monet w tej samej transakcji. 6. Przy ponownej dostawie handler znajduje już zapisane zdarzenie, nie wydaje nagrody drugi raz i zwraca `204`. Ten sam scenariusz pasuje też do przedmiotów, ról, czasu VIP, kodów promocyjnych lub zadań w wewnętrznej kolejce. ## Zdarzenie głosu {#vote-event} Dla głosu na serwer GAMEMONITORING wysyła `server.vote`, a dla głosu na projekt — `project.vote`. Body zdarzenia zawiera tylko dane dostawy: `event_type`, `event_id`, `is_test` i `signature`. Pełne dane głosu trzeba pobrać osobno. **Przykład zdarzenia** ```json { "event_id": "9824cabb-2203-437e-9b6c-aba43dde3e4b", "event_type": "server.vote", "is_test": false, "signature": "ae83b8aba88a3a9ab3b97b1f6d65664da5628a9cb64d56d5132807bca5472e4f" } ``` `event_id` w tym zdarzeniu jest ID głosu. Nie używaj body Webhook jako źródła nicku, serwera lub użytkownika: te dane pochodzą z API. ## Pobieranie danych głosu {#fetch-vote} Użyj `event_id` jako `vote_id` i pobierz dane głosu przez [GET /votes/:vote_id](https://gamemonitoring.pl/developers/docs/api/votes/:vote_id/__GET): **Żądanie danych głosu** ```bash curl -sS "https://api.gamemonitoring.pl/votes/9824cabb-2203-437e-9b6c-aba43dde3e4b" ``` Do wydania nagrody zwykle potrzebujesz `response.nickname`, `response.server` i publicznych danych `response.user`. Jeśli nagroda zależy od konkretnego serwera, zawsze sprawdzaj `response.server.id`. Jak używać pól: `response.nickname` pomaga znaleźć konto gracza w Twojej bazie, `response.server.id` wybiera regułę nagrody dla serwera, a `response.user.id` można zapisać w logu nagród jako ID użytkownika GAMEMONITORING, który oddał głos. Jeśli API jest chwilowo niedostępne albo zwraca nieoczekiwaną odpowiedź, nie wydawaj nagrody bez weryfikacji. Zwróć kod błędu, napraw przyczynę i [ponów dostawę](https://gamemonitoring.pl/developers/docs/webhook#tests-resend) z interfejsu. ## Krok 3. Handler nagrody za głos {#complete-example} Przykład kontynuuje podstawowy handler: sprawdza podpis, pobiera dane głosu, chroni zdarzenie przed ponownym przetworzeniem i dodaje nagrodę w jednej transakcji. Nazwę tabeli użytkowników, pole salda i regułę wyszukiwania gracza zastąp strukturą swojego systemu. Przed uruchomieniem przykładu skonfiguruj [Webhook projektu](https://gamemonitoring.pl/developers/docs/webhook#connect), sprawdź [GET /votes/:vote_id](https://gamemonitoring.pl/developers/docs/api/votes/:vote_id/__GET) i zastąp SQL aktualizacji użytkownika swoim modelem kont. ### PHP ```php $isTest ? 'true' : 'false']); // Build the exact signing string: all body fields except signature, // sorted by key and joined as key=value pairs with &. $fields = array_values(array_filter(array_keys($event), fn($field) => $field !== 'signature')); sort($fields, SORT_STRING); // Calculate HMAC-SHA256 with the webhook token from your settings. $signing = implode('&', array_map(fn($field) => $field . '=' . (string) ($signingData[$field] ?? ''), $fields)); $expected = hash_hmac('sha256', $signing, $secret); $actual = (string) ($event['signature'] ?? ''); // Reject the request before doing any work when the signature is invalid. if (!hash_equals($expected, $actual)) { http_response_code(401); exit; } // Test deliveries must not change balance, inventory, roles, or production data. if ($isTest) { http_response_code(204); exit; } // Real deliveries must include an event type and a stable event id. $eventType = (string) ($event['event_type'] ?? ''); $eventId = (string) ($event['event_id'] ?? ''); if ($eventType === '' || $eventId === '') { http_response_code(400); exit; } // This reward handler processes server and project vote events. if (!in_array($eventType, ['server.vote', 'project.vote'], true)) { http_response_code(204); exit; } // At this point the webhook is trusted. Load vote data before opening a database transaction. $pdo = null; try { // Load full vote data by event_id. Nickname, entity, and user data are not // in the webhook body. Return 500 if the API cannot confirm the vote. $voteUrl = $apiUrl . '/votes/' . rawurlencode($eventId); $voteContext = stream_context_create(['http' => ['timeout' => 5]]); $voteBody = @file_get_contents($voteUrl, false, $voteContext); if ($voteBody === false) { throw new RuntimeException('Vote API request failed'); } $voteResponse = json_decode($voteBody, true) ?: []; $vote = $voteResponse['response'] ?? null; // Do not issue a reward when the vote response is missing a concrete nickname. if (!is_array($vote) || !isset($vote['nickname']) || !is_string($vote['nickname'])) { throw new RuntimeException('Vote API response does not include nickname'); } // Verify that the API entity matches the event before changing the account. $expectedEntityType = $eventType === 'project.vote' ? 'project' : 'server'; if (($vote['entity_type'] ?? '') !== $expectedEntityType) { throw new RuntimeException('Vote entity type does not match event type'); } // Use vote nickname to update the local account. The entity id is available in // vote.entity_id and in either vote.server.id or vote.project.id. $nickname = trim($vote['nickname']); if ($nickname === '') { throw new RuntimeException('Vote nickname is empty'); } // Add your local database connection for deduplication and event-specific work. $pdo = new PDO('mysql:host=127.0.0.1;dbname=game;charset=utf8mb4', 'game', 'password', [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, ]); // Keep deduplication and the real state change in one transaction. // If any step fails, return 500 so the delivery can be retried. $pdo->beginTransaction(); // Store the event once. This requires the table to have a unique key on // (event_type, event_id). Duplicate deliveries affect zero rows. $deduplicate = $pdo->prepare('INSERT IGNORE INTO gamemonitoring_webhooks (event_type, event_id) VALUES (?, ?)'); $deduplicate->execute([$eventType, $eventId]); // The event was already processed earlier. Return success without changing // state again, because duplicate delivery is expected. if ($deduplicate->rowCount() === 0) { $pdo->commit(); http_response_code(204); exit; } // Add event-specific database changes here. Keep them after the // deduplication insert and inside this same transaction. $balance = $pdo->prepare('UPDATE users SET balance = balance + ? WHERE nickname = ?'); $balance->execute([$rewardAmount, $nickname]); // Commit only after deduplication and event-specific work both succeed. $pdo->commit(); // Log only newly processed real events after the transaction succeeds. syslog(LOG_INFO, 'Accepted webhook event ' . $eventType . ' #' . $eventId); http_response_code(204); } catch (Throwable $error) { // Roll back partial database work so the event can be retried safely. if ($pdo instanceof PDO && $pdo->inTransaction()) { $pdo->rollBack(); } // 500 keeps the delivery failed instead of marking unfinished work as done. http_response_code(500); } ``` ### JavaScript ```javascript const crypto = require('node:crypto') const express = require('express') const mysql = require('mysql2/promise') const app = express() // Replace this token with the signing token from your GAMEMONITORING webhook settings. const secret = 'paste-webhook-token-here' // Add the GAMEMONITORING API URL and reward settings for vote events. const apiUrl = 'https://api.gamemonitoring.pl' const rewardAmount = '1.00' // Add your local database connection for deduplication and event-specific work. const db = mysql.createPool({ database: 'game', host: '127.0.0.1', password: 'password', user: 'game', }) // GAMEMONITORING sends JSON with Content-Type: application/json. app.use(express.json()) function isValidSignature(event) { // Build the exact signing string: all body fields except signature, // sorted by key and joined as key=value pairs with &. const fields = Object.keys(event).filter((field) => field !== 'signature').sort() const signing = fields.map((field) => field + '=' + String(event[field] ?? '')).join('&') // Calculate HMAC-SHA256 with the webhook token from your settings. const expected = crypto.createHmac('sha256', secret).update(signing).digest('hex') const actual = String(event.signature || '') // timingSafeEqual requires buffers with the same length. const expectedBuffer = Buffer.from(expected) const actualBuffer = Buffer.from(actual) return expectedBuffer.length === actualBuffer.length && crypto.timingSafeEqual(expectedBuffer, actualBuffer) } app.post('/gamemonitoring-webhook', async (req, res) => { // Read the webhook payload parsed by express.json(). const event = req.body || {} // Reject the request before doing any work when the signature is invalid. if (!isValidSignature(event)) { return res.sendStatus(401) } // Test deliveries must not change balance, inventory, roles, or production data. if (event.is_test === true) { return res.sendStatus(204) } // Real deliveries must include an event type and a stable event id. const eventType = String(event.event_type || '') const eventId = String(event.event_id || '') if (!eventType || !eventId) { return res.sendStatus(400) } // This reward handler processes server and project vote events. if (!['server.vote', 'project.vote'].includes(eventType)) { return res.sendStatus(204) } // At this point the webhook is trusted. Load vote data before opening a database transaction. let connection try { // Load full vote data by event_id. Nickname, entity, and user data are not // in the webhook body. Return 500 if the API cannot confirm the vote. const voteUrl = apiUrl + '/votes/' + encodeURIComponent(eventId) const voteResponse = await fetch(voteUrl, { signal: AbortSignal.timeout(5000) }) if (!voteResponse.ok) { throw new Error('Vote API request failed') } const voteBody = await voteResponse.json() const vote = voteBody.response // Do not issue a reward when the vote response is missing a concrete nickname. if (!vote || typeof vote.nickname !== 'string') { throw new Error('Vote API response does not include nickname') } // Verify that the API entity matches the event before changing the account. const expectedEntityType = eventType === 'project.vote' ? 'project' : 'server' if (vote.entity_type !== expectedEntityType) { throw new Error('Vote entity type does not match event type') } // Use vote nickname to update the local account. The entity id is available in // vote.entity_id and in either vote.server.id or vote.project.id. const nickname = vote.nickname.trim() if (!nickname) { throw new Error('Vote nickname is empty') } connection = await db.getConnection() // Keep deduplication and the real state change in one transaction. // If any step fails, return 500 so the delivery can be retried. await connection.beginTransaction() // Store the event once. This requires the table to have a unique key on // (event_type, event_id). Duplicate deliveries affect zero rows. const [deduplicate] = await connection.execute( 'INSERT IGNORE INTO gamemonitoring_webhooks (event_type, event_id) VALUES (?, ?)', [eventType, eventId], ) // The event was already processed earlier. Return success without changing // state again, because duplicate delivery is expected. if (deduplicate.affectedRows === 0) { await connection.commit() return res.sendStatus(204) } // Add event-specific database changes here. Keep them after the // deduplication insert and inside this same transaction. await connection.execute('UPDATE users SET balance = balance + ? WHERE nickname = ?', [rewardAmount, nickname]) // Commit only after deduplication and event-specific work both succeed. await connection.commit() // Log only newly processed real events after the transaction succeeds. console.log('Accepted webhook event ' + eventType + ' #' + eventId) return res.sendStatus(204) } catch (error) { // Roll back partial database work so the event can be retried safely. if (connection) { await connection.rollback() } // 500 keeps the delivery failed instead of marking unfinished work as done. return res.sendStatus(500) } finally { // Return the connection to the pool. if (connection) { connection.release() } } }) app.listen(3000) ``` ### Python ```python import hashlib import hmac import pymysql import requests from flask import Flask, abort, request app = Flask(__name__) # Replace this token with the signing token from your GAMEMONITORING webhook settings. secret = b'paste-webhook-token-here' # Add the GAMEMONITORING API URL and reward settings for vote events. api_url = 'https://api.gamemonitoring.pl' reward_amount = '1.00' # Add your local database connection for deduplication and event-specific work. db_config = { 'database': 'game', 'host': '127.0.0.1', 'password': 'password', 'user': 'game', } def stringify(value): # GAMEMONITORING signs booleans as lowercase true/false strings. if isinstance(value, bool): return 'true' if value else 'false' return '' if value is None else str(value) def is_valid_signature(event): # Build the exact signing string: all body fields except signature, # sorted by key and joined as key=value pairs with &. fields = sorted(field for field in event.keys() if field != 'signature') signing = '&'.join(f'{field}={stringify(event.get(field))}' for field in fields) # Calculate HMAC-SHA256 with the webhook token from your settings. expected = hmac.new(secret, signing.encode(), hashlib.sha256).hexdigest() actual = str(event.get('signature') or '') return hmac.compare_digest(expected, actual) @app.post('/gamemonitoring-webhook') def gamemonitoring_webhook(): # Read and decode the JSON body sent by GAMEMONITORING. event = request.get_json(silent=True) or {} # Reject the request before doing any work when the signature is invalid. if not is_valid_signature(event): abort(401) # Test deliveries must not change balance, inventory, roles, or production data. if event.get('is_test') is True: return '', 204 # Real deliveries must include an event type and a stable event id. event_type = str(event.get('event_type') or '') event_id = str(event.get('event_id') or '') if not event_type or not event_id: abort(400) # This reward handler processes server and project vote events. if event_type not in ('server.vote', 'project.vote'): return '', 204 # At this point the webhook is trusted. Load vote data before opening a database transaction. connection = None try: # Load full vote data by event_id. Nickname, entity, and user data # are not in the webhook body. Return 500 if the API cannot confirm the vote. vote_url = f"{api_url}/votes/{event_id}" response = requests.get(vote_url, timeout=5) if not response.ok: raise RuntimeError('Vote API request failed') vote = response.json().get('response') # Do not issue a reward when the vote response is missing a concrete nickname. if not isinstance(vote, dict) or not isinstance(vote.get('nickname'), str): raise RuntimeError('Vote API response does not include nickname') # Verify that the API entity matches the event before changing the account. expected_entity_type = 'project' if event_type == 'project.vote' else 'server' if vote.get('entity_type') != expected_entity_type: raise RuntimeError('Vote entity type does not match event type') # Use vote nickname to update the local account. The entity id is available in # vote.entity_id and in either vote.server.id or vote.project.id. nickname = vote['nickname'].strip() if not nickname: raise RuntimeError('Vote nickname is empty') connection = pymysql.connect(**db_config) connection.begin() # Keep deduplication and the real state change in one transaction. # If any step fails, return 500 so the delivery can be retried. with connection.cursor() as cursor: # Store the event once. This requires the table to have a unique key # on (event_type, event_id). Duplicate deliveries affect zero rows. cursor.execute( 'INSERT IGNORE INTO gamemonitoring_webhooks (event_type, event_id) VALUES (%s, %s)', (event_type, event_id), ) # The event was already processed earlier. Return success without # changing state again, because duplicate delivery is expected. if cursor.rowcount == 0: connection.commit() return '', 204 # Add event-specific database changes here. Keep them after the # deduplication insert and inside this same transaction. cursor.execute('UPDATE users SET balance = balance + %s WHERE nickname = %s', (reward_amount, nickname)) # Commit only after deduplication and event-specific work both succeed. connection.commit() # Log only newly processed real events after the transaction succeeds. app.logger.info('Accepted webhook event %s #%s', event_type, event_id) return '', 204 except Exception: # Roll back partial database work so the event can be retried safely. if connection: connection.rollback() # 500 keeps the delivery failed instead of marking unfinished work as done. abort(500) finally: # Close the database connection. if connection: connection.close() ``` https://gamemonitoring.pl/developers/docs/webhook/vote.md --- # Adresy IP systemu Tych IP-adresów GAMEMONITORING używa do sprawdzania serwerów gier i dostarczania [żądań Webhook](https://gamemonitoring.pl/developers/docs/webhook#connect) do Twojego systemu. Dodaj je do allowlisty, jeśli serwer, strona, WAF, CDN albo bot protection ogranicza przychodzące requesty. ## Kiedy je dodać {#when-needed} - serwer gry przyjmuje requesty tylko z dozwolonych adresów; - [handler Webhook](https://gamemonitoring.pl/developers/docs/webhook#handler-requirements) jest chroniony przez firewall, WAF albo Cloudflare; - bot protection blokuje automatyczne requesty; - hosting prosi o listę IP do reguł sieciowych. ## Przykład użycia {#usage-example} Przykład Webhook: handler działa pod `https://panel.example.com/gamemonitoring-webhook`, a domena jest chroniona przez Cloudflare. Dodaj IP GAMEMONITORING do allowlisty dla tej domeny lub dokładnej ścieżki, żeby Cloudflare nie pokazywał challenge i nie blokował [żądań Webhook `POST`](https://gamemonitoring.pl/developers/docs/webhook#handler-requirements). Przykład serwera gry: firewall pozwala na query-port tylko z zaufanych adresów. Dodaj IP GAMEMONITORING do reguły dla query-portu, inaczej monitoring nie będzie stabilnie sprawdzał online i stanu serwera. ## Konfiguracja allowlisty {#allowlist} Przekaż IP-adresy z listy powyżej administratorowi albo hostingowi. Reguła musi pozwalać na przychodzące requesty z tych adresów do serwera gry lub handlera Webhook. Jeśli reguła działa po ścieżce, ogranicz ją do endpointu, np. `/gamemonitoring-webhook`. Jeśli działa po porcie, wskaż tylko query-port gry albo port web-serwera przyjmującego Webhook. ## Weryfikacja po konfiguracji {#verification} Po zmianie reguł wyślij testowy request lub [testowy Webhook](https://gamemonitoring.pl/developers/docs/webhook#tests-resend) i sprawdź, że request nie jest już blokowany. Jeśli test się nie udał, sprawdź logi firewall, WAF albo Cloudflare. Powinny pokazać IP źródłowe, ścieżkę i powód blokady. To pozwala znaleźć brakującą domenę, ścieżkę, port albo kolejność reguł. ## Konfiguracja Cloudflare {#cloudflare} Jeśli handler Webhook jest za Cloudflare, dodaj IP GAMEMONITORING do reguły, która pomija kontrole WAF dla tych requestów: 1. Zaloguj się do panelu Cloudflare. 2. Wybierz domenę. 3. Otwórz **Security**. 4. Wybierz **WAF**. 5. Otwórz **Custom rules**. 6. Kliknij **Create rule**. 7. Podaj nazwę, np. **Allow GAMEMONITORING**. 8. W **Field** wybierz **IP Source Address**. 9. W **Operator** wybierz **is in**. 10. W **Value** dodaj IP z listy powyżej. 11. W **Choose action** wybierz **Skip**. 12. W **WAF components to skip** zaznacz kontrole blokujące requesty do handlera. 13. W **Select order** wybierz **First**. 14. Kliknij **Deploy**. Jeśli requesty nadal są blokowane, sprawdź logi firewall lub Cloudflare i upewnij się, że reguła dotyczy właściwej domeny oraz ścieżki handlera. ```http GET https://api.gamemonitoring.pl/pages/system/ips ``` https://gamemonitoring.pl/developers/docs/ips.md