I'm making a ticketing system with buttons. I trying to if user opened a ticket, user can't open a new ticket. Im tried some code:
//ticket channel is created with **"help: " + interaction.user.username** name
if (interaction.guild.channels.fetch('channel name'))
//working with only id
if (interaction.guild.channels.cache.get(c=>c.name==='channel name'))
//reacted nothing
The discord.js channels cache is a Discord.Collection of values, meaning that it is a JS map with some extra quality of life methods added by Discord.js. Discord Collections are keyed using the snowflake id with the value being whatever object is being stored with that id (in this case the channel you want). This means that the method fetch on the collection of channels can always only be passed an ID as stated here in the docs. This would also mean that the Map.get() method you try to use in the second attempt will not return anything as the channel is not keyed by its name, its keyed by a snowflake id.
You can use a piece of code like this one I used in a discord moderation bot to find and return a channel by name if it exists in the cache.
/**
* Get the log channel for the provided guild.
* #param {Discord.Guild} guild The guild to get the log channel for.
*/
#getLogChannel = (guild) => {
const guildLogChannel = guild.channels.cache
.find(channel => channel.name === 'guild-logs');
if (!guildLogChannel) return false;
return guildLogChannel;
}
If the channel has not yet been cached you have no other option than to pass that channel into the interaction as an option, fetch the channel by its snowflake id, or fetch all channels for all guilds the bot is in inside your client.on('ready', () => {}) handler. The last option is what I chose to do for the bot that the above code snippet is taken from.
Related
I have telegram bot which is added to the group and is listening on everything what is going on on the group. There is a command /invite implemented which displays invitation link to the group (not to the bot but to the group). This link contains parameter refUserId so I can get it later and count how many people has been invited by particular members of the group. This is what I was going to achieve but looks like there is no way to retrieve invitation link parameters on the new_chat_members event.
Here is a piece of code I want to retrieve the param
bot.on('new_chat_members', ctx => {
// retrieve refUserId param here
})
I'm open to any suggestion and will be more than grateful to hear some other solutions.
Here is bigger picture in case that's needed
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.start((ctx) => ctx.reply(`${Constants.msg.welcome(ctx.from.first_name)}`))
bot.command('invite', ctx => {
// reply with invitation link like this:
// t.me/myGroupIdWillBeHere?refUserId=${ctx.from.id}
})
bot.on('new_chat_members', ctx => {
// retrieve refUserId param here
})
bot.launch()
Using Discord.js in an Express/Node.js app, I'm trying to build a bot that grabs external data periodically and updates Discord with an embed msg containing some elements of that data. I'm trying to add a feature that will check if that data was deleted from the external source(no longer existing upon the next grab), then delete the specific msg in Discord that contains that data that was sent.
Some of the msgs posted in Discord may have duplicate data items, so I want to delete by specific msg ID, but it seems that msg ID is assigned when posted to Discord.
Is there a way to programmatically grab or return this msg ID when sending from Discord.js, rather than manually copy/pasting the msg ID from the Discord GUI? In other words, I need my bot to know which message to delete if it sees that msg's source data is no longer being grabbed.
// FOR-LOOP TO POST DATA TO DISCORD
// see if those IDs are found in persistent array
for (var i = 0; i < newIDs.length; i++) {
if (currentIDs.indexOf(newIDs[i]) == -1) {
currentIDs.push(newIDs[i]); // add to persistent array
TD.getTicket(33, newIDs[i]) // get ticket object
.then(ticket => { postDiscord(ticket); }) // post to DISCORD!
}
}
// if an ID in the persistent array is not in temp array,
// delete from persistent array & existing DISCORD msg.
// message.delete() - need message ID to get msg object...
// var msg = channel.fetchMessage(messageID) ?
Let me refer you to:
https://discord.js.org/#/docs/main/stable/class/Message
Assuming you are using async/await, you would have something like:
async () => {
let message = await channel.send(some message);
//now you can grab the ID from it like
console.log(message.id)
}
If you are going to use .then for promises, it is the same idea:
channel.send(some message)
.then(message => {
console.log(message.id)
});
ID is a property of messages, and you will only get the ID after you receive a response from the Discord API. This means you have to handle them asynchronously.
im trying to implement my bot a function. Function that if the channel write any message it will be forwarded to the groups where the bot already is.
Trying to use scope method that worked like a charm on welcome message when new user joined the group.
//index.js
const Telegram = require('telegram-node-bot'),
tg = new Telegram.Telegram('MYAPI', {
workers: 1
});
const ForwardController = require('./controllers/forward')
tg.router.when(new Telegram.TextCommand('/info', 'infoCommand'), new InfoController())
.otherwise(new ForwardController());
//forward.js
const Telegram = require('telegram-node-bot');
class ForwardController extends Telegram.TelegramBaseController {
handle(scope) {
if ('channel' == scope.message.chat._type) {
scope.api.forwardMessage(scope.message._chat._id, _forwardFromChat._text);
}
}
}
module.exports = ForwardController;
I tried many combinations but the message is never forwarded... The bot is already administrator on the channel and is also putted in the groups. (Have also private message opened with bot so i think it should forward also there)
Take a look at the API reference for the library, the documentation page appears to be down so Github is your friend.
The forwardMessage call you are making has incorrect arguments and is accessing the private class variables. It is also returning a promise so you should await the promise or chain a .then to it. You can use the class methods on the Scope instance itself.
It should be more like:
// using async/await - note the containing function must be async for this approach
const result = await forwardMessage(<id of chat here>, scope.message().id());
// or to chain a .then
forwardMessage(<id of chat here>, scope.message().id())
.then(result => /* do something with result */)
.catch(err => /* handle the error */);
This will use the Scopes instance method and handle sending the id of the current chat for you, all you need is the id of the chat you want to send the message to and then replace the <id of chat here> with that id.
My logging command needs a channel to send messages, I do this with a >logging #channel-here command, it stores on better-sqlite3, my issue is I am not sure on how to read the contents and convert it to a channel.
I have been working on this for several days, and I have tried several different things, this was my latest attempt
const id = sql.prepare(`SELECT channel FROM logging WHERE guildid = ${message.guild.id};`).get();
const logs = client.channels.get(id);
if (!logs) return;
logs.send(`A message was deleted`);
const logs = needs to = the channel id that you see in the channel record if the guildid record matches the one that the message was deleted in.
Instead of saving the channels mention you should save the channels id.
<#channel-id> is used to mention a channel, but discord.js <guild>.channels.get(), takes only the ID.
So you should only store the Channel Id in the Database, in your code for >logging #channel-here just use const mentionedchannel = message.mentions.channels.first();
and then into your DB just write the mentionedchannel.id, then your .get() should work!
I've seen my bot join many more servers, but it seems like some are abusing it.
I want the bot to make a one time use invite to a server that I am not on, but my bot is. Once I am on the server I can just remove it. It would be like so:
^backdoor "guild id". I am very new to coding. Thanks!
There are 2 possible ways of doing this, but both are reliant on the permissions that the bot has in that guild.
guildid has to be replaced with an ID or an variable equivilant to the ID
Way 1:
let guild = client.guilds.get(guildid):
if (!guild) return message.reply("The bot isn't in the guild with this ID.");
guild.fetchInvites()
.then(invites => message.channel.send('Found Invites:\n' + invites.map(invite => invite.code).join('\n')))
.catch(console.error);
Way 2:
let guild = client.guilds.get(guildid):
if (!guild) return message.reply("The bot isn't in the guild with this ID.");
let invitechannels = guild.channels.filter(c=> c.permissionsFor(guild.me).has('CREATE_INSTANT_INVITE'))
if(!invitechannels) return message.channel.send('No Channels found with permissions to create Invite in!')
invitechannels.random().createInvite()
.then(invite=> message.channel.send('Found Invite:\n' + invite.code))
There would also be the way of filtering the channels for SEND_MESSAGE and you could send a message to the server.
Instead of entering the guild and then removing it, it would be simpler to just make the bot leave the guild, using Guild.leave()
// ASSUMPTIONS:
// guild_id is the argument from the command
// message is the message that triggered the command
// place this inside your command check
let guild = client.guilds.get(guild_id);
if (!guild) return message.reply("The bot isn't in the guild with this ID.");
guild.owner.send("The bot has been removed from your guild by the owner.").then(() => {
guild.leave();
});