python - 如何获取/请求 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")
解决方案
首先,您需要请求您需要 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.)
推荐阅读
- xamarin.forms - 带有 BODYHTML 的 Xamarin EmailMessage 不起作用
- java - onRequestPermissions 中的某些用户发生 ArrayIndexOutOfBoundsException
- java - 升级到 targetSdkVersion 30,努力实现范围存储
- python - 内部带有 QPushbutton 的 QTableWidget:按钮不会消失
- r - 在“rugarch”预测中选择日期 R
- xamarin.forms - Windows 上的 iOS 远程模拟器
- javascript - 从 JS 文件生成 Typescript 声明时从用法推断参数类型
- c - 我正在尝试按升序在我的列表中添加整数!!有什么帮助吗?
- php - Laravel 带控制器的路由白页
- c -
C 代码中关于 malloc/free 的致命错误