Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
No puedo entender qué estoy haciendo mal con esta expresión regular, se supone que coincide con todo entre id":" y "

Estoy tratando de hacer coincidir el "83eec6e44ea04dee9103e845ad51c4f0" de este json, pero recibo un error (que se muestra a continuación). Obtuve el json de una solicitud httpget por cierto. Al leer el error yo mismo, parece que tiene algo que ver con el httpget, pero estoy obteniendo los datos de la solicitud sin problemas.

 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) } })

Error:

 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: [] } }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

El body contiene JSON, y si desea extraer la identificación, simplemente use

const match = JSON.parse(body).id

about 4 years ago · Juan Pablo Isaza Report

0

Te sugiero que analices tu JSON. Es más simple y probablemente más rápido para JSON más complejos.

 if (!error && response.statusCode == 200) { let { id } = JSON.parse(body); message.channel.send(id); }

Si necesita usar expresiones regulares, debe saber que .match(regex) devuelve una matriz, por lo tanto, solo debe elegir el primer elemento:

 matches = body.match(regex); // Don't name it match... It's an array :) message.channel.send(matches[0]);

¡Pero se puede usar un código mucho más eficaz! Puede secuenciar el texto antes de la clave de identificación (conocemos la clave de nombre == nombre de usuario) y .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); }

Si desea usar la identificación fuera de la devolución de llamada de la request , debe envolver todo en una promesa y una función dedicada:

 const request = require('request'); function get_username_id(username) { return new Promise((resolve, reject) => request( `https://api.mojang.com/users/profiles/minecraft/${username}`, function(error, response, body) { if (error || response.statusCode != 200) reject(error || response.statusCode) // body is {"name":"uhWillem","id":"83eec6e44ea04dee9103e845ad51c4f0"}; resolve(JSON.response(body)); }); } let username = message.content; get_username_id(username) .then(({name, id}) => { console.log(`The id of ${name} is ${id}`); // here we should see the name == username and the id // here we work with the data, eg we send it message.channel.send(id); // you can return a promise that resolves to something else and chain it with an other .then() return Promise.resolve('This will be recived after the first promise'); }) .then(text => { console.log(text); // id and name are not accessible anymore, but you can pass them on... }) .catch(err => console.error(err)); // here we print the error or status code different from 200

Este es bastante más largo y complejo pero permite ser más flexible en el desarrollo para el futuro.

Le sugiero que eche un vistazo, para encontrar más información sobre las promesas.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!