首页 > 解决方案 > 如何获取/请求 api:https://ev.io/stats-by-un/(username)

问题描述

当玩家输入 $stats (username) 时,我想在游戏统计中显示

import Keep_alive
import tkinter as tk
import discord
import os
import asyncio
from discord import Embed
from discord.ext import commands
from discord.ext.commands import bot
import asyncio
import datetime as dt

bot = commands.Bot(command_prefix='$')

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

@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("token")

标签: pythondiscord.py

解决方案


首先,您需要请求您需要 requests 模块的 api。

import requests

接下来,您需要知道如何从请求的 api 中获取数据。

@bot.command()
async def stats(ctx, *, username):
    # This is how you request data from the api
    data = requests.get(f"https://ev.io/stats-by-un/{username}").json()
    # This is how you get certain stats from the data
    # I don't know what does this api request, so I'm just going to use kills as an example.
    # Different apis have different methods to get certain data, so it's better to take a look at their documentation.
    kills = data["kills"]
    await ctx.send(f"{username} has {kills} kills in total.")

我不建议在异步代码中使用请求,因为它是阻塞的。discord.py使用aiohttp,所以它应该已经安装了。

这是使用 aiohttp 和 discord.py 的示例代码:

async with aiohttp.ClientSession() as cs:
    async with cs.get(f"https://ev.io/stats-by-un/{username}") as r:
        response = await r.json()
        await ctx.send(f"{username} has {response["kills"]} kills in total.)

推荐阅读