【问题标题】:How can I get user directly from discord API?How can I get user directly from discord API?
【发布时间】:2022-12-26 19:18:52
【问题描述】:

I've been looking around for code that works like this one:

const fetchUser = async id => {
    const response = await fetch('https://discord.com/api/v9/users/(USER ID)', {
        headers: {
            'Authorization': 'Bot ' + (BOT TOKEN)
        }
    })
    return JSON.parse(await response.json())
}
console.log(fetchUser())

I'm trying to get something like this:

{
  "id": "000000000000000001",
  "username": "8",
  "avatar": null,
  "discriminator": "0001",
  "public_flags": 0,
  "banner": null,
  "banner_color": null,
  "accent_color": null
}

This is the error/log I get

Promise { <pending> }
undefined:1
[object Object]
 ^

SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at fetchUser (C:\Users\Dev03\Desktop\uri\main.js:12:21)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

【问题讨论】:

    标签: discord discord.js fetch-api


    【解决方案1】:

    const fetchUser = async id => {
        const response = await fetch('https://discord.com/api/v9/users/(USER ID)', {
            headers: {
                'Authorization': 'Bot ' + (BOT TOKEN)
            }
        })
        return JSON.stringify(await response.json(), null, 4)
    }
    
    fetchUser().then(console.log)

    You should use JSON.stringify() instead of JSON.parse() in this scenario, it will return Promise&lt;pending&gt; that could been logged with .then().

    【讨论】:

      【解决方案2】:

      You could try this code

      const fetch = require('node-fetch')
      const fetchUser = async userid => {
        const response = await fetch(`https://discord.com/api/v9/users/${userid}`, {
          headers: {
            Authorization: 'Bot' + token
          }
        })
        return JSON.parse(await response.json())
      }
      console.log(fetchUser(id))
      

      【讨论】:

      • It gave me the same error.
      【解决方案3】:

      Yoy can try this one.

      let { data } = await get("https://discordapp.com/api/v9/users/userid", { headers: { "Authorization": "Bot " + client.token, "Content-Type": "application/json" } });
      
      

      Make sure you are using async while using await

      【讨论】:

        猜你喜欢
        • 2022-11-20
        • 2022-12-27
        • 2022-12-01
        • 2022-12-27
        • 2022-12-19
        • 2022-12-27
        • 2022-12-28
        • 2022-12-02
        • 2023-01-06
        相关资源
        最近更新 更多