Sending attachments in embed field - discord

I'm working with discord.js and I was trying to get my bot to send attachments in an embed field. I've tried this but it didn't work:
message.channel.send({embed: {
files: [ "images/twitter.png" ]
}});
I tried this too, it also didn't work:
message.channel.send({embed: {}, files: [ "images/twitter.png" ]}});
Any help would be greatly appreciated!

This similar post may help. Sending an attachment takes 2 steps.
Add the attachment to your message:
files: [{ attachment: 'images/twitter.png', name: 'twitter.png' }]
Then add the attachment to your embed:
image: { url: "attachment://twitter.png" }
Full example:
message.channel.send({
embed: {
description: "This is some text",
image: {
url: "attachment://twitter.png"
}
},
files: [{
attachment: 'images/twitter.png',
name: 'twitter.png'
}]
});

My best guess is at the bottom of a guide that I saw.
It should be like this:
.setThumbnail("http://i.imgur.com/p2qNFag.png")
Hope this works for what you need to do.

Related

discord.js v14 create channel

I try to create a channel but i always have an error.
I don't find how to fix it.
Don't pay attention to the "req[0]." in "code" it comes from the database, no link with the problem because it works in v13
"It looks like your post is mostly code; please add some more details." I don't know what can I have for more details. haha.
Sorry, English is not my native langage.
error :
throw new DiscordAPIError.DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
^
DiscordAPIError[50035]: Invalid Form Body
name[BASE_TYPE_REQUIRED]: This field is required
at SequentialHandler.runRequest (/root/project/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.cjs:293:15)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async SequentialHandler.queueRequest (/root/project/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.cjs:99:14)
at async REST.request (/root/project/node_modules/#discordjs/rest/dist/lib/REST.cjs:52:22)
at async GuildChannelManager.create (/root/new ascension/node_modules/discord.js/src/managers/GuildChannelManager.js:145:18) {
rawError: {
code: 50035,
errors: {
name: {
_errors: [
{
code: 'BASE_TYPE_REQUIRED',
message: 'This field is required'
}
]
}
},
message: 'Invalid Form Body'
},
code: 50035,
status: 400,
method: 'POST',
url: 'https://discord.com/api/v10/guilds/873350117124628552/channels',
requestBody: {
files: undefined,
json: {
name: undefined,
topic: undefined,
type: undefined,
nsfw: undefined,
bitrate: undefined,
user_limit: undefined,
parent_id: undefined,
position: undefined,
permission_overwrites: undefined,
rate_limit_per_user: undefined,
rtc_region: undefined,
video_quality_mode: undefined
}
}
}
Node.js v18.3.0
code :
action.guild.channels.create(`hello`, {
type: "GUILD_TEXT",
parent: cat[0].ID,
permissionOverwrites: [
{
id: bot.user.id,
allow: ['VIEW_CHANNEL', "MANAGE_CHANNELS"]
},
{
id: action.user.id,
allow: ["VIEW_CHANNEL"]
},
{
id: req[0].ID,
deny: ["VIEW_CHANNEL"]
},
{
id: staff[0].ID,
allow: ["VIEW_CHANNEL"]
}
]
})
You can't set the type of the channel using a string anymore, you have to use the new ChannelType enum. You can import it from the discord.js library, and once you've done that, creating a channel would look something like this:
guild.channels.create({
name: "hello",
type: ChannelType.GuildText,
parent: cat[0].ID,
// your permission overwrites or other options here
});
Also make sure that all of your arguments are being passed in only one object, and the name isn't a separate argument.

Discord.js : "Supplied parameter is not a User nor a Role" while creating channel through button interaction

The bot was working fine while making this. The error started popping from last week.
I don't understand what's wrong as I have also tried the same code on another bot and it creates channel fine.
I thought maybe it had to do with discord making the 19 character snowflake but that's not the case.
Here is the index.js file (I have a omitted few things)
ID is the member username who clicked the button.
staff1, staff2, everyone roles are defined above. [ const staff1 = "role-id"; etc ]
verifyParent is the ID of the category under which the channel is created. [ Defined above ]
switch (customId) {
case 'VERIFY':
await interaction.guild.channels.create(`${customId + "-" + ID}`, {
type: "GUILD_TEXT",
parent: verifyParent,
permissionOverwrites: [
{
id: interaction.member.id,
allow: [ "SEND_MESSAGES", "VIEW_CHANNEL", "READ_MESSAGE_HISTORY" ]
},
{
id: staff1,
allow: [ "SEND_MESSAGES", "VIEW_CHANNEL", "READ_MESSAGE_HISTORY" ]
},
{
id: staff2,
allow: [ "SEND_MESSAGES", "VIEW_CHANNEL", "READ_MESSAGE_HISTORY" ]
},
{
id: everyone,
deny: [ "SEND_MESSAGES", "VIEW_CHANNEL", "READ_MESSAGE_HISTORY" ]
}
]
})
.then(async(channel) => {
channel.send(`${ID} Please send the details.`);
})
.catch(console.log);
}
The error I got:
TypeError [INVALID_TYPE]: Supplied parameter is not a User nor a Role.
at PermissionOverwrites.resolve (/home/runner/cum-bot/node_modules/discord.js/src/structures/PermissionOverwrites.js:184:28)
at /home/runner/cum-bot/node_modules/discord.js/src/managers/GuildChannelManager.js:145:81
at Array.map (<anonymous>)
at GuildChannelManager.create (/home/runner/cum-bot/node_modules/discord.js/src/managers/GuildChannelManager.js:145:51)
at Client.<anonymous> (/home/runner/cum-bot/index.js:120:48)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
[Symbol(code)]: 'INVALID_TYPE'
}
I have looked at other posts and nothing works. I have tried to reset the bot token and still the same thing.
The same code is working fine on a test bot of mine but not with this one.
And no, the bot is not rate limited.
Thanks!
I believe interaction.member.id is the person who sent the interaction itself. if you are trying to get the person that pressed the button, i believe it is:
{
id: interaction.user.id,
allow: [ "SEND_MESSAGES", "VIEW_CHANNEL", "READ_MESSAGE_HISTORY" ]
}

Unable to add code blocks in Sanity CMS after I install the code-input plugin

I am learning to build a blog using Sanity CMS and React. I am new to Sanity.
I should be able to insert code snippets in my blog posts. So, I have installed the code-input plugin.
According to the link here, after I install the plugin I have to use the following code in my schema types.
I have no idea where do I insert the code.
Please help.
My folder structure is as follows:
sanityblog/blockContent.js
/**
* This is the schema definition for the rich text fields used for
* for this blog studio. When you import it in schemas.js it can be
* reused in other parts of the studio with:
* {
* name: 'someName',
* title: 'Some title',
* type: 'blockContent'
* }
*/
export default {
title: "Block Content",
name: "blockContent",
type: "array",
of: [
{
title: "Block",
type: "block",
// Styles let you set what your user can mark up blocks with. These
// correspond with HTML tags, but you can set any title or value
// you want and decide how you want to deal with it where you want to
// use your content.
styles: [
{ title: "Normal", value: "normal" },
{ title: "H1", value: "h1" },
{ title: "H2", value: "h2" },
{ title: "H3", value: "h3" },
{ title: "H4", value: "h4" },
{ title: "Quote", value: "blockquote" },
],
lists: [{ title: "Bullet", value: "bullet" }],
// Marks let you mark up inline text in the block editor.
marks: {
// Decorators usually describe a single property – e.g. a typographic
// preference or highlighting by editors.
decorators: [
{ title: "Strong", value: "strong" },
{ title: "Emphasis", value: "em" },
],
// Annotations can be any object structure – e.g. a link or a footnote.
annotations: [
{
title: "URL",
name: "link",
type: "object",
fields: [
{
title: "URL",
name: "href",
type: "url",
},
],
},
],
},
},
// You can add additional types here. Note that you can't use
// primitive types such as 'string' and 'number' in the same array
// as a block type.
{
type: "image",
options: { hotspot: true },
},
],
};
sanityblog/schema.js
// First, we must import the schema creator
import createSchema from "part:#sanity/base/schema-creator";
// Then import schema types from any plugins that might expose them
import schemaTypes from "all:part:#sanity/base/schema-type";
// We import object and document schemas
import blockContent from "./blockContent";
import category from "./category";
import post from "./post";
import author from "./author";
// Then we give our schema to the builder and provide the result to Sanity
export default createSchema({
// We name our schema
name: "default",
// Then proceed to concatenate our document type
// to the ones provided by any plugins that are installed
types: schemaTypes.concat([
// The following are document types which will appear
// in the studio.
post,
author,
category,
// When added to this list, object types can be used as
// { type: 'typename' } in other document schemas
blockContent,
]),
});
If you installed the plugin correctly, it's now available as a schema type to be used in any of your other schemas. So, to answer your question, you can put that code anywhere you want code blocks in your Sanity studio. I'd strongly suggest going over the content modelling documentation 😉
Specifically to your question, assuming you use the sanityBlog/blockContent.js field for the content of your posts, you can add it there. Here's how that would look like:
export default {
title: "Block Content",
name: "blockContent",
type: "array",
of: [
{
title: "Block",
type: "block",
// ...annotations, styles, lists and marks you already have
},
{
type: "image",
options: { hotspot: true },
},
// Add the code block here 👇
// it'll show up as one of the blocks available in your
// Portable Text Editor
{
type: "code",
title: "Code block",
}
],
};
For specifics on the portable text / rich content field (type: "block"), refer to the block type documentation. If you want to take it one step back, refer to the general block content documentation.
Hope this helps 🙌

Mongoose instance .save() not working when embedded array object changed

I am using Mongoose npm module to manage mongodb.
This is schema of mongodb collection what I am going to update.
var UserSchema = new Schema({
username: {
type: String,
unique: true,
required: true
},
email: {
type: String,
unique: true,
required: true
},
cards: []
});
module.exports = mongoose.model('User', UserSchema);
inside post request, here req is request object of post request.
and res is response object.
User.findById(userID).exec(function (err, doc) {
let cardInfo = req.cardInfo
let cardIndex = req.cardIndex
doc["cards"][0] = cardInfo;
console.log(doc)
/* here I got right doc object as I requested
{
"_id": "59f3bdd488f912234fcf06ab",
"email": "test#gmail.com",
"username": "test",
"__v": 2,
"cards": [
{
"testNo": "42424242424242"
}
]
}
*/
doc.save(function (err) {
if (err) {
return res.json({
success: false,
msg: 'Card add error'
});
}
res.json({
success: true,
msg: 'Successful updated card.'
});
});
})
I got message 'Successful updated card.', but actually, It doesn't save.
How to solve it. Thanks.
The problem is that mongoose don't knwo your array is modified.
You can use 2 solutions :
markModified
This function will mark the embedded element as modified and force a resave of it.
It will tell mongoose to resave this element.
User.findById(userID).exec(function (err, doc) {
let cardInfo = req.cardInfo
let cardIndex = req.cardIndex
doc["cards"][0] = cardInfo;
console.log(doc)
/* here I got right doc object as I requested
{
"_id": "59f3bdd488f912234fcf06ab",
"email": "test#gmail.com",
"username": "test",
"__v": 2,
"cards": [
{
"testNo": "42424242424242"
}
]
}
*/
doc.markModified('cards');
doc.save(function (err) {
if (err) {
return res.json({
success: false,
msg: 'Card add error'
});
}
res.json({
success: true,
msg: 'Successful updated card.'
});
});
})
Use a full schema.
To avoid the markModified trick, you should describe the content of cards in your schema. This way mongoose will be able to determine if it needs to save the field or not.
Here is the way to declare your schema properly :
const CardSchema = new Schema({
testNo: String,
});
var UserSchema = new Schema({
username: {
type: String,
unique: true,
required: true
},
email: {
type: String,
unique: true,
required: true
},
cards: [CardSchema]
});
module.exports = mongoose.model('User', UserSchema);
This way, mongoose will be able to detect if a value inside cards changed and save only the modified item.
If you can do it (static schema), this is clearly the good way to do it.
If you just want to update cards based on cardIndex:
User.update({_id: userID}, {'$set': {
'cards.cardIndex': cardInfo
}}, function(err) {
//code
}
Thanks for all answers.
I find this solution in addition.
doc["cards"].set(cardIndex, cardInfo)
Cheers!

How to create sap.m.ComboBox without the strange 'is not a function' error?

I've been playing around with SapUI5 for a while and now I'm facing another issue, which is totally confusing me.
My goal: To add a ComboBox to an oTable.
What I tried: I decided to do the 'separation of concerns', in order to investigate it better, so I 'extracted' the ComboBox code from the table and am testing it on its own like this:
var cbWizardTypes = [
{
Code: "0",
Name: "Name0",
AdditionalText: "Additional0"
},
{
Code: "1",
Name: "Name1",
AdditionalText: "Additional1"
},
{
Code: "2",
Name: "Name2",
AdditionalText: "Additional2"
},
];
// now the template to use when showing the items
var cbWizardTypesTemplate = new sap.ui.core.ListItem({
key: "{Code}",
text: "{Name}",
additionalText: "{AdditionalText}"
});
// now let's create it and place it
var cbWizardType = new sap.m.ComboBox({
items: {
path: cbWizardTypes,
template: cbWizardTypesTemplate
},
showSecondaryValues: true
});
cbWizardType.placeAt(containerID, 'only');
Now, this is giving me this error in the console:
Additionally, I tried not to use a template, just to see what happens
var cbWizardType = new sap.m.ComboBox({
//items: {
// path: cbWizardTypes,
// template: cbWizardTypesTemplate
//},
items: cbWizardTypes,
showSecondaryValues: true
});
In this case, there are no errors in the Chrome Developer Tools - Console. I get a ComboBox with 3 items, but they are all blank.
Now, I will, at least, try to investigate further, although library-preload.js had been minified, so it will be really hard and time-consuming to navigate through all those 'd'-s, 'p'-s, 'j'-s, etc., I guess.
As always, I will appreciate any help. Thank you!
The problem lies with the binding path that you assign to the ComboBox. The binding should be a string & not an array. You will have to store the data in a model & bind it then to your control.
The code below should work
var cbWizardTypes = [
{
Code: "0",
Name: "Name0",
AdditionalText: "Additional0"
},
{
Code: "1",
Name: "Name1",
AdditionalText: "Additional1"
},
{
Code: "2",
Name: "Name2",
AdditionalText: "Additional2"
},
];
var oModel = new sap.ui.model.json.JSONModel({ items: cbWizardTypes});
// now the template to use when showing the items
var cbWizardTypesTemplate = new sap.ui.core.ListItem({
key: "{Code}",
text: "{Name}",
additionalText: "{AdditionalText}"
});
// now let's create it and place it
var cbWizardType = new sap.m.ComboBox({
items: {
path: "/items",
template: cbWizardTypesTemplate
},
showSecondaryValues: true
});
cbWizardType.setModel(oModel);
cbWizardType.placeAt(containerID, 'only');

Resources