You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何改造Discord bot调用ev.io API实现$stats指令查询游戏数据

功能实现调整方案

前置准备

先安装异步请求库避免阻塞bot运行:
pip install aiohttp

完整修改后代码

import Keep_alive
import discord
import os
import asyncio
import aiohttp
from discord import Embed
from discord.ext import commands
import datetime as dt

# 注意需要提前去Discord开发者后台开启对应权限,比如Message Content Intent
bot = commands.Bot(command_prefix='$', intents=discord.Intents.all())

@bot.command()
async def test(ctx, arg):
  await ctx.send(arg)

@bot.command()
async def stats(ctx, username: str):
    api_url = f"https://ev.io/stats-by-un/{username}"
    async with aiohttp.ClientSession() as session:
        try:
            async with session.get(api_url, timeout=10) as resp:
                if resp.status != 200:
                    await ctx.send(f"查询失败,玩家`{username}`不存在或接口请求异常")
                    return
                stats_data = await resp.json()
        except asyncio.TimeoutError:
            await ctx.send("请求超时,请稍后再试")
            return
        except Exception as e:
            await ctx.send(f"查询出错:{str(e)}")
            return
    
    # 构造Embed展示数据,字段可根据接口实际返回的键名调整
    stats_embed = discord.Embed(
        title=f"{username} 游戏统计数据",
        color=discord.Color.blue(),
        timestamp=dt.datetime.utcnow()
    )
    # 示例字段,可根据接口返回内容自定义增删
    stats_embed.add_field(name="总击杀", value=stats_data.get("kills", "无数据"), inline=True)
    stats_embed.add_field(name="总死亡", value=stats_data.get("deaths", "无数据"), inline=True)
    stats_embed.add_field(name="KD值", value=stats_data.get("kd", "无数据"), inline=True)
    stats_embed.add_field(name="总对局数", value=stats_data.get("matches", "无数据"), inline=True)
    stats_embed.add_field(name="胜率", value=f"{stats_data.get('win_rate', 0)*100:.1f}%" if stats_data.get('win_rate') else "无数据", inline=True)
    stats_embed.add_field(name="最高单局击杀", value=stats_data.get("max_kills", "无数据"), inline=True)
    stats_embed.set_footer(text="数据来源:ev.io官方接口")

    await ctx.send(embed=stats_embed)

@bot.command()
async def embed(ctx):
  embed=discord.Embed(
  title="Hello!",
  description="Im a embed text!")
  await ctx.send(embed=embed)

Keep_alive.Keep_alive()  
bot.run("你的bot token")

注意事项

  • 未开启Message Content Intent权限会导致bot无法读取消息内容、无法触发命令,需要去Discord开发者后台的bot设置页手动开启
  • 如果要支持带空格的用户名查询,把stats命令的参数定义改成async def stats(ctx, *, username: str):即可
  • 代码中Embed展示的字段为示例值,可以根据ev.io接口实际返回的JSON键名自行调整增删

内容的提问来源于stack exchange,提问作者0zone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 20:45:01