我正在嘗試匹配此 json 中的“83eec6e44ea04dee9103e845ad51c4f0”,但出現錯誤(如下所示)。順便說一句,我從 httpget 請求中獲得了 json。從我自己閱讀錯誤來看,它似乎與 httpget 有關,但我從請求中獲取資料就好了。
username = message.content;
var request = require('request');
request(`https://api.mojang.com/users/profiles/minecraft/${username}`, function(error, response, body) {
if (!error && response.statusCode == 200) {
// body is this: body = {"name":"uhWillem","id":"83eec6e44ea04dee9103e845ad51c4f0"};
console.log(body)
message.channel.send(body);
regex = "(?<=id\":\")(.*)(?=\")";
match = body.match(regex);
message.channel.send(match)
}
})
錯誤:
C:\Users\wille\OneDrive\Bureaublad\discordBot\node_modules\discord.js\src\rest\RequestHandler.js:298
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (C:\Users\wille\OneDrive\Bureaublad\discordBot\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (C:\Users\wille\OneDrive\Bureaublad\discordBot\node_modules\discord.js\src\rest\RequestHandler.js:50:14)
at async TextChannel.send (C:\Users\wille\OneDrive\Bureaublad\discordBot\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:172:15) {
method: 'post',
path: '/channels/883457777035534417/messages',
code: 50006,
httpStatus: 400,
requestData: {
json: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
},
files: []
}
}
uj5u.com熱心網友回復:
在body包含JSON,如果你想提取的ID,只是使用
const match = JSON.parse(body).id
uj5u.com熱心網友回復:
我建議你決議你的 JSON。對于更復雜的 JSON,它更簡單,可能更快。
if (!error && response.statusCode == 200) {
let { id } = JSON.parse(body);
message.channel.send(id);
}
如果你需要使用正則運算式,你需要知道.match(regex)回傳一個陣列,因此你應該只選擇第一個元素:
matches = body.match(regex); // Don't name it match... It's an array :)
message.channel.send(matches[0]);
但是可以使用性能更高的代碼!您可以將 id 鍵之前的文本字串化(我們知道名稱鍵 == 用戶名)和.substring():
if (!error && response.statusCode == 200) {
let pre = `{"name":"${username}","id":"`;
// id is 32 characters long (16 bytes)
let id = body.substring(pre.length, pre.length 32);
message.channel.send(id);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/323699.html
標籤:javascript 不和谐.js
