Python如何获取非JSON格式API输出?Discord host命令修复咨询
问题修复说明
错误根源
- 你调用的域名转IP接口返回的是无标准JSON结构的纯文本内容,直接调用仅能解析合规JSON响应的
response.json()方法,会直接触发JSON解析报错。 - 当前异步命令中使用同步
requests库会阻塞Discord Bot的事件循环,可能导致机器人响应卡顿、完全无响应。 - Embed标题拼接域名时未加空格,会出现
IP for websitegoogle.com这类文字粘连的显示问题。
处理逻辑
对于非JSON格式的普通文本类API响应,无需做JSON解析,直接读取响应对象的
text属性即可拿到返回的纯文本内容。
异步命令需搭配异步HTTP请求库使用,避免阻塞事件循环影响Bot整体运行。
推荐修复版本(适配异步逻辑)
需先安装异步依赖aiohttp,执行pip install aiohttp即可安装,完整修复代码如下:
import discord from discord.ext import commands import aiohttp # 省略你原有客户端初始化的相关代码 @client.command() async def host(ctx, host): url = f'https://api.apithis.net/host2ip.php?hostname={host}' try: # 异步发起请求,不会阻塞事件循环 async with aiohttp.ClientSession() as session: async with session.get(url, timeout=10) as response: # 直接读取纯文本响应,不需要JSON解析 ipaddress = (await response.text()).strip() # 处理无效域名、接口返回空内容的异常场景 if not ipaddress: await ctx.send("未获取到对应IP,请检查域名格式是否正确") return # 修正标题的空格拼接问题 embed = discord.Embed(title=f"IP for website {host}", color=0x00ffff) embed.add_field(name="IP:", value=ipaddress, inline=True) await ctx.send(embed=embed) except Exception: await ctx.send("请求失败,请稍后重试")
临时快速修复版本(最小改动)
如果暂时不想更换请求库,可先按以下代码改动解决报错,注意该版本仍存在同步请求阻塞事件循环的问题,仅适合临时测试使用,正式上线建议使用上述异步版本:
@client.command() async def host(ctx, host): url = f'https://api.apithis.net/host2ip.php?hostname={host}' try: response = requests.get(url, timeout=10) # 替换原有的response.json()为response.text,直接获取纯文本 ipaddress = response.text.strip() embed = discord.Embed(title=f"IP for website {host}", color=0x00ffff) embed.add_field(name="IP:", value=ipaddress, inline=True) await ctx.send(embed=embed) except Exception: await ctx.send("请求失败,请检查域名是否输入正确")
内容的提问来源于stack exchange,提问作者3301
相关产品推荐
相关产品推荐

