- What is xG in football and why do you need a Telegram bot with xG analytics
- Choosing a sports events API to obtain match xG statistics
- How to get keys and set up access to the football statistics API
- How to create and register a Telegram bot for football analytics
- Connecting the xG analytics API to the Telegram bot: step-by-step instructions
- Examples of API requests and Telegram bot code with match xG analytics
- How to set up notifications in Telegram for xG and other match metrics
What is xG in football and why do you need a Telegram bot with xG analytics
xG (expected goals) is a metric that assesses the likelihood that a specific shot on goal will result in a goal. It uses dozens of factors for calculation: distance to the goal, angle of the shot, type of pass (cross, lob, through ball), position of defenders and the goalkeeper, type of shot (header, foot), situation (penalty, set piece, open play) and much more. As a result, each attacking attempt receives a value from 0 to 1, and the team’s total xG shows how many goals they «should have» scored based on the quality of chances.
Unlike the shot counter and ball possession, xG answers a more precise question: who created truly dangerous moments, and who simply controlled the ball without real threat. This is why the metric is widely used in professional analytics, scouting, media, and betting. Comparing the actual score and xG allows you to see who was lucky and who missed their goals, assess the sustainability of current results, and the quality of the team’s play over time.
A Telegram bot with xG analytics turns complex statistics into a convenient tool that is always at hand for fans, analysts, or bettors. The user can find out in a couple of clicks how the balance of chances changed during the match, who dominates in terms of chance quality, and at what moment the risk or value in betting becomes most interesting. The bot can send push notifications when there is a sharp increase in xG, a series of dangerous attacks appears, or there is a discrepancy between the score and expected goals.
The basis of such a solution is high-quality sports data in live mode. Through API de eventos deportivos you get detailed statistics of football matches, including shots, moments, possession, duels, and other key metrics. Based on them, you can build your own xG calculation model and integrate it into a Telegram bot, expanding functionality with other sports, esports, and betting odds as the project grows.
Choosing a sports events API to obtain match xG statistics
For the Telegram bot with xG analytics to work reliably and provide users with accurate hints, a reliable data source is needed. It is critical that the API provides not only the match score but also extended statistics: shots on target and off target, shots from inside and outside the penalty area, «big chances,» possession, number of passes, and entries into the final third. Such indicators are contained in the object estadísticasDelPartido in the Sport Events API and allow building your own expected goals models.
An important selection parameter is support for live mode and data update speed. For a bot that analyzes xG «on the fly,» it is essential that the statistics are updated during the match, not just after the final whistle. The endpoints /v2/fútbol/partidos и /v2/fútbol/partidos/{matchId} return not only basic information but also fields minutoDelPartidoActual, eventosEnVivo и estadísticasDelPartido, that allow tracking the course of the game in real time, the emergence of dangerous moments, and the dynamics of attacking activity.
It is also worth noting how the API scales under different scenarios. The platform api-sport.ru supports football, hockey, basketball, tennis, table tennis, esports, and other sports, and also contains a block of data on betting markets (oddsBase). This means that you can start with a Telegram bot for football and xG, and then gradually expand functionality: adding analytics for other sports, combining xG with the dynamics of bookmaker odds, connecting upcoming WebSocket capabilities and AI models without a complete overhaul of the bot’s architecture.
How to get keys and set up access to the football statistics API
The first step to creating a Telegram bot with xG analytics is to gain access to the Sport Events API. To do this, you need to register at la cuenta personal., create a project, and generate a unique API key. The key is used for authorizing each request and is passed in the header Autorización. This approach allows for flexible management of limits, transparent traffic tracking, and restricting access if necessary.
After obtaining the key, you can immediately test basic requests to the football section of the API. All sports use a unified URL format with the parameter {sportSlug}, so for football, the base path will be as follows: https://api.api-sport.ru/v2/football. To, for example, get a list of current live matches with basic statistics, it is enough to send a GET request to the endpoint /matches with the parameter status=inprogress and the authorization header.
An example of a simple request via curl might look like this:
curl -X GET "https://api.api-sport.ru/v2/football/matches?status=inprogress" \ -H "Authorization: ВАШ_API_КЛЮЧ"
In response, you will receive a JSON object with the field totalMatches and an array partidos. Each element of the array contains the match ID, score, status, current minute, as well as an array estadísticasDelPartido if statistics are available. These data will be used for calculating xG within your server or directly in the Telegram bot code. It is important to handle error codes correctly (for example, 401 for an incorrect key or exceeding the limit) and to provide logging of requests — this will simplify debugging and scaling the project.
How to create and register a Telegram bot for football analytics
Once access to the sports API is set up, you can proceed to create the Telegram bot. To register a bot in Telegram, you need to contact the BotFather service bot, execute the command to create a new bot, set a name and a unique @username. In response, BotFather will issue a token in the format 123456789:ABCDEF... — it must be saved and used on the server side to work with the Bot API.
Next, a technology stack is chosen for implementing the logic. Often, Python is used for such tasks (libraries aiogram, python-telegram-bot) or Node.js (node-telegram-bot-api, telegraf). The language is not critical: the main thing is that the chosen framework allows for convenient handling of commands, callback buttons, inline requests, and works asynchronously — this is especially useful when frequently accessing the external API of sports events.
A typical minimal stack for a Python project includes installing the Telegram client library and an HTTP client for working with the REST API:
pip install aiogram requests
It is recommended to store the Telegram bot token and the Sport Events API key in environment variables or in a separate configuration file that does not get into version control. This approach enhances security and simplifies the transfer of the bot between the testing and production environments. At this stage, you can implement a simple command, for example /start, to ensure that the bot responds to users, and only then proceed to integrate xG analytics and requests to the sports events API.
Connecting the xG analytics API to the Telegram bot: step-by-step instructions
The integration of xG analytics into the Telegram bot is built on a clear chain: the bot receives a command from the user, requests the necessary data from the Sport Events API, calculates xG based on the chosen model, and returns the result in a convenient text or graphic form. In practice, this means several sequential steps that are easily scalable as functionality grows.
First, the bot determines which matches interest the user: it can be a specific league, team, or just a list of all current live matches. For example, upon request, /live, the bot queries the endpoint /v2/fútbol/partidos with a filter by status or tournament. The user selects the desired match, after which the bot requests its details via /v2/fútbol/partidos/{matchId} and receives an object estadísticasDelPartido, containing groups of metrics (Shots, Attack, Passes, etc.).
Based on these statistics, a simplified xG model can be implemented. For example, assign base weights to shots from inside and outside the penalty area, as well as to «big chances.» This does not replace an advanced machine model, but is great for the first working prototype of a Telegram bot. Below is an example of a function in Python that calculates conditional xG using fields with keys totalDisparosDentroDelÁrea, totalShotsOutsideBox и granOportunidadCreada de estadísticasDelPartido:
def calculate_simple_xg(match_statistics: list) -> dict:
"""Возвращает примерный xG для хозяев и гостей на основе базовых показателей.
Ожидается, что на вход передается значение поля matchStatistics из ответа API.
"""
home_xg = 0.0
away_xg = 0.0
# Перебираем периоды и группы статистики
for period in match_statistics:
if period.get("period") != "ALL":
continue
for group in period.get("groups", []):
for item in group.get("statisticsItems", []):
key = item.get("key")
hv = float(item.get("homeValue", 0) or 0)
av = float(item.get("awayValue", 0) or 0)
if key == "totalShotsInsideBox":
home_xg += hv * 0.10
away_xg += av * 0.10
elif key == "totalShotsOutsideBox":
home_xg += hv * 0.03
away_xg += av * 0.03
elif key == "bigChanceCreated":
home_xg += hv * 0.35
away_xg += av * 0.35
return {"home_xg": round(home_xg, 2), "away_xg": round(away_xg, 2)}
After calculating xG, the bot forms a response: it shows the score, the current minute, the xG values of both teams, and, if necessary, a textual comment («the hosts are significantly underperforming in goals,» «the guests dominate in the quality of chances»). As the project develops, you can replace the simple formula with a more complex one trained on historical data and use additional fields from estadísticasDelPartido. The current list of key statistics can always be clarified in the documentation API de Eventos Deportivos.
Examples of API requests and Telegram bot code with match xG analytics
Let’s consider how a complete cycle of processing a user’s command in a Telegram bot might look: from querying the sports events API to sending a ready xG report. For simplicity, let’s take Python and the library aiogram. The bot will accept commands of the form /xg, request match details by this identifier, and return a summary of expected goals.
import os
import requests
from aiogram import Bot, Dispatcher, executor, types
API_KEY = os.getenv("SPORT_API_KEY")
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
BASE_URL = "https://api.api-sport.ru/v2/football"
bot = Bot(token=TELEGRAM_TOKEN)
dp = Dispatcher(bot)
def get_match(match_id: int) -> dict:
resp = requests.get(
f"{BASE_URL}/matches/{match_id}",
headers={"Authorization": API_KEY},
timeout=5,
)
resp.raise_for_status()
return resp.json()
@dp.message_handler(commands=["xg"])
async def cmd_xg(message: types.Message):
parts = message.text.split()
if len(parts) != 2 or not parts[1].isdigit():
await message.reply("Использование: /xg <match_id>")
return
match_id = int(parts[1])
data = get_match(match_id)
stats = data.get("matchStatistics", [])
xg = calculate_simple_xg(stats)
home = data["homeTeam"]["name"]
away = data["awayTeam"]["name"]
minute = data.get("currentMatchMinute")
text = (
f"Матч: {home} — {away}"
f"Минута: {minute}'"
f"xG хозяев: {xg['home_xg']}"
f"xG гостей: {xg['away_xg']}"
)
await message.reply(text)
If you want to additionally consider the betting context, you can also display the current bookmaker odds in the same response. To do this, it is enough to read the array oddsBase from the match endpoint response and find the 1X2 market. An example of sampling the required market in Python:
def extract_1x2_odds(match: dict) -> dict | None:
for market in match.get("oddsBase", []):
if market.get("group") == "1X2":
choices = {c["name"]: c["decimal"] for c in market.get("choices", [])}
return {
"home": choices.get("1"),
"draw": choices.get("X"),
"away": choices.get("2"),
}
return None
In the bot’s response, you can compare xG and current odds: showing where the market undervalues the team that dominates in terms of chances. This approach turns a regular info bot into a full-fledged analytical tool that combines match data and information from betting markets available through the Sport Events API.
How to set up notifications in Telegram for xG and other match metrics
One of the key features of a smart sports bot is automatic notifications without user involvement. In the context of xG, these can be signals of a sharp increase in expected goals for one of the teams, a series of dangerous attacks, or a serious mismatch between the score and the quality of chances. To implement such logic, the bot periodically polls the Sport Events API or, as they become available, connects to a WebSocket channel to receive updates almost instantly.
In the polling option, you set up a periodic task (cron, Celery beat, background task in asyncio), which requests current data on the matches of interest every N seconds through /v2/fútbol/partidos or /v2/fútbol/partidos/{matchId}. After receiving estadísticasDelPartido you recalculate xG and compare it with the previous value stored in the database or in the app’s memory. If the increase exceeds a specified threshold (for example, +0.5 xG over a short period of time) or one of the teams significantly «falls short» of their expected goals, the bot sends a message to the subscribers of this match.
An example of a background task in Python using asyncio, that checks for changes in xG every minute and sends notifications might look like this:
import asyncio
async def xg_watcher(match_id: int, chat_id: int):
last_xg = None
while True:
match = get_match(match_id)
stats = match.get("matchStatistics", [])
xg = calculate_simple_xg(stats)
current = xg["home_xg"] + xg["away_xg"]
if last_xg is not None and current - last_xg >= 0.5:
await bot.send_message(
chat_id,
f"Резкий рост xG в матче {match['homeTeam']['name']} — {match['awayTeam']['name']}: {current}",
)
last_xg = current
await asyncio.sleep(60)
Alerts for other metrics can be set up in the same way: a spike in the number of shots on target, a sharp change in ball possession, an increase in the number of attacks in the final third, or changes in coefficients in arrays. oddsBase. As the service develops api-sport.ru you will be able to transfer this logic from periodic polling to WebSocket connections and enhance it with AI models that will not only record events but also assess the probability of a goal or comeback in real time.




