如何改造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
相关产品推荐
相关产品推荐

