discord.js机器人似乎仅在本地主机上运行,否则会离线。

huangapple go评论80阅读模式
英文:

discord.js bot only seems to work with localhost and goes offline otherwise

问题

我使用 discord.js 版本 14.11.0。目标是在我的网站上有一个按钮,当点击时,让我的机器人发送直接消息给一个用户。这是按钮的点击处理程序:

const discordClient = new Client({ intents: [GatewayIntentBits.Guilds] })
discordClient.login(MY_BOT_TOKEN)

const discordUser = await discordClient.users.fetch('1234567890')
discordUser.send({ content: 'hello world', files: [{ attachment: 'image.png' }] })

每当我在本地版本上点击按钮时,消息几乎立即发送给了 Discord 用户。我在 Vercel 上托管了一个暂存站点。第一次我点击按钮时,消息发送了(尽管有 10 秒的延迟)。之后再次点击按钮,消息就再也发送不出去了。我还注意到我的 Discord 机器人现在下线了。如果我从本地版本点击按钮,它每次都能正常工作,机器人似乎也重新上线了。但是在我的暂存站点上使用时,它永远不会发送消息,并且机器人会重新下线。

我需要让 Discord 客户端使用单例模式,并在我的站点首次加载时实例化和登录吗?然后按钮点击只调用 .send() 方法?

英文:

I'm using discord.js version 14.11.0. The goal is to have a button on my site, when clicked, to have my bot send a direct message to a user. This is the button click handler:

const discordClient = new Client({ intents: [GatewayIntentBits.Guilds] })
discordClient.login(MY_BOT_TOKEN)

const discordUser = await discordClient.users.fetch('1234567890')
discordUser.send({ content: 'hello world', files: [{ attachment: 'image.png' }] })

Anytime I click the button on my localhost version, the message gets sent to the discord user pretty much instantly. I have a staging site hosted with Vercel. The first time I clicked the button, the message got sent (although with a 10 second delay). Clicking the button anytime after and the message never gets sent. I also see that my discord bot is offline now. If I click the button from my localhost version, it works every time and the bot appears to be back online. But then using my staging site it never sends and the bot goes back offline.

Do I need to have the discord client use a singleton pattern and instantiate and login only once when my site first loads? And then the button click only calls the .send() method?

答案1

得分: 0

如果我是你,我会尝试使用Discord REST API 来完成这个任务。你只需要调用两个端点:

如果你能避免创建完整的Discord.js客户端实例,将会更加轻便且容易调试。

英文:

If I were you, I would try to use the Discord REST API for this. You only have two endpoints to call:

If you can avoid creating a complete Discord.js client instance, it will be much lighter and easier to debug.

huangapple
  • 本文由 发表于 2023年7月17日 22:09:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76705283.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定