Search code examples
authenticationdiscorddiscord.jsbotssingleton

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


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?


Solution

  • 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.