【问题标题】:Confused with discordjs + twitter api对 discordjs + twitter api 感到困惑
【发布时间】:2021-07-27 02:03:34
【问题描述】:

直截了当地说,我从来没有这么困惑过...这个命令被设计得简单易行,正是直到这个问题。

当在 discord ex 上获取一个名字时,它工作得很好,但是当它遇到像我这样较长的 id 时,它只会在最后抛出 3 个随机数

例如:我的实际推特 ID (1054084643346137089) |我的机器人显示的内容 (1054084643346137100)

如您所见,它只是为最后 3 个抛出随机数

您可以在 https://tweeterid.com/ 上自行测试

代码-

const Discord = require("discord.js");
const request = require("node-superfetch");
const { stripIndents } = require("common-tags");
const bearer =
  ""; // empty only for this

module.exports = {
  name: "twit",
  aliases: ["twitter", "twitid"],
  description: "This command allows admins to grab twitter user ids.",
  /**
   * @param {Client} client
   * @param {Message} message
   * @param {String[]} args
   */
  run: async (client, message, args) => {
    const username = args[0];
    if (!username)
      return message.channel.send("You must provide a username to search for.");

    try {
      const { body } = await request
        .get("https://api.twitter.com/1.1/users/show.json")
        .set({ Authorization: `Bearer ${bearer}` })
        .query({ screen_name: username });

      message.channel.send(
        `Twitter ID For ${username}: http://www.twitter.com/I/user/${body.id}`
      );
    } catch (error) {
      if (error.status === 403)
        return message.channel.send(
          "This user either went private or deactivated their account."
        );
      else if (error.status === 404)
        return message.channel.send("Couldn't find this user.");
      else return message.channel.send(`Unknown Error: ${error.message}`);
    }
  },
};

【问题讨论】:

  • 您有什么问题吗?
  • 请不要在外部网站上托管您的代码,而是编辑您的问题以将您的代码包含为Minimal, Reproducible Example。外部链接往往会改变/破坏您问题的未来访问者的价值。
  • 更重要的是,听起来您的代码在某种程度上将此标识符转换为其整数表示形式,并且您遇到了精度问题,因为结果整数超过了MAX_SAFE_INTEGER。不要将其转换为代码中任何位置的int,并将其保留为字符串
  • 我该怎么做呢?大多数标准 ID 现在超过 16 个字符
  • 使用字符串而不是数字来存储ID

标签: node.js twitter discord discord.js


【解决方案1】:

问题在于 Twitter 使用带符号的 64 位整数来存储用户 ID。这个数字大于 53 位 (MAX_SAFE_INTEGER),JavaScript 难以解释它。它只能安全​​地表示 -(253 - 1) 和 253 - 1 之间的整数。

幸运的是,Twitter 的user object 还提供了作为id_str 的唯一标识符的字符串表示。正如文档提到的那样; “实现应该使用 this 而不是 id 中可能无法使用的大整数”

所以你需要做的就是使用id_str 而不是id

const body = {
  id: 1054084643346137089,
  id_str: '1054084643346137089'
}

console.log(`Twitter ID: http://www.twitter.com/I/user/${body.id}`)
console.log(`Twitter ID: http://www.twitter.com/I/user/${body.id_str}`)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    • 2019-09-13
    • 2012-07-22
    • 2013-05-13
    • 2020-04-16
    相关资源
    最近更新 更多