[英]How can I beautify Json output in a discord.py bot message
首先,我是新來的(第一篇文章)和 python 的新人
我正在編寫一個 discord 機器人,它調用 API,它為我的游戲服務器獲取 http 請求。 API output 正在打印縮進,一切都很好,但是 discord 機器人消息都像這樣搞砸了。 我該如何解決?
此外,我無法訪問單獨的行以打印出像“name”或“maxplayers”
這是用於請求和格式化 json 的 api 代碼:
import requests
import json
url = "https://vrising-server-scanner.p.rapidapi.com/179.155.101.206/27016"
headers = {
"X-RapidAPI-Key": "03ceea7e11mshe52b1b49827f626p17aa4djsnb92582243b8e",
"X-RapidAPI-Host": "vrising-server-scanner.p.rapidapi.com"
}
response = requests.get(url, headers=headers)
data = response.json()
json_formatted = json.dumps(data, indent=4)
print(json_formatted)
我的 discord 代碼從 API 發送 output:
@client.command()
async def status(ctx):
await ctx.send('Checking status...')
await asyncio.sleep(1)
await ctx.send('Status:')
await asyncio.sleep(0.1)
await ctx.send('```')
await asyncio.sleep(0.1)
await ctx.send(subprocess.check_output(['python', 'VrisingAPI.py']))
await asyncio.sleep(0.1)
await ctx.send('```')
client.run(TOKEN)
由於您沒有為check_output()
定義任何特殊編碼,因此默認情況下它將始終返回bytes
object。 在您的情況下,您可以使用UTF-8
作為編碼:
subprocess.check_output(['python', 'VrisingAPI.py'], encoding='UTF-8')
另一種可能的解決方案是使用bytes.decode()
手動解碼:
subprocess.check_output(['python', 'VrisingAPI.py']).decode("utf-8")
如果您使用 Python 3.7 或更高版本,您還可以將參數text
設置為True
,這將使用系統的默認編碼對其進行解碼:
subprocess.check_output(['python', 'VrisingAPI.py'], text=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.