惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

小众软件
小众软件
WordPress大学
WordPress大学
IT之家
IT之家
G
Google Developers Blog
Vercel News
Vercel News
阮一峰的网络日志
阮一峰的网络日志
博客园 - 三生石上(FineUI控件)
Engineering at Meta
Engineering at Meta
Martin Fowler
Martin Fowler
V
V2EX
爱范儿
爱范儿
Hugging Face - Blog
Hugging Face - Blog
Apple Machine Learning Research
Apple Machine Learning Research
B
Blog
V
Visual Studio Blog
有赞技术团队
有赞技术团队
I
InfoQ
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
月光博客
月光博客
J
Java Code Geeks
Stack Overflow Blog
Stack Overflow Blog
P
Proofpoint News Feed
云风的 BLOG
云风的 BLOG
雷峰网
雷峰网

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How to build a CS2 live score Discord bot
Kanyik Tesh · 2026-06-28 · via DEV Community
Cover image for How to build a CS2 live score Discord bot

Kanyik Tesh

Original post:

What we're building
By the end of this guide, you'll have a Discord bot that posts live CS2 match scores to a channel, updates every 60 seconds, and shows team names, current map, and odds. No database required — everything comes straight from the API.

Prerequisites
You'll need Node.js installed (v18 or newer), a Discord bot token from the Discord Developer Portal, and a free Tachio Sports API key. Sign up on the homepage with GitHub to get yours.

Step 1 — Create the Discord bot
Go to discord.com/developers/applications and create a new application. Under the Bot tab, click Add Bot and copy the token. Invite the bot to your server with the 'bot' and 'Send Messages' permissions. Keep your token secret — it's like a password for your bot.

Step 2 — Set up the project

mkdir cs2-discord-bot
cd cs2-discord-bot
npm init -y
npm install discord.js

Step 3 — The complete bot code

const { Client, GatewayIntentBits, EmbedBuilder } = require("discord.js");

const DISCORD_TOKEN = process.env.DISCORD_TOKEN;
const API_KEY = process.env.TACHIO_API_KEY;
const CHANNEL_ID = process.env.CHANNEL_ID;

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
  ],
});

async function fetchLiveMatches() {
  const res = await fetch(
    "https://api.tachiosports.com/esports/live/cs2",
    { headers: { "x-api-key": API_KEY } },
  );
  if (!res.ok) return [];
  const data = await res.json();
  return data.matches ?? [];
}

function buildEmbed(match) {
  const home = match.teams.home.name ?? "TBD";
  const away = match.teams.away.name ?? "TBD";
  const score = match.score?.display ?? "vs";
  const map = match.current_map ?? "";
  const format = match.match_format ?? "";
  const league = match.league.name ?? "";
  const oddsHome = match.odds.match_winner.home ?? "";
  const oddsAway = match.odds.match_winner.away ?? "";

  return new EmbedBuilder()
    .setColor(0xde9b35)
    .setTitle(`${home} ${score} ${away}`)
    .setDescription(
      `${format} | ${map}\n${league}\n\n**Odds:** ${oddsHome}${oddsAway}`,
    )
    .setTimestamp();
}

let lastMessageId = null;

async function updateScores() {
  const channel = client.channels.cache.get(CHANNEL_ID);
  if (!channel) return;

  const matches = await fetchLiveMatches();
  if (matches.length === 0) {
    channel.send("No live CS2 matches right now.");
    return;
  }

  if (lastMessageId) {
    try {
      const oldMsg = await channel.messages.fetch(lastMessageId);
      await oldMsg.delete();
    } catch {}
  }

  const embeds = matches.slice(0, 10).map(buildEmbed);
  const msg = await channel.send({
    content: `**⚡ Live CS2 Matches — ${matches.length} online**`,
    embeds,
  });
  lastMessageId = msg.id;
}

client.once("ready", () => {
  console.log(`Bot logged in as ${client.user.tag}`);
  updateScores();
  setInterval(updateScores, 60_000);
});

client.login(DISCORD_TOKEN);

How it works
The bot calls the Tachio Sports API every 60 seconds to get live CS2 matches. It builds a Discord embed for each match showing the teams, score, current map, league, and odds. The old message is deleted before posting a new one so the channel stays clean with only the latest scores visible.

Step 4 — Run the bot

# Set your environment variables
export DISCORD_TOKEN=your-discord-bot-token
export TACHIO_API_KEY=your-tachio-api-key
export CHANNEL_ID=your-discord-channel-id

# Start the bot
node index.js

Step 5 — Deploy (free on Railway)
To keep the bot running 24/7 without your computer, deploy it to a free hosting service like Railway or Render. Push your code to GitHub, connect the repo to Railway, set the three environment variables, and deploy. The free tier handles a single bot easily.

Going further
Want more? Add a slash command like /scores that posts live scores on demand. Monitor multiple games by changing the sport parameter. Use the WebSocket endpoint for instant updates instead of polling. Add map scores by reading the maps array. The Tachio API has everything you need to build a production-ready esports bot.

Quick tip — Slash command

// Add this before client.login()
client.on("interactionCreate", async (interaction) => {
  if (!interaction.isCommand()) return;
  if (interaction.commandName === "scores") {
    await interaction.deferReply();
    const matches = await fetchLiveMatches();
    const embeds = matches.slice(0, 10).map(buildEmbed);
    await interaction.editReply({
      content: `Live CS2 Matches — ${matches.length} online`,
      embeds,
    });
  }
});

// Register the command (run once):
// const { REST, Routes } = require("discord.js");
// const rest = new REST().setToken(DISCORD_TOKEN);
// await rest.put(Routes.applicationCommands(CLIENT_ID), {
//   body: [{ name: "scores", description: "Show live CS2 match scores" }],
// });

And that's it. In under 50 lines of code you've built a live CS2 score bot that your Discord server will love. The Tachio Sports API handles the hard part — you just build the experience. Ready to ship? Grab your API key and start coding.

https://tachiosports.com