{"id":79,"date":"2024-09-19T11:31:19","date_gmt":"2024-09-19T09:31:19","guid":{"rendered":"https:\/\/lukasza.hopto.org\/blog\/wordpress\/?p=79"},"modified":"2024-12-18T13:15:40","modified_gmt":"2024-12-18T12:15:40","slug":"building-a-python-telegram-bot-to-check-csmatch-stats-after-a-premiere-match","status":"publish","type":"post","link":"https:\/\/lukasza.hopto.org\/index.php\/2024\/09\/19\/building-a-python-telegram-bot-to-check-csmatch-stats-after-a-premiere-match\/","title":{"rendered":"Building a Python Telegram Bot to Check CSMatch Stats After a Premiere Match"},"content":{"rendered":"\n<p>If you\u2019ve ever wanted instant updates on your <strong>CS<\/strong><\/p>\n\n\n\n<p><strong>Premiere<\/strong> matches without constantly refreshing stats websites, you\u2019re in luck! With a little Python and the magic of Telegram, you can create a <strong>Telegram bot<\/strong> that automatically fetches and shares match stats from <strong>CSStats<\/strong> right after your game. Whether you\u2019re showing off your latest ace or keeping tabs on your performance, this bot will make your CS<\/p>\n\n\n\n<p>life much easier.<\/p>\n\n\n\n<p>Let\u2019s dive into how you can build this handy bot that does all the heavy lifting for you!<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>What You\u2019ll Need<\/strong><\/h3>\n\n\n\n<p>To get this project rolling, here\u2019s a list of the basic tools and accounts you\u2019ll need:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Python<\/strong>: Preferably Python 3.x.<\/li>\n\n\n\n<li><strong>Telegram Bot Token<\/strong>: You can get this by creating a bot through <a>BotFather<\/a> on Telegram.<\/li>\n\n\n\n<li><strong>CSStats API or CSstats source<\/strong>: This is where you\u2019ll fetch match stats after each game.<\/li>\n\n\n\n<li><strong>Python Libraries<\/strong>: You\u2019ll need <code>python-telegram-bot<\/code> for interacting with Telegram, and <code>requests<\/code> to make HTTP requests to CSStats.<\/li>\n\n\n\n<li><strong>A Telegram Account<\/strong>: You\u2019ll be interacting with your bot here!<\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 1: Creating Your Telegram Bot<\/strong><\/h3>\n\n\n\n<p>First, you\u2019ll need to create a Telegram bot using <strong>BotFather<\/strong>:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Open <strong>Telegram<\/strong> and search for <code>@BotFather<\/code>.<\/li>\n\n\n\n<li>Start a chat with BotFather and type <code>\/newbot<\/code>.<\/li>\n\n\n\n<li>Follow the prompts to name your bot and get a <strong>bot token<\/strong>. You\u2019ll need this token for the Python code, so keep it handy.<\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 2: Setting Up the Python Environment<\/strong><\/h3>\n\n\n\n<p>To get started, you\u2019ll need to install a few Python libraries. Open your terminal or command prompt and run the following commands to install the necessary packages:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>pip install python-telegram-bot requests<br><\/code><\/pre>\n\n\n\n<p>These will let you easily interact with the Telegram API and send HTTP requests to fetch stats.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 3: Writing the Bot Code<\/strong><\/h3>\n\n\n\n<p>Here\u2019s a basic Python script that checks your CS<\/p>\n\n\n\n<p>stats after a Premiere match and sends them to your Telegram bot.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Importing Required Libraries<\/strong><\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>import requests<br>from telegram import Update<br>from telegram.ext import Updater, CommandHandler, CallbackContext<br><br># CSStats API (replace with your actual API source or endpoint)<br>CSSTATS_API_URL = 'https:\/\/api.csstats.example.com\/match_stats\/'<br><br># Replace with your Telegram bot token<br>TELEGRAM_BOT_TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'<br><\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Function to Fetch CSMatch Stats<\/strong><\/h4>\n\n\n\n<p>Let\u2019s define a function that pulls the latest stats from CSStats. You\u2019ll need the match ID (or player ID, depending on the API) to get specific stats.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>def get_match_stats(player_id: str) -&gt; dict:<br>    \"\"\"Fetches match stats from CSStats API.\"\"\"<br>    response = requests.get(f\"{CSSTATS_API_URL}{player_id}\")<br>    <br>    if response.status_code == 200:<br>        return response.json()  # Returns stats as a dictionary<br>    else:<br>        return {\"error\": \"Could not fetch match stats. Please try again later.\"}<br><\/code><\/pre>\n\n\n\n<p>Here, <code>player_id<\/code> would be the ID associated with your CS<\/p>\n\n\n\n<p>profile on CSStats (or whichever stats provider you\u2019re using).<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Command to Fetch Stats<\/strong><\/h4>\n\n\n\n<p>Next, you\u2019ll create a command in your bot to trigger the stats check. This function will respond to the <code>\/stats<\/code> command from users and send back the match data.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>def check_stats(update: Update, context: CallbackContext):<br>    \"\"\"Telegram command to check latest CS:GO match stats.\"\"\"<br>    chat_id = update.message.chat_id<br>    player_id = context.args[0]  # Pass the player ID as an argument to the bot command<br>    <br>    stats = get_match_stats(player_id)<br>    <br>    if \"error\" in stats:<br>        context.bot.send_message(chat_id=chat_id, text=stats[\"error\"])<br>    else:<br>        match_result = f\"\"\"<br>        Match Results for Player {player_id}:<br>        - Kills: {stats['kills']}<br>        - Deaths: {stats['deaths']}<br>        - MVPs: {stats['mvps']}<br>        - Headshots: {stats['headshots']}%<br>        - Total Score: {stats['score']}<br>        \"\"\"<br>        context.bot.send_message(chat_id=chat_id, text=match_result)<br><\/code><\/pre>\n\n\n\n<p>In this function, the player\u2019s CS<\/p>\n\n\n\n<p>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.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 4: Putting It All Together<\/strong><\/h3>\n\n\n\n<p>Finally, you need to create the bot\u2019s main function, which will handle incoming messages and respond to commands.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>def main():<br>    \"\"\"Start the bot.\"\"\"<br>    updater = Updater(token=TELEGRAM_BOT_TOKEN, use_context=True)<br>    dispatcher = updater.dispatcher<br>    <br>    # Command to check stats<br>    dispatcher.add_handler(CommandHandler('stats', check_stats))<br>    <br>    # Start the Bot<br>    updater.start_polling()<br>    print(\"Bot is running...\")<br>    <br>    # Keep the bot running until interrupted<br>    updater.idle()<br><br>if __name__ == '__main__':<br>    main()<br><\/code><\/pre>\n\n\n\n<p>Here\u2019s a breakdown of what this script does:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>It initializes the bot with your <strong>Telegram bot token<\/strong>.<\/li>\n\n\n\n<li>It sets up the <code>\/stats<\/code> command that calls the <code>check_stats()<\/code> function.<\/li>\n\n\n\n<li>It starts polling Telegram for messages and commands.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Step 5: Running the Bot<\/strong><\/h3>\n\n\n\n<p>Save the code to a Python file (e.g., <code>telegram_bot.py<\/code>), and run it with:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>python telegram_bot.py<br><\/code><\/pre>\n\n\n\n<p>Your bot is now live! You can interact with it by sending a <code>\/stats<\/code> command followed by your CS<\/p>\n\n\n\n<p>player ID. For example:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><code>\/stats 76561198012345678<br><\/code><\/pre>\n\n\n\n<p>The bot will reply with your latest match stats straight from CSStats.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Bonus: Automating Post-Match Updates<\/strong><\/h3>\n\n\n\n<p>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\u2019s <code>schedule<\/code> library or Telegram\u2019s job queue feature. This way, after every Premiere match, the bot can fetch the latest stats and push them to you.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Final Thoughts: Game Stats at Your Fingertips<\/strong><\/h3>\n\n\n\n<p>With this Python bot, you\u2019ve now automated one of the most tedious parts of competitive gaming\u2014checking your post-match stats. By leveraging the power of <strong>Telegram<\/strong> and <strong>Python<\/strong>, 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.<\/p>\n\n\n\n<p>So whether you\u2019re a CS<\/p>\n\n\n\n<p>pro or just a casual player, your stats will always be just one chat away! Happy coding and happy fragging!<\/p>\n\n\n\n<script type=\"text\/javascript\" src=\"https:\/\/cdnjs.buymeacoffee.com\/1.0.0\/button.prod.min.js\" data-name=\"bmc-button\" data-slug=\"lukasza\" data-color=\"#BD5FFF\" data-emoji=\"\"  data-font=\"Cookie\" data-text=\"Buy me a coffee\" data-outline-color=\"#000000\" data-font-color=\"#ffffff\" data-coffee-color=\"#FFDD00\" ><\/script>\n","protected":false},"excerpt":{"rendered":"<p>If you\u2019ve ever wanted instant updates on your CS Premiere matches without constantly refreshing stats websites, you\u2019re in luck! With a little Python and the&hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,2],"tags":[9,14,26,37],"class_list":["post-79","post","type-post","status-publish","format-standard","hentry","category-bez-kategorii","category-ogolne","tag-cs-stats","tag-gaming","tag-pthon","tag-telegram-bot"],"_links":{"self":[{"href":"https:\/\/lukasza.hopto.org\/index.php\/wp-json\/wp\/v2\/posts\/79","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/lukasza.hopto.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/lukasza.hopto.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/lukasza.hopto.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/lukasza.hopto.org\/index.php\/wp-json\/wp\/v2\/comments?post=79"}],"version-history":[{"count":1,"href":"https:\/\/lukasza.hopto.org\/index.php\/wp-json\/wp\/v2\/posts\/79\/revisions"}],"predecessor-version":[{"id":148,"href":"https:\/\/lukasza.hopto.org\/index.php\/wp-json\/wp\/v2\/posts\/79\/revisions\/148"}],"wp:attachment":[{"href":"https:\/\/lukasza.hopto.org\/index.php\/wp-json\/wp\/v2\/media?parent=79"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/lukasza.hopto.org\/index.php\/wp-json\/wp\/v2\/categories?post=79"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/lukasza.hopto.org\/index.php\/wp-json\/wp\/v2\/tags?post=79"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}