Menu Zamknij

Building a Python Telegram Bot to Check CSMatch Stats After a Premiere Match

If you’ve ever wanted instant updates on your CS

Premiere matches without constantly refreshing stats websites, you’re in luck! With a little Python and the magic of Telegram, you can create a Telegram bot that automatically fetches and shares match stats from CSStats right after your game. Whether you’re showing off your latest ace or keeping tabs on your performance, this bot will make your CS

life much easier.

Let’s dive into how you can build this handy bot that does all the heavy lifting for you!


What You’ll Need

To get this project rolling, here’s a list of the basic tools and accounts you’ll need:

  1. Python: Preferably Python 3.x.
  2. Telegram Bot Token: You can get this by creating a bot through BotFather on Telegram.
  3. CSStats API or CSstats source: This is where you’ll fetch match stats after each game.
  4. Python Libraries: You’ll need python-telegram-bot for interacting with Telegram, and requests to make HTTP requests to CSStats.
  5. A Telegram Account: You’ll be interacting with your bot here!

Step 1: Creating Your Telegram Bot

First, you’ll need to create a Telegram bot using BotFather:

  1. Open Telegram and search for @BotFather.
  2. Start a chat with BotFather and type /newbot.
  3. Follow the prompts to name your bot and get a bot token. You’ll need this token for the Python code, so keep it handy.

Step 2: Setting Up the Python Environment

To get started, you’ll need to install a few Python libraries. Open your terminal or command prompt and run the following commands to install the necessary packages:

pip install python-telegram-bot requests

These will let you easily interact with the Telegram API and send HTTP requests to fetch stats.


Step 3: Writing the Bot Code

Here’s a basic Python script that checks your CS

stats after a Premiere match and sends them to your Telegram bot.

Importing Required Libraries

import requests
from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext

# CSStats API (replace with your actual API source or endpoint)
CSSTATS_API_URL = 'https://api.csstats.example.com/match_stats/'

# Replace with your Telegram bot token
TELEGRAM_BOT_TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'

Function to Fetch CSMatch Stats

Let’s define a function that pulls the latest stats from CSStats. You’ll need the match ID (or player ID, depending on the API) to get specific stats.

def get_match_stats(player_id: str) -> dict:
"""Fetches match stats from CSStats API."""
response = requests.get(f"{CSSTATS_API_URL}{player_id}")

if response.status_code == 200:
return response.json() # Returns stats as a dictionary
else:
return {"error": "Could not fetch match stats. Please try again later."}

Here, player_id would be the ID associated with your CS

profile on CSStats (or whichever stats provider you’re using).

Command to Fetch Stats

Next, you’ll create a command in your bot to trigger the stats check. This function will respond to the /stats command from users and send back the match data.

def check_stats(update: Update, context: CallbackContext):
"""Telegram command to check latest CS:GO match stats."""
chat_id = update.message.chat_id
player_id = context.args[0] # Pass the player ID as an argument to the bot command

stats = get_match_stats(player_id)

if "error" in stats:
context.bot.send_message(chat_id=chat_id, text=stats["error"])
else:
match_result = f"""
Match Results for Player {player_id}:
- Kills: {stats['kills']}
- Deaths: {stats['deaths']}
- MVPs: {stats['mvps']}
- Headshots: {stats['headshots']}%
- Total Score: {stats['score']}
"""
context.bot.send_message(chat_id=chat_id, text=match_result)

In this function, the player’s CS

stats (kills, deaths, MVPs, etc.) are fetched and sent back as a formatted message. You can customize this message to include any data available in the API response.


Step 4: Putting It All Together

Finally, you need to create the bot’s main function, which will handle incoming messages and respond to commands.

def main():
"""Start the bot."""
updater = Updater(token=TELEGRAM_BOT_TOKEN, use_context=True)
dispatcher = updater.dispatcher

# Command to check stats
dispatcher.add_handler(CommandHandler('stats', check_stats))

# Start the Bot
updater.start_polling()
print("Bot is running...")

# Keep the bot running until interrupted
updater.idle()

if __name__ == '__main__':
main()

Here’s a breakdown of what this script does:

  • It initializes the bot with your Telegram bot token.
  • It sets up the /stats command that calls the check_stats() function.
  • It starts polling Telegram for messages and commands.

Step 5: Running the Bot

Save the code to a Python file (e.g., telegram_bot.py), and run it with:

python telegram_bot.py

Your bot is now live! You can interact with it by sending a /stats command followed by your CS

player ID. For example:

/stats 76561198012345678

The bot will reply with your latest match stats straight from CSStats.


Bonus: Automating Post-Match Updates

Want the bot to automatically notify you after every match? You can schedule the bot to periodically check for new match data by using Python’s schedule library or Telegram’s job queue feature. This way, after every Premiere match, the bot can fetch the latest stats and push them to you.


Final Thoughts: Game Stats at Your Fingertips

With this Python bot, you’ve now automated one of the most tedious parts of competitive gaming—checking your post-match stats. By leveraging the power of Telegram and Python, you can stay updated on your performance with ease, all while impressing your friends with your newfound coding skills. The bot can be customized further to track multiple players, send match highlights, or even analyze performance trends over time.

So whether you’re a CS

pro or just a casual player, your stats will always be just one chat away! Happy coding and happy fragging!

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *