So I want to make it so that every time a new ticket is made it will add a number example: ticket-1 | ticket-2 | ticket-3, ect. And then I want the bot to send the channel in a chat
module.exports = {
data: {
name: `GT1`
},
async execute(interaction, client, message) {
const guild = client.guilds.cache.get("1057116059750117426");
const ticketId = Math.floor(Math.random() * 9000);
await guild.channels.create({
name: `TICKET-${ticketId}`,
parent: '1057370813357109308',
})
interaction.reply({ephemeral: true, content: `Your ticket has been submited \n You can view it here -> ${guild.channels.id}` });
}
}
What you need is a way to persist data after every command. This would require some sort of data storage. I've listed a few options below:
Use a database, (On the discord.js guide they recommend using an ORM)
Store the files in a JSON object on your file system.
Here is an example for 2:
module.exports = {
data: {
name: 'GT1',
},
async execute(interaction, client, message) {
const guild = client.guilds.cache.get('1057116059750117426');
const storageBuffer = fs.readFileSync('./storage.json'); // you will input your file path here.
const storageData = JSON.parse(storageBuffer.toString());
storageData.ticket_id++; // adds one to the ticket number?
const ticketId = storageData.ticket_id;
await guild.channels.create({
name: `TICKET-${ticketId}`,
parent: '1057370813357109308',
});
interaction.reply({
ephemeral: true,
content: `Your ticket has been submited \n You can view it here -> ${guild.channels.id}`,
});
fs.writeFileSync('./storage.json', JSON.stringify(storageData)); // updates the data to your storage file
},
};
You will need to create the json file before using it.
storage.json
{
ticket_id: 0
}
As for sending to a channel you can take a look at this: https://discord.js.org/#/docs/main/stable/class/Interaction?scrollTo=channel
Related
I need to write a nodejs api where I need to create and update a logo.
The create works fine, but while updating the logo with a given id, the previous logo should get deleted and update with the new logo. We can use fs.unlink to delete the logo; but while using fs.unlink, the code deleted the updated logo; how do I fix this?
If I somehow knew the previous logo's name, then I could delete it.
const data = await PRISMA.ref_types.update({
where: { id: id },
data: {
business_name: business_name,
business_logo: File_Name,
business_type: business_type,
address: address,
timezone: timezone,
currency: currency,
ref: headerData?.ref
},
});
// Update the existing image record in the database
const existingImage = await PRISMA.ref_types.findFirst({
where: { id }, select: {
business_logo: true
}
})
// find the image
const a = Object.entries(existingImage)
const b = a[0][1]
const fileName = b.split('/').pop()
console.log("dsadsad", fileName)
// Delete the old image file
fs.unlinkSync('uploads/' + headerData?.ref + '/settings/' + fileName)
let found = await PRISMA.languages.findFirst({
where: { ref: headerData.ref }
})
How do I assign an 'owner' to content when it is created programatically with Strapi
I am trying to associate content created by a User (NOT an Admin User) to that User so that I can then restrict them to only that content later.
Apparentely this functionality doesn't exist out of the box but can be done through middleware, policy, or just custom controller logic.
I'm finding that I'm unable to assign it during the create step and having to do a second update call on every create. Is there a more eloquent way of doing this?
EDIT:
The first method is now working after updating the default User's Role, enabling:
User-Permissions > Auth > Connect
User-Permissions > User > Find
User-Permissions > User > Me
Though I'm still going to have to apply this to every method of every content's controller without a more streamlined solution.
'use strict';
/**
* store controller
*/
const { createCoreController } = require('#strapi/strapi').factories;
module.exports = createCoreController('api::store.store', ({ strapi }) => ({
async create(ctx) {
if (ctx?.state?.isAuthenticated) {
/**
* this does not work. The relationship is not assigned when I open the new store in the admin dashboard
* the userId is correctly added to the incoming data
*/
const userId = ctx.state.user.id
Object.assign(ctx.request.body.data, { users_permissions_user: userId })
console.log('ctx.request.body.data', ctx.request.body.data);
//ctx.request.body.data {
// name: 'User Created Store',
// description: 'this store was created by a logged in user',
// users_permissions_user: 74
//}
}
const response = await super.create(ctx)
console.log('response.data', response.data);
//response.data {
// id: 52,
// attributes: {
// name: 'User Created Store',
// description: 'this store was created by a logged in user',
// createdAt: '2022-07-07T15:48:16.362Z',
// updatedAt: '2022-07-07T15:48:16.362Z',
// publishedAt: '2022-07-07T15:48:16.360Z'
// }
//}
if (response?.data?.id) {
// this does work. The relationship is assigned and the correct user appears on the drop-down box
const userId = ctx.state.user.id
const updated = await strapi.entityService.update('api::store.store', response.data.id, { data: { users_permissions_user: userId } });
console.log('updated', updated);
//updated {
// id: 52,
// name: 'User Created Store',
// description: 'this store was created by a logged in user',
// createdAt: '2022-07-07T15:48:16.362Z',
// updatedAt: '2022-07-07T15:48:16.370Z',
// publishedAt: '2022-07-07T15:48:16.360Z'
//}
}
return response;
}
}));
I'm new to feathersjs. Please help me understand these bits
So, I have this codes (products.services.js)
function mapUserIdToData(context) {
if (context.data && context.params.route.userId) {
context.data.user = context.params.route.userId;
}
}
app.use("/stores", new Stores(options, app));
const service = app.service("stores");
service.hooks(hooks);
// setup our nested routes
app.use("/users/:userId/stores", app.service("stores"));
app.service("users/:userId/stores").hooks({
before: {
find(context) {
if (context.params.route.userId)
context.params.query.user = context.params.route.userId;
},
create: mapUserIdToData,
update: mapUserIdToData,
patch: mapUserIdToData,
},
});
And in my register module (register.service.js), I called these logic to create store for new user
const users = this.app.service("users");
const user = await users.create(userData);
// save store
if (storeTitle) {
const stores = this.app.service("stores");
await stores.create({ user: user._id, title: storeTitle });
}
What I don't understand is : Why the line await stores.create({ user: user._id, title: storeTitle }); also trigger hooks logic in app.service("users/:userId/stores") ? I know because it run the mapUserIdToData function, which will be failed because there is no route param for userId.
Thank You
I'm creating a discord bot using node.js and i want it to create a private text channel on a server and add to it the user sending the command "!create" and the bot itself.
I have found a way to make a text channel using this answer: How to create a text channel
but i can't find a way to make it private and add people to it.
I do it always like this:
const everyoneRole = client.guilds.get('SERVER ID').roles.find('name', '#everyone');
const name = message.author.username;
message.guild.createChannel(name, 'text')
.then(r => {
r.overwritePermissions(message.author.id, { VIEW_CHANNEL: true });
r.overwritePermissions(client.id, { VIEW_CHANNEL: true });
r.overwritePermissions(everyoneRole, { VIEW_CHANNEL: false });
})
.catch(console.error);
First, we define the everyoneRole. Then we use the method overwritePermissions() to overwrite the permissions of the newly created guild textchannel. There we give the message author and the bot the permission to view the channel and we revoke the everyone role the permission to view this channel.
Thanks to #gilles-heinesch for the lead. The API of discord.js got drastically changed over time, so here is an updated version:
const { Client, Permissions } = require('discord.js');
/** #param {string|number} serverId - a "snowflake" ID you can see in address bar */
async function createPrivateChannel(serverId, channelName) {
const guild = await client.guilds.fetch(serverId);
const everyoneRole = guild.roles.everyone;
const channel = await guild.channels.create(channelName, 'text');
await channel.overwritePermissions([
{type: 'member', id: message.author.id, allow: [Permissions.FLAGS.VIEW_CHANNEL]},
{type: 'member', id: client.user.id, allow: [Permissions.FLAGS.VIEW_CHANNEL]},
{type: 'role', id: everyoneRole.id, deny: [Permissions.FLAGS.VIEW_CHANNEL]},
]);
}
https://discord.js.org/#/docs/main/stable/class/ChannelManager
Use cache collection
const channels = message.guild.channels.cache
const myChannel = channels.find(channel => channel.name === 'channel name')
So, I having an issue of sending a DM to a specific person without an author tag, and without a mention of the person. I tried duplicating the mention array:
/*jshint esversion: 6*/
const commando = require('discord.js-commando');
class Msgowner extends commando.Command {
constructor(client) {
super(client, {
name: 'msgowner',
group: 'info',
memberName: 'msgowner',
description: 'Gives rules on mock or legit duels.',
examples: ['ladderrules type'],
});
}
async run(message) {
var user = {
id: '12345',
username: 'Bloodmorphed',
discriminator: '12345',
avatar: 'd510ca3d384a25b55d5ce7f4c259b2d0',
bot: false,
lastMessageID: null,
lastMessage: null,
};
user.send('Test');
}
}
module.exports = Msgowner;
There is a reason why I need to send DMs this way, but I can't seem to figure out how. (The error it gives now is a unknown function). Also replacing id and discriminator with generic numbers, but they are correct in my code.
Try something like this - get the member you're looking for using message.channel.members.find() method:
async run(message) {
// get Collection of members in channel
let members = message.channel.members;
// find specific member in collection - enter user's id in place of '<id number>'
let guildMember = members.find('id', '<id number>');
// send Direct Message to member
guildMember.send('test message');
}
Edit: It looks like it's also possible to find users outside the current channel by doing something like this:
async run(message) {
// get client from message's channel
let client = message.channel.client;
// fetch user via given user id
let user = client.fetchUser('<id number>')
.then(user => {
// once promise returns with user, send user a DM
user.send('Test message');
});
}
Okay, found my answer:
async run(message) {
var user = {
id: '12345,
username: 'Bloodmorphed',
discriminator: '12345',
avatar: 'd510ca3d384a25b55d5ce7f4c259b2d0',
bot: false,
lastMessageID: null,
lastMessage: null,
};
console.log(user);
message.member.user.send('Test');
}
}
module.exports = Msgowner;
EDIT: This was NOT the answer, still looking for one.