How to develop a bot that warns about «dangerous moments»?

What is the API for sports events and how to use it for an alert bot

The sports events API is a standardized interface that allows you to obtain match structures, online statistics, timely events, and bookmaker odds in a machine-readable format. Instead of parsing websites, you make a request to the REST endpoint and receive a neat JSON, which already contains lists of matches, lineups, current scores, live events, and detailed statistics. Based on such data, you can build bots that timely warn about dangerous moments — attacks, penalties, series of shots on goal, or sharp changes in odds.

Service por el API de eventos deportivos api-sport.ru provides a unified interface for football, basketball, hockey, tennis, table tennis, esports, and other sports. For each sport, a specific path is used, for example /v2/football/ or /v2/basketball/. Through methods /matches и /matches/{matchId} you get a list of games and detailed information: current match time, score, array eventosEnVivo with goals and cards, array estadísticasDelPartido with shots, possession, and other metrics. Additionally, a block oddsBase with bookmaker odds is available, which is especially important for betting-oriented bots.

API → logic → notification

The simplest architecture of a notification bot looks like this: a background service regularly polls the API, analyzes live data, and sends a notification to the user in the chosen channel (chatbot, push notification, web panel) when conditions are met. On the logic side, you define what to consider a dangerous moment: a shot on target, a penalty, a series of attacks in a short period, or a jump in the odds for a goal.

Below is an example of a request to get all current football matches in live mode via the API:

const apiKey = 'ВАШ_API_КЛЮЧ';
async function loadLiveMatches() {
  const res = await fetch('https://api.api-sport.ru/v2/football/matches?status=inprogress', {
    headers: {
      Authorization: apiKey,
    },
  });
  if (!res.ok) {
    throw new Error('Ошибка загрузки матчей: ' + res.status);
  }
  const data = await res.json();
  // data.matches — массив текущих матчей, над ним и будет работать ваш бот
  console.log('Текущие live матчи:', data.totalMatches);
}
loadLiveMatches().catch(console.error);

Based on such a request, the bot can select the necessary games (by tournament, teams, country), and then regularly request details for each match to timely find and highlight dangerous episodes.

How to choose a sports statistics API for a bot that warns about dangerous moments

When choosing a sports API for a bot that alerts about dangerous moments, it is important to look not only at the list of sports but also at the depth and freshness of live data. For such a task, the presence of detailed statistics (shots, possession, moments), a set of match events, and the speed of updates are fundamentally important. The API must support popular sports and top tournaments; otherwise, the bot will only cover a narrow segment of the audience and quickly exhaust its potential.

On the infrastructure side, it is important that the API provider ensures high availability, clear limits, and predictable response times. Stable SLAs, Russian-language documentation, the presence of request examples, and a clear description of fields are critical for bot development. The platform api-sport.ru offers a unified stack: API for sports events, API for bookmakers with odds and line dynamics, as well as actively developing new capabilities — WebSocket connections for data streaming and AI-based tools for advanced analysis.

Key criteria for choosing a sports API

  • Wide coverage of sports and tournaments. Football, hockey, basketball, tennis, table tennis, esports, etc.
  • Live statistics and events. Fields minutoDelPartidoActual, eventosEnVivo, estadísticasDelPartido must be updated near real-time.
  • Bookmaker data. Availability of the block oddsBase, so that the bot can react to changes in coefficients and tie the logic to betting.
  • Simple authorization. Operation via API key, which can be quickly obtained in the personal account.
  • Readiness for scaling. Support for both polling and (in the future) WebSocket subscriptions to reduce load and latency.

To start working with the API on the side la cuenta personal api-sport.ru, it is enough to register, create a project, and generate a personal key. The key is then passed in the Authorization header. Below is an example of a request for football matches with filtering by tournaments:

import requests
API_KEY = 'ВАШ_API_КЛЮЧ'
BASE_URL = 'https://api.api-sport.ru/v2/football/matches'
params = {
    'status': 'inprogress',
    'tournament_id': '7,17',  # например, Лига чемпионов и АПЛ
}
resp = requests.get(
    BASE_URL,
    headers={'Authorization': API_KEY},
    params=params,
)
resp.raise_for_status()
data = resp.json()
print('Найдено live матчей:', data.get('totalMatches'))

This approach allows the bot to work only with the necessary tournaments, minimize the volume of downloaded data, and focus on matches where dangerous moments are most interesting to your audience.

What data can be obtained from the sports events API to identify dangerous moments

The concept of a dangerous moment can be formalized in different ways, but it almost always relies on live statistics and match events. Through the sports API, you receive several key data blocks. First of all, this is an array eventosEnVivo, where goals, penalties, cards, the assignment of added time, and other episodes are recorded with reference to the minute of the match and the team. Secondly, this is a detailed array estadísticasDelPartido, which is broken down into groups of shots, ball possession, dribbles, duels, goalkeeper saves, and much more. Thirdly, the field minutoDelPartidoActual allows for a precise understanding of the phase of the game and tracking dynamics over specific time intervals.

For example, in football, a dangerous moment can be considered a series of shots on target, big chances (fields granOportunidadCreada, granOportunidadMarcada), touches in the penalty area (touchesInOppBox), shots hitting the goal frame (golpeóElTravesaño), as well as a sharp increase in the goal coefficient in the block oddsBase. In hockey, this can be a series of shots, penalties, and playing with a man advantage; in basketball — scoring runs and a series of accurate three-pointers. The API api-sport.ru provides a unified data structure for different sports, so you can adapt the logic for identifying dangerous moments for each discipline.

Example of obtaining detailed statistics for a single match

Below is an example of a request that loads data for a specific match and extracts basic metrics to identify dangerous episodes:

const apiKey = 'ВАШ_API_КЛЮЧ';
const matchId = 14570728; // пример ID матча
async function loadMatchDetails() {
  const url = `https://api.api-sport.ru/v2/football/matches/${matchId}`;
  const res = await fetch(url, {
    headers: { Authorization: apiKey },
  });
  const match = await res.json();
  console.log('Текущая минута:', match.currentMatchMinute);
  // Пример: просмотр live событий
  match.liveEvents.forEach((event) => {
    console.log(event.time, event.type, event.team, event.reason);
  });
  // Поиск статистики ALL периода
  const allPeriod = match.matchStatistics.find((p) => p.period === 'ALL');
  if (!allPeriod) return;
  const shotsGroup = allPeriod.groups.find((g) => g.groupName === 'Shots');
  if (shotsGroup) {
    const shotsOnGoal = shotsGroup.statisticsItems.find((s) => s.key === 'shotsOnGoal');
    console.log('Удары в створ (дом/гости):', shotsOnGoal.homeValue, shotsOnGoal.awayValue);
  }
}
loadMatchDetails().catch(console.error);

This data can be wrapped in simple rules: if in the last 10 minutes the team has made more than a certain number of shots on target, if a penalty has been awarded, or if the number of touches in the penalty area has sharply increased, the bot generates a notification for the user. Similarly, changes in odds from the block can be used oddsBase, to react to situations that the betting market considers potentially productive.

How to set up data processing from the API to determine dangerous moments in real time

After you have determined which fields of the sports API are important for your logic, the next step is to set up real-time data processing. This is usually implemented through regular polling: a background process requests a list of live matches and details for the games you are interested in every N seconds. Soon, the infrastructure of api-sport.ru will have WebSocket, which will allow updates to be received without constant requests and reduce the delay between an event on the field and a notification from the bot.

When polling, it is important to properly design the request frequency and caching. For example, it makes sense to update the list of live matches less frequently, while data for selected matches should be updated more often. Upon receiving a response, you save it in operational storage (Redis, in-memory cache) and compare it with the previous state: have new events appeared in eventosEnVivo, have key statistics or odds changed. It is on these differences that the logic for identifying dangerous moments is built.

Example of periodic checking for dangerous moments

Below is a simplified example in Python that cyclically checks matches and outputs messages about dangerous episodes to the console. In a working bot, these messages will be sent to a chat or another notification system.

import time
import requests
API_KEY = 'ВАШ_API_КЛЮЧ'
BASE_URL = 'https://api.api-sport.ru/v2/football/matches'
seen_events = set()

def check_dangerous_moments():
    resp = requests.get(
        BASE_URL,
        headers={'Authorization': API_KEY},
        params={'status': 'inprogress'},
    )
    resp.raise_for_status()
    data = resp.json()
    for match in data.get('matches', []):
        match_id = match['id']
        for ev in match.get('liveEvents', []):
            key = (match_id, ev['time'], ev['type'], ev.get('reason'))
            if key in seen_events:
                continue
            seen_events.add(key)
            # Простейшее правило: пенальти или гол — всегда опасный момент
            if ev['type'] == 'inGamePenalty' or (ev['type'] == 'goal'):
                print(f'Опасный момент в матче {match_id} на {ev["time"]}-й минуте')

if __name__ == '__main__':
    while True:
        check_dangerous_moments()
        time.sleep(15)  # период опроса в секундах

In a real project, you will complement such rules with analysis estadísticasDelPartido, thresholds for strikes, possession, and xG-proxy metrics, as well as signals from the bookmaker block oddsBase. Switching to WebSocket as soon as it becomes available will allow for instant event reception without polling and will make the bot’s operation almost synchronous with the broadcast.

How to implement a bot for notifications about dangerous moments: step-by-step instructions

Implementing a bot for alerts about dangerous moments follows a clear sequence of steps. First, you define the target audience: fans of a specific club, bettors, users watching several matches at once. Then you choose the sports and tournaments. Next, you formulate the rules for what exactly constitutes a dangerous moment and on which channel the user will receive notifications: messenger, web widget, mobile app, or internal analytics panel.

After that, you register on the platform, obtain an API key in your personal account, and implement the server part of the bot. The server is responsible for polling the sports events API, analyzing data, and queuing notifications. The client part (chatbot or frontend) retrieves these notifications and displays them to the user. An important point is to keep the minimum state on the client so that all heavy logic and API integration remain on your backend side.

Conditional development plan for the bot

  • Step 1. Register and obtain a key in the personal account at api-sport.ru.
  • Step 2. Define the sport, tournaments, and types of events that the bot will respond to.
  • Step 3. Describe the rules for dangerous moments in the form of algorithms and threshold values.
  • Step 4. Implement the service for processing API data and storing match states.
  • Step 5. Connect the notification delivery channel and test the end-to-end chain.

Below is a simplified example in Node.js that illustrates the idea of a bot core service. It does not implement integration with a specific messenger but shows how to process matches and generate events to send to the user.

const fetch = require('node-fetch');
const API_KEY = 'ВАШ_API_КЛЮЧ';
const BASE_URL = 'https://api.api-sport.ru/v2/football/matches';
async function detectDangerousMoments() {
  const res = await fetch(`${BASE_URL}?status=inprogress`, {
    headers: { Authorization: API_KEY },
  });
  const data = await res.json();
  const notifications = [];
  for (const match of data.matches || []) {
    const minute = match.currentMatchMinute;
    const events = match.liveEvents || [];
    for (const ev of events) {
      if (ev.type === 'inGamePenalty' || ev.type === 'goal') {
        notifications.push({
          matchId: match.id,
          minute: ev.time,
          text: `Опасный момент в матче ${match.id}: ${ev.type} на ${ev.time}-й минуте`,
        });
      }
    }
  }
  return notifications;
}
setInterval(async () => {
  const notes = await detectDangerousMoments();
  for (const n of notes) {
    // Здесь вы вызываете логику отправки сообщения в ваш канал
    console.log('Уведомление:', n.text);
  }
}, 15000);

In production, it is better to queue such notifications (for example, through a message broker) and then retrieve them with a separate worker that communicates with the API of the chosen messenger. This ensures scalability and allows for the painless addition of new types of rules and sports as your bot evolves.

How to test and launch a bot with notifications about dangerous moments through the sports API

Transitioning from a prototype to a live launch of the bot requires careful testing of the entire chain: from requests to the sports API to delivering notifications to the end user. It makes sense to first test the operation on a limited set of matches: select one or two tournaments and a few matches by their identifiers. This will help ensure that the filtering logic, calculation of dangerous moments, and message formatting work correctly, as well as that you correctly handle match statuses (notstarted, inprogress, finished, and others).

At the next stage, it is important to check the bot’s behavior under conditions close to real-world scenarios: load testing, simulating peaks (weekends, evening hours, playoffs), checking the response to connection drops or temporary service unavailability. It is important to log all API requests and responses, as well as key decisions of the dangerous moment detection algorithm. This will simplify error analysis and allow for fine-tuning thresholds so that the bot is neither too silent nor overly intrusive.

Example of filtering matches for testing and basic response validation.

Below is a snippet of code in Python that demonstrates a request to the API with a selection of matches by specific tournaments and basic validation of the response structure. This step is useful to include in automated tests and monitoring.

import requests
API_KEY = 'ВАШ_API_КЛЮЧ'
URL = 'https://api.api-sport.ru/v2/football/matches'
params = {
    'status': 'inprogress',
    'tournament_id': '7,17',
}
resp = requests.get(URL, headers={'Authorization': API_KEY}, params=params)
if resp.status_code == 401:
    raise RuntimeError('Проблема с API-ключом, проверьте настройки')
resp.raise_for_status()
data = resp.json()
assert 'matches' in data, 'В ответе нет списка матчей'
for match in data['matches']:
    assert 'id' in match and 'currentMatchMinute' in match, 'Некорректная структура матча'
print('Тест успешен, матчей в выборке:', data['totalMatches'])

After technical testing, it is worth conducting a pilot launch with a small group of users. Gather feedback: which notifications seem truly useful to them, what moments are lacking, and where the bot triggers too often. Based on this data, you can fine-tune the algorithms, add the use of coefficients from the block, oddsBase, adjust thresholds based on statistics. Next, a monitoring system is connected (alerts for errors, dashboards for the number of notifications and delays), and the bot is ready for a full commercial launch and further scaling.