这是我第一次创建 Discord 机器人,我正在尝试从 chess.com API 中提取数据。当您在 Discord 频道中输入 !chessresult user 时,如果用户赢得了上一场 chess.com 游戏,我希望机器人返回。我知道我的机器人已连接,因为我可以让机器人回复文本,但我很难让它提取数据。任何帮助,将不胜感激。谢谢!
import discord
import requests
from discord.ext import commands
PREFIX = '!'
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=PREFIX, intents=intents)
@bot.event
async def on_ready():
print('We have logged in as {0.user}'.format(bot))
@bot.event
async def on_message(message):
if message.content == "hello":
await message.channel.send('hello')
@bot.command()
async def chessresult(ctx, username: str):
try:
# Fetch the recent games of the user from the Chess.com API
response = requests.get(f'https://api.chess.com/pub/player/{username}/games/archives')
response.raise_for_status() # Raise an error for bad responses
archives = response.json()['archives']
if not archives:
await ctx.send(f"No games found for user {username}")
return
# Use the most recent archive to get the games
last_month_url = archives[-1]
games_response = requests.get(f"{last_month_url}/pgn")
games_response.raise_for_status()
# Extract games from the PGN
games = games_response.text.split("\n\n\n")
# Extract the result of the most recent game
last_game = games[-2] # The last item is empty, so take the second last
result_line = [line for line in last_game.split("\n") if "Result" in line][0]
result = result_line.split('"')[1]
await ctx.send(f"Last game result for {username}: {result}")
except requests.RequestException as e:
await ctx.send(f"Error fetching data for {username}: {str(e)}")
bot.run('KEY')
我尝试了各种方法,但还没有走得太远。这是我第一次编写机器人程序。
您可以解析 json 响应,而不是在第二个请求中从国际象棋 API 请求 PGN 文件:
with requests.Session() as sess:
# get the archives
resp = sess.get(
f'https://api.chess.com/pub/player/{username}/games/archives')
resp.raise_for_status()
last_game = resp.json().get('archives', [False])[-1]
if not last_game:
#error
# get the last month
resp = sess.get(f"{last_month_url}")
resp.raise_for_status()
game = resp.json().get('games', [{}])[-1].get('pgn')
if not game:
#error
# now session is closed
await ctx.send(game)
长话短说,我无法重现您的错误。看起来 chess.com API 不需要密钥或身份验证,所以事实并非如此。您可以添加日志语句,并确保您不会在其他地方遇到被您的 try/ except 语句之一吞没的错误。