Using json online - javascript

Heyo!
So, I'm trying to make something like https://aws.random.cat/meow however, when using my code with a discord bot, it isn't working.. It makes me wonder if you can host json things online directly by using the below code:
document.body.innerHTML = "<pre style=\"word-wrap: break-word; white-space: pre-wrap;\">{\"file\":\"https:\\/\\/"+domain+"\\/images\\/hug\\/"+item+"\"}</pre>";
Furthermore, my bot code is:
const { MessageEmbed } = require('discord.js');
const axios = require('axios');
const {get} = require("snekfetch");
const embed = new MessageEmbed()
.setColor("RANDOM")
.setTitle("thingie")
.setDescription("Loading...")
message.channel.send(embed).then(msg => {
get('https://example.com/kiss').then(response => {
setTimeout(function(){
embed.setDescription("")
embed.setImage(response.body.file)
msg.edit(embed)
}, 1500);
});
})
My website is working perfectly and is showing exactly as in https://aws.random.cat/meow However, it still doesn't work. Please lmk how or why this is happening.
P.S I didn't include the modules.export part in the bot code cuz, I thought it was extra.
P.P.S The following is my current output: This
Thanks!

If you want to provide data in a JSON format on your endpoint then just provide the JSON part, no need to put it in an HTML. If you put your JSON inside HTML like a string, then when you do get(<your url>) you'll get the entire HTML code with the embedded JSON, and so response.file doesn't work.
The reason why https://aws.random.cat/meow shows up as being embedded within HTML is because the browser detects that it is a JSON file and hence it does the embedding automatically. Here is the RAW response from that URL when you try to make the request using wget on the command line:
$ wget https://aws.random.cat/meow --no-check-certificate
$ cat meow
{"file":"https:\/\/purr.objects-us-east-1.dream.io\/i\/935392_10151612620866211_62628372_n.jpg"}
As you can see, there's no HTML around it. It's pure JSON.
To verify that this is indeed the case, log the response you get from your url:
get('https://example.com/kiss').then(response => {
console.log(response.body);
});
Unrelated: anyone else appreciate the cat meow coincidence here?

Related

JSON error in javascript when using websockets

I seem to be overlooking an error in my code that I just can't figure out. I have read multiple online sources showing what the error can be, but I can't find it in my code.
I am using WebSockets to communicate between my front and backend, when sending data in JSON format from my front to backend, it works perfectly, but not the other way around.
In my code snippets, I replaced my data with dummy values to make it easier to see the error.
Backend:
some_code.js
var msg = {"a": "a"};
Websocket.Send(msg);
websocket.js
Websocket.Send = (msg) =>
{
Websocket.Socket.clients.forEach(function each(client)
{
client.send(JSON.stringify(msg));
});
}
Frontend:
websocket.js
Socket.addEventListener("message", ({msg}) =>
{
console.log(JSON.parse(msg));
});
Error:
Any help will be appreciated, thanks!
Ok so changing the code of websocket.js to the following fixed it.
websocket.js
Socket.addEventListener("message", ({data}) =>
{
console.log(JSON.parse(data));
});
So it seems that the WebSocket library requires the variable name holding the received data to be named "data".

How to use an EmbedMessage From a Different File?

I'm having trouble with an embedmessage. I provided my code below of my index.js in which I'm trying to use a function made in "globalspeakfunction.js".
Don't worry about the variables I'm sending they look extra in this but I only provided the relevant code to hopefully reduce confusion.
I'm building up my EmbedMessage in GlobalSpeakFunction.js and then sending it in the channel of the message provided in "index.js".
However my console gives back "cannot send empty message" and when I do a console.log of the EmbedMessage it returns the embed perfectly?
I tried adding a string "test" after my embedmessage in the send() function and then it returned
[object Object]test
I have no idea what's going on here. Am I not able to buildup an EmbedMessage in a different file and then send it back to my bot? Or is there something I'm just overlooking?
index.js
const Discord = require('discord.js');
const client = new Discord.Client();
const speak = require('../GlobalSpeakFunction.js');
client.on('message', message => {
if (message.content.toUpperCase().includes(`test`)){
speak("778978295059972106", message, "test", "Default");
}
}
GlobalSpeakFunction.js
const Discord = require("discord.js")
module.exports = function speak(charID, data, message, emotion){
var EmbedMessage = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('title')
.setURL('https://discord.js.org/')
.setDescription(message)
.setThumbnail('https://drive.google.com/file/d/17J90PzTLBR96wTwk_Wl3U06-or6ZjPW2/view')
.setTimestamp();
message.channel.send(EmbedMessage);
}
I'm not sure where you experienced the 'Cannot send an empty message' error, I can't reproduce it locally. However, there are a few issues here:
Firstly, you're using toUpperCase() on message.content, and later checking whether it includes (lowercase) "test". Thus, this if statement will never execute.
Secondly, the order of arguments in the speak() function is charID, data, message, emotion, but you're passing them as "778978295059972106", message, "test", "Default" (notice how data and message are swapped when calling the function).
Thirdly, the setThumbnail() function expects a direct link to an image (one that ends with a file extension, like .png or .jpg). You're providing a Google Drive link, which is additionally set to private, which makes it unreadable for anyone but you. I'd recommend uploading it to an image host and getting the direct link from there.
Also, [object Object] is just a string representation of an object. JavaScript tries to convert your MessageEmbed (which is an object) to a string (because you're trying to append 'test' to it).

How to fix this 'Attachment is not a constructor' error with my bot?

When I made my bot for Discord and tried to attach an image, I can't because of this error
It's a bot for Discord that runs on Discord.js
I tried const Attachment on the beginning, but that didn't work, removed new and const in the code didn't work too
case 'about':
message.channel.send('I am Damabot, developed by Damadion!')
const attachment = new Attachment('./DidYouThinkIAmTheRealFace.png')
message.channel.send('I am Damabot, developed by Damadion!' + attachment)
console.log('Bot successfully replied')
break;
I expected it to send an attachment, but it didn't and sent this error
You can do it like this:
message.channel.send('I am Damabot, developed by Damadion!', { files: ['./DidYouThinkIAmTheRealFace.png'] });
It adds the file directly into the message, so you don't have to create Attachment. I use this my BOT, and it works just fine.
Attachment is a class within Discord.js. Unless you're using a destructuring assignment for your require statement (const { Attachment } = require('discord.js')), Node.js is trying to construct an Attachment object based on a class within your code. When it finds that there is none, it throws your error.
If you want to stick to constructing Attachment objects, you can use:
const attachment = new Discord.Attachment('./path/to/file.png', 'name'); // name is optional
message.channel.send('Hey there', attachment)
.catch(console.error);
Otherwise, you can use the files property of a message like so:
message.channel.send('Hey there', {
files: ['./path/to/file.png']
})
.catch(console.error);
The latter allows you to also send an embed (and maybe use the attachment in your embed).
Discord.js Docs
For me the following code worked:
const attachment = new Discord.MessageAttachment("url");
channel.send(attachment);
Discord.Attachment was replaced with Discord.MessageAttachement
I had the same problem. I ran npm install to update my packages and to check if my discord version was outdated and therefore causing any issues.
After that, I decided to go through the docs and found this snippet here:
const attachment=new Discord.MessageAttachment("enter the URL u wanna enter here")
const generalChannel=client.channels.cache.get("enter ur channel id here")
$generalChannel.send(attachment);
At least, it has worked for me. Please let me know if it works for you as well.

Parsing the text with React from server with Draft.js

I'm trying out Draft.js with my React application running with a GraphQL server. Currently I have a editor where I can type and add code blocks and submit it to the server. Here's the code for that:
const contentState = this.state.editorState.getCurrentContent()
const { content } = this.state.values
console.log('raw', convertToRaw(contentState))
let response;
try {
response = await this.props.mutate({
variables: {
content: JSON.stringify(contentState)
},
})
console.log(response)
response gives me
And that's no good. I rather have the convertToRaw(contentState) since that gives me:
The reason why I'm not doing convertToRaw(contentState) at mutate is because it gives me this error:
contentState.getBlockMap is not a function
So my questions are how can I use the convertToRaw function when submitting the text to the server and how can I later parse the text on the frontend so it wont look like this:
Thanks for reading my question. All help is appreciated!
Have a great day.

Discord make channel using bot

I'm making a discord bot, and I'm trying to make use of the createChannel function shown here in the documentation. For some reason, I am getting the following error:
TypeError: bot.createChannel is not a function.
My code is within a function which I pass a message to, and I have been able to create roles and add users to roles within the same function. It's just the createChannel function that's not working. Below is the relevant portions of the code.
const bot = new Discord.Client();
function makeChannel(message){
var server = message.guild;
var name = message.author.username;
server.createRole(data);
var newrole = server.roles.find("name", name);
message.author.addrole(newrole);
/* The above 3 lines all work perfectly */
bot.createChannel(server,name);
}
I have also tried bot.addChannel, and bot.ChannelCreate, since ChannelCreate.js is the name of the file which contains the code for this command. Also, I have attempted specifying channel type and assigning a callback function as well, but the main issue is the TypeError saying that this isn't a function at all. Any idea what I'm doing wrong?
Additionally, I plan to use ServerChannel.update() at some point in the future, so any advice on getting that to work once the previous problem is resolved would be greatly appreciated.
Alright, after a few days of trying things and going through the docs, I have discovered the solution. I am using a more recent version of Discord than the docs I was reading were written for. In the newer version, channels are created with a method in the server, not a client method. so, the code should be:
const bot = new Discord.Client();
function makeChannel(message){
var server = message.guild;
var name = message.author.username;
server.createChannel(name, "text");
}
The "text" value is the type of channel you are making. Can be text or voice.
I'll post a link to the most recent documentation for anyone else who encounters this problem here.
The answer should update documentation link to the GuildChannelManager which is now responsible for creating new channel.
(Example from docs)
// Create a new text channel
guild.channels.create('new-general', { reason: 'Needed a cool new channel' })
.then(console.log)
.catch(console.error);
https://discord.js.org/#/docs/main/stable/class/GuildChannelManager
#Jim Knee's I think your answer is v11, I'm new in discord.js, using Visual Studio Code's auto-code thingy. You can do all the same things except your thing must be this. If you are poor people, getting errors on doing #Jim Knee's answer, this is the place for "YOU!"
Get rid of server.createChannel(name, "text/voice");
And get it to THIS server.channels.create(name, "text/voice");
Hope I can help at least ;)
I'm just a new guy here too
I think you have not logged in with your bot.
From the docs:
const Discord = require('discord.js');
var client = new Discord.Client();
client.login('mybot#example.com', 'password', output); // you seem to be missing this
function output(error, token) {
if (error) {
console.log(`There was an error logging in: ${error}`);
return;
} else
console.log(`Logged in. Token: ${token}`);
}
Alternatively, you can also login with a token instead. See the docs for the example.

Categories