How to store latest discord message in json and send the data stored in json to roblox

const Discord = require("discord.js")

const client = new Discord.Client({ intents: [
  Discord.GatewayIntentBits.Guilds,
  Discord.GatewayIntentBits.GuildMessages
]})

const channelID = 'id';

client.on('message', message => {
  if (message.channel.id === channelID) {
    console.log(`${message.content}`);
  }
});

client.login("token");
{
    "message": "hi"
  }

i have little experience on java, but how would i achieve this?

1 Like

This question is not exactly an easy one to solve since most people don’t have a reason to do this, but:

You’d need to post the message content to an HTTP address (try github for instance) and listen for it in game with an httplistener. Unfortunately I only know how to do the inverse off the top of my head using noblox. But it will definitely involve Noblox.js! Check out the documentation for it.

how would i make the json file update when a message is sent in discord?

const fs = require('fs');
const fileName = './file.json';
const file = require(fileName);
    
file.key = "new value";
    
fs.writeFile(fileName, JSON.stringify(file), function writeJSON(err) {
  if (err) return console.log(err);
  console.log(JSON.stringify(file));
  console.log('writing to ' + fileName);
});

Credit: How to update a value in a json file and save it through node.js - Stack Overflow

It depends on how you want to host the file. Are you going to use a cloud provider or are you going to host it on your PC? I can’t tell you how to write to the file if I don’t know where the file is.

im going to use a cloud provider(github if that helps)

Are you going to write to the Github repository via the API or locally with git? If you’re doing it locally with Git then your computer has to be on for this to work, but I assume it’s on anyways if you’re running the Discord bot. The web API is ratelimited at 5000 requests an hour so if you’re going to be doing more than that, then you’ll need to use your own setup.

the request wont go over 5000 so its fine to use github repository

In order to use the web API you’ll have to authenticate yourself. First, you’ll need to go to github.com/settings/tokens and create a classic token for your account. Set the expiration date and make sure the “repo” checkbox is selected (this grants the API access to your repository). Click on generate token — and don’t share it anywhere. Copy it because you won’t see it again.

You’ll also need to create a Discord app by going to discord.com/developers. Then click on “bot” in the sidebar of the app and fill out the information. I don’t have much experience with Discord bots but I assume the permission to read messages is granted automatically. If it isn’t, then give it the appropriate permissions at the bottom of the page. Copy the token because you won’t see it again.

I’m going to assume you’re using discord.js with Node since that’s what you referenced earlier. If you’re using Python, you’ll have to modify it accordingly.

To do this, when a message is sent, the bot will grab the content and use the Github API to send a POST request to your repository. Your file will then contain the most recent message from the channel, and you’ll be able to access it using the raw.githubusercontent.com/username/repo/branch/path/to/message.json endpoint.

Again, I don’t have much experience with Discord, but here’s an example program. You’ll have to test it and modify to fit your needs:

const Discord = require('discord.js');
const fetch = require('node-fetch');
const fs = require('fs');

const client = new Discord.Client({
  intents: [
    Discord.Intents.FLAGS.GUILDS,
    Discord.Intents.FLAGS.GUILD_MESSAGES,
  ],
});

const channelID = '12345';
const githubToken = 'ghp_123aBc456';
const githubRepoOwner = 'username';
const githubRepoName = 'repo';
const filePathInRepo = 'path/to/message.json';
const discordBotToken = 'aBc123xYz';

client.on('ready', () => {
  console.log(`logged in as: ${client.user.tag}`);
});

client.on('messageCreate', async (message) => {
  if (message.channel.id === channelID) {
    const messageContent = message.content;

    try {
      const response = await fetch(
        `https://api.github.com/repos/${githubRepoOwner}/${githubRepoName}/contents/${filePathInRepo}`,
        {
          method: 'GET',
          headers: {
            Authorization: `Bearer ${githubToken}`,
          },
        }
      );

      if (response.status === 200) {
        const fileInfo = await response.json();
        const fileContent = JSON.parse(Buffer.from(fileInfo.content, 'base64').toString());
        fileContent.message = messageContent;

        const updatedContent = JSON.stringify(fileContent, null, 2);

        const updateResponse = await fetch(
          `https://api.github.com/repos/${githubRepoOwner}/${githubRepoName}/contents/${filePathInRepo}`,
          {
            method: 'PUT',
            headers: {
              Authorization: `Bearer ${githubToken}`,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              message: `New message`,
              content: Buffer.from(updatedContent).toString('base64'),
              sha: fileInfo.sha,
            }),
          }
        );

        if (updateResponse.status === 200) {
          console.log(`successfully updated message: "${messageContent}"`);
        } else {
          console.error('failed to update');
        }
      } else {
        console.error('failed to fetch');
      }
    } catch (error) {
      console.error('other error:', error);
    }
  }
});

client.login(discordBotToken);

I’ve only tested the Github API endpoints in the browser, and I haven’t tested the Discord bot at all. Feel free to reply if you get any errors and I can try to help you out.

Also, since you’re overwriting the file every message, you have to make at least 2 requests (one to delete the previous message, and one to add the new message). This means your request ratelimit will be cut in half (down to 2500/hour).

im sorry but how do i get the file path in my repository?

It’s just where the file is inside your repository. For example, if message.json is inside a folder called “example” the path would be example/message.json. If it’s not in any folders, the path would just be message.json.

i keep getting “failed to update” error in the console whenever i send a message in the channel

That means something’s wrong with the Github API. It’s usually because your token doesn’t have access to write to the repository. It could also be a problem with how the code overwrites a file. I tested it myself, and aside from a few Discord permission issues, everything worked fine.

I rewrote the code to fix the Discord errors and everything works perfectly fine. This is what I used:

index.cjs:

const Discord = require('discord.js');
const fetch = require('node-fetch');
const fs = require('fs');

const { Client, GatewayIntentBits, Partials } = require('discord.js');
const client = new Client({ 
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
  ],
  partials: [Partials.Channel]
});

const channelID = '12345';
const githubToken = 'ghp_12345';
const githubRepoOwner = 'username';
const githubRepoName = 'repo';
const filePathInRepo = 'message.json';
const discordBotToken = 'abc123';

client.on('ready', () => {
  console.log(`logged in as: ${client.user.tag}`);
});

client.on('messageCreate', async (message) => {
  if (message.channel.id === channelID) {
    console.log(message.content)
    const messageContent = message.content;

    try {
      const { default: fetch } = await import('node-fetch');

      const response = await fetch(
        `https://api.github.com/repos/${githubRepoOwner}/${githubRepoName}/contents/${filePathInRepo}`,
        {
          method: 'GET',
          headers: {
            Authorization: `Bearer ${githubToken}`,
          },
        }
      );

      if (response.status === 200) {
        const fileInfo = await response.json();
        const fileContent = JSON.parse(Buffer.from(fileInfo.content, 'base64').toString());
        fileContent.message = messageContent;

        const updatedContent = JSON.stringify(fileContent, null, 2);

        const updateResponse = await fetch(
          `https://api.github.com/repos/${githubRepoOwner}/${githubRepoName}/contents/${filePathInRepo}`,
          {
            method: 'PUT',
            headers: {
              Authorization: `Bearer ${githubToken}`,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              message: `New message`,
              content: Buffer.from(updatedContent).toString('base64'),
              sha: fileInfo.sha,
            }),
          }
        );

        if (updateResponse.status === 200) {
          console.log(`successfully updated message: "${messageContent}"`);
        } else {
          console.error('failed to update');
        }
      } else {
        console.error('failed to fetch');
      }
    } catch (error) {
      console.error('other error:', error);
    }
  }
});

client.login(discordBotToken);

package.json (dependency versions):

{
  "name": "example",
  "version": "1.0.0",
  "description": "",
  "main": "index.cjs",
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "discord.js": "^14.13.0",
    "node-fetch": "^2.6.1",
    "yarn": "^1.22.19"
  },
  "engines": {
    "node": "*"
  },
  "type": "module"
}

I assume that your error was unrelated, though. Make sure your Github token is still valid and has the appropriate permissions.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.