I am creating a discord music bot. I want the bot to give output messages with embeds and reply to the user who used the command. Here's my code:
const { QueryType } = require('discord-player');
module.exports = {
name: 'play',
aliases: ['p'],
utilisation: '{prefix}play [song name/URL]',
voiceChannel: true,
async execute(client, message, args) {
if (!args[0]) return message.channel.send(`Please enter a valid search.`);
const res = await player.search(args.join(' '), {
requestedBy: message.member,
searchEngine: QueryType.AUTO
});
if (!res || !res.tracks.length) return message.channel.send(`No results found.`);
const queue = await player.createQueue(message.guild, {
metadata: message.channel
});
try {
if (!queue.connection) await queue.connect(message.member.voice.channel);
} catch {
await player.deleteQueue(message.guild.id);
return message.channel.send(`I can't join the voice channel.`);
}
await message.channel.send(`Loading your ${res.playlist ? 'playlist' : 'track'}...`);
res.playlist ? queue.addTracks(res.tracks) : queue.addTrack(res.tracks[0]);
if (!queue.playing) await queue.play();
},
};
I want to make it look like this
Related
in my /report command, a channel is created, into which the button and embed are sent. I need to store the id of the new channel the button was sent to in order to interact with that channel later on. I tried to create an array and use exports to export it to my InteractionCreater file in which I have written: const reportArr = require('../commands/Report/report')
module.exports = {
name: 'interactionCreate',
async execute(interaction,client) {
if(interaction.isCommand()){
// if (!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction,client);
} catch (error) {
console.error(error);
await interaction.reply({content: 'There was an error while executing this command!', ephemeral: true});
}
}
else if(interaction.isButton()){
if(interaction.customId.includes('acceptB')){
console.log(reportArr.reports)
}
}
but in InteractionCreater i get undefeated even though if i try to output the array in command then they are output. Tell me how can I put my channel in the InteractionCreater file, which is created when the /report command is sent. This is what sending embed\button looks like:
(Creating new channel).then(async reportChannel => {const acceptButton = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId(`acceptB`)
.setLabel('Accept')
.setStyle('SUCCESS')
.setEmoji('β
')
);
await client.channels.cache.get(`${settings["tickets-log"]}`).send({
content: `<#&${settings.moder}>`
}).then(idmessage => {
idmessage.delete()
})
To create a channel and then send a message and button into it:
const channelName = `Channel Name Here` // Change this
const channel = await interaction.guild.channels.create(channelName, {
parent: 'parentID', // Change this
type: 'GUILD_TEXT',
permissionOverwrites: [{ // For if you want it private, otherwise delete this whole section from here
id: interaction.guild.id,
deny: [
'VIEW_CHANNEL'
]
}, {
id: interaction.user.id, // id of person who started the channel creation process
allow: [
'SEND_MESSAGES', 'VIEW_CHANNEL', 'EMBED_LINKS', 'ATTACH_FILES', 'READ_MESSAGE_HISTORY'
]
}, {
id: 'adminRoleID', // Change this
allow: [
'SEND_MESSAGES', 'VIEW_CHANNEL', 'EMBED_LINKS', 'ATTACH_FILES', 'READ_MESSAGE_HISTORY'
]
}, {
id: 'anyAdditionalRoleID', // Change this
allow: [
'SEND_MESSAGES', 'VIEW_CHANNEL', 'EMBED_LINKS', 'ATTACH_FILES', 'READ_MESSAGE_HISTORY'
]
}] // For if you want it private, otherwise delete this whole section up to here
})
const acceptButton = new MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId(`acceptB`)
.setLabel('Accept')
.setStyle('SUCCESS')
.setEmoji('β
')
)
await channel.send({
content: `<#&${settings.moder}>`,
components: [acceptButton]
})
Then to make that button do something:
module.exports = {
name: 'interactionCreate',
async execute(interaction, client) {
if (interaction.isCommand()) {
const command = client.commands.get(interaction.commandName);
if (!command) return;
try {
await command.execute(interaction, client);
} catch (error) {
console.error(error);
await interaction.reply({
content: 'There was an error while executing this command!',
ephemeral: true
});
}
} else if (interaction.isButton()) {
if (interaction.customId === 'acceptB') {
console.log('button clicked') // Do what you want to do here
}
}
}
}
Description
I created slash command bot with bot, applications.commands scopes. And create slash command for guild, and command not showed so I create commands as application scope. And still not showing
I tried to kick out my bot and re enter url but not worked...
What is the solution plz! Thank you
Steps to Reproduce
const serverless = require("serverless-http");
const express = require("express");
const app = express();
const { CreateRateUseCase } = require("./core/usecase/createRateUseCase");
const nacl = require("tweetnacl");
const getRawBody = require("raw-body");
const { DiscordBot } = require("./discordBot");
// const { verifyKeyMiddleware } = require("discord-interactions");
require("dotenv").config({ path: `./.env.${process.env.NODE_ENV}` });
app.post(
"/interactions",
// verifyKeyMiddleware(process.env.DISCORD_PUBLIC_KEY),
async (req, res, next) => {
try {
console.log(`req : `);
console.log(req);
console.log(`body ${req.body} ${JSON.stringify(req.body)}`);
const rawBody = await getRawBody(req);
console.log(`rawBody ${rawBody} ${typeof rawBody}`);
const body = JSON.parse(rawBody);
if (
process.env.NODE_ENV === "dev" ||
process.env.NODE_ENV === "production"
) {
const signature = req.get("X-Signature-Ed25519");
console.log(`signature ${signature}`);
const timestamp = req.get("X-Signature-Timestamp");
console.log(`timestamp ${timestamp}`);
const isVerified = nacl.sign.detached.verify(
Buffer.from(timestamp + rawBody),
Buffer.from(signature, "hex"),
Buffer.from(process.env.DISCORD_PUBLIC_KEY, "hex")
);
console.log(`isVerified ${isVerified}`);
if (!isVerified) {
console.log("Failed verification");
return res.status(401).end("invalid request signature");
}
if (body.type === 1) {
console.log("Handling validation test request");
return res.status(200).send({ type: 1 });
}
}
if (body.type === 2) {
if (
body.channel_id !== process.env.DISCORD_CHANNEL_ID_KOR &&
body.channel_id !== process.env.DISCORD_CHANNEL_ID_EN
) {
console.log(`channel id ${body.channel_id}`);
console.log(
"This command is only available in the COMMUNITY category"
);
res.status(200).send({
type: 4,
data: {
content: `This command is only available in the 'COMMUNITY' category. π’`,
},
});
return;
}
const discordBot = new DiscordBot();
const result = await discordBot.execute(body);
console.log(`result ${JSON.stringify(result)}`);
res.status(200).send(result);
console.log("reply done");
}
return;
} catch (e) {
console.error(e.message);
return res.send("Error handling verification");
}
}
);
deploy server on aws lambda
OAuth2 -> URL Generator, check bot, applications.commands and enter url then select server.
check SERVER MEMBERS INTENT, MESSAGE CONTENT INTENT
enter api gateway url to INTERACTIONS ENDPOINT URL as https://xyz.amazonaws.com/interactions/
create slash commands
const { Client, Intents } = require("discord.js");
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});
console.log(`NODE_ENV ${process.env.NODE_ENV}`);
require("dotenv").config({ path: `./.env.${process.env.NODE_ENV}` });
const korCommandList = {
γ
γ
γΉ: {
description: "μμΉ μμ΅λ₯ μλ΅",
},
μμ΅λ₯ : {
description: "μμΉ μμ΅λ₯ μλ΅",
},
μμΉμμ΅λ₯ : {
description: "μμΉ μμ΅λ₯ μλ΅",
},
};
const enCommandList = {
depositapy: {
description: "response deposit yield",
},
yield: {
description: "response deposit yield",
},
apy: {
description: "response deposit yield",
},
deposityield: {
description: "response deposit yield",
},
};
client.on("ready", async () => {
const promises = [];
const objs = Object.assign(korCommandList, enCommandList);
console.log(
`process.env.DISCORD_BOT_CLIENT_ID ${process.env.DISCORD_BOT_CLIENT_ID}`
);
console.log(`process.env.DISCORD_GUILD_ID ${process.env.DISCORD_GUILD_ID}`);
for (const key in objs) {
const p = await client.api
.applications(process.env.DISCORD_BOT_CLIENT_ID)
// .guilds(process.env.DISCORD_GUILD_ID)
.commands.post({
data: {
name: key,
description: objs[key].description,
},
});
promises.push(p);
}
const result = await Promise.all(promises);
console.log(result);
client.destroy();
});
client.login(process.env.DISCORD_BOT_TOKEN);
after hours, or day type / on discord app. normal user can not see commad list, but admin can see.
Expected Behavior
Every user on server with bot can see slash command list.
Current Behavior
Admin can see slash command lists, but normal user can not see.
Screenshots/Videos
text box by server admin
text box by server normal user, slash commands not displayed
Client and System Information
browser admin : chrome on mac
user : discord app on mac
lib
I'm trying to make it so I can verify someones question but the usual reaction.emoji.name check doesn't work. It says that it's undefined. But I've used it so many times without defining it. I'm very lost help would be appreciated.
const {Client, Collection, GuildMember, User, MessageEmbed, Message} = require("discord.js");
module.exports.run = async(client, message, args, member, reaction) => {
var woord = '!poll'
var question = args.slice(0).join(' ')
var pollChannel = message.guild.channels.cache.find(c => c.id === `875406886986477569`)
var poll = new MessageEmbed()
.setTitle(`${message.author.username} wil een poll maken.`)
.setDescription(question)
.setColor('#eb8dd8')
.setFooter(`Poll gemaakt door: `+ message.author.username)
var success = new MessageEmbed()
.setDescription(question)
.setColor('#eb8dd8')
.setFooter("Poll started door: "+ message.author.username)
if(message.content.includes(woord)) {
message.delete({timeout:0})
}
if(message.member.roles.cache.some(r => r.name === 'Barman')) {
if(message.channel.name.includes("π-poll")) {
if(args[1]) {
message.delete()
message.guild.channels.create(message.author.username, { permissionOverwrites:[
{
deny: 'VIEW_CHANNEL',
id: message.guild.id
},
{
allow: 'VIEW_CHANNEL',
id: message.author.id
},
],
}).then(channel => {
channel.send(poll).then(poll => {
poll.react('β
')
.then(() => poll.react('β'));
})
})
} else {
message.delete()
}
}
}
if(reaction.emoji.name === 'β
') {
console.log('check!')
}
}
module.exports.help = {
name: "test"
}
i want collect news from different channels and echo them in a second channel, with the code i can read channels(not all but most).
I stuck now on the echo problem and have no clue about how i can do this, mtproto is completely new to me, thanks.
Im using the following code i have from another stackoverflow question.
const { MTProto, getSRPParams } = require('#mtproto/core');
const prompts = require('prompts');
const api_id = 'xxxxx';
const api_hash = 'xxxxx';
async function getPhone() {
return (await prompts({
type: 'text',
name: 'phone',
message: 'Enter your phone number:'
})).phone
}
async function getCode() {
// you can implement your code fetching strategy here
return (await prompts({
type: 'text',
name: 'code',
message: 'Enter the code sent:',
})).code
}
async function getPassword() {
return (await prompts({
type: 'text',
name: 'password',
message: 'Enter Password:',
})).password
}
const mtproto = new MTProto({
api_id,
api_hash,
});
function startListener() {
console.log('[+] starting listener')
mtproto.updates.on('updates', ({ updates }) => {
const newChannelMessages = updates.filter((update) => update._ === 'updateNewChannelMessage').map(({ message }) => message) // filter `updateNewChannelMessage` types only and extract the 'message' object
for (const message of newChannelMessages) {
// printing new channel messages
console.log(`[${message.to_id.channel_id}] ${message.message}`)
}
});
}
// checking authentication status
mtproto
.call('users.getFullUser', {
id: {
_: 'inputUserSelf',
},
})
.then(startListener) // means the user is logged in -> so start the listener
.catch(async error => {
// The user is not logged in
console.log('[+] You must log in')
const phone_number = await getPhone()
mtproto.call('auth.sendCode', {
phone_number: phone_number,
settings: {
_: 'codeSettings',
},
})
.catch(error => {
if (error.error_message.includes('_MIGRATE_')) {
const [type, nextDcId] = error.error_message.split('_MIGRATE_');
mtproto.setDefaultDc(+nextDcId);
return sendCode(phone_number);
}
})
.then(async result => {
return mtproto.call('auth.signIn', {
phone_code: await getCode(),
phone_number: phone_number,
phone_code_hash: result.phone_code_hash,
});
})
.catch(error => {
if (error.error_message === 'SESSION_PASSWORD_NEEDED') {
return mtproto.call('account.getPassword').then(async result => {
const { srp_id, current_algo, srp_B } = result;
const { salt1, salt2, g, p } = current_algo;
const { A, M1 } = await getSRPParams({
g,
p,
salt1,
salt2,
gB: srp_B,
password: await getPassword(),
});
return mtproto.call('auth.checkPassword', {
password: {
_: 'inputCheckPasswordSRP',
srp_id,
A,
M1,
},
});
});
}
})
.then(result => {
console.log('[+] successfully authenticated');
// start listener since the user has logged in now
startListener()
});
})
Using Azure Bot Framework and LUIS.ai to recognize user intent. Performing a get request to the endpoint with the text returns the json object I am expecting, however using the built-in Luis Recognizer I receive the following error: 'Cannot read property 'get' of undefined'. From the documentation here: https://learn.microsoft.com/en-us/azure/cognitive-services/luis/luis-nodejs-tutorial-bf-v4 this appears to be the proper configuration so I am not sure what is going awry. Any ideas?
const { ComponentDialog, DialogSet, DialogTurnStatus, WaterfallDialog, ChoicePrompt, TextPrompt } = require('botbuilder-dialogs');
const { TopLevelDialog, TOP_LEVEL_DIALOG } = require('./topLevelDialog');
const { LuisRecognizer, QnAMaker } = require('botbuilder-ai');
const axios = require('axios');
const MAIN_DIALOG = 'MAIN_DIALOG';
const WATERFALL_DIALOG = 'WATERFALL_DIALOG';
const USER_PROFILE_PROPERTY = 'USER_PROFILE_PROPERTY';
const CHOICE_PROMPT = 'CHOICE_PROMPT';
const TEXT_PROMPT = 'TEXT_PROMPT';
class MainDialog extends ComponentDialog {
constructor(userState) {
super(MAIN_DIALOG);
this.userState = userState;
this.userProfileAccessor = userState.createProperty(USER_PROFILE_PROPERTY);
this.addDialog(new TextPrompt(TEXT_PROMPT));
this.addDialog(new TopLevelDialog());
this.addDialog(new WaterfallDialog(WATERFALL_DIALOG, [
this.initialStep.bind(this),
this.askIfFinishedStep.bind(this),
this.finalStep.bind(this)
]));
this.initialDialogId = WATERFALL_DIALOG;
let luisConfig = {
applicationId: '',
endpointKey: '',
endpoint: '',
};
this.Luis = new LuisRecognizer(
luisConfig,
{
includeAllIntents: true,
log: true,
staging: false
},
true
);
}
async run(turnContext, accessor) {
const dialogSet = new DialogSet(accessor);
dialogSet.add(this);
const dialogContext = await dialogSet.createContext(turnContext);
const results = await dialogContext.continueDialog();
if (results.status === DialogTurnStatus.empty) {
await dialogContext.beginDialog(this.id);
}
}
async initialStep(stepContext) {
let luisAnalysis = await this.Luis.recognize(stepContext);
let queryString = encodeURIComponent(stepContext.context._activity.text);
/*
Ignore this if statement - only in use with the get request
*/
if(luisResponse.data.topScoringIntent.intent === 'TrainingExpiry' && luisResponse.data.topScoringIntent.score > .75)
{
return await stepContext.beginDialog(TOP_LEVEL_DIALOG);
}
else
{
await stepContext.context.sendActivity("I'm sorry, that is not supported at this time or a high enough intent was not acknowledged.");
await stepContext.context.sendActivity("Top intent: " + luisResponse.data.topScoringIntent.intent + " Score: " + luisResponse.data.topScoringIntent.score);
return await stepContext.next();
}
}
async askIfFinishedStep(stepContext) {
const promptOptions = { prompt: 'Is there anything else I can assist you with?' };
return await stepContext.prompt(TEXT_PROMPT, promptOptions);
}
async finalStep(stepContext) {
if(stepContext.context._activity.text.toLowerCase() === 'no')
{
await stepContext.context.sendActivity("Good bye");
return await stepContext.endDialog();
}
else
{
return await stepContext.beginDialog(MAIN_DIALOG);
}
}
}
module.exports.MainDialog = MainDialog;
module.exports.MAIN_DIALOG = MAIN_DIALOG;
Note: The issue was in my parameter being passed to the recognizer, as #billoverton pointed out. The solution is to pass stepContext.context.
Looking at luisRecognizer.js from the botbuilder-ai module, the error is because the recognizer is expecting a turnContext (with turnState property) and you are sending a stepContext. turnState doesn't exist on stepContext, thus the get property is failing and causing your error. If you send stepContext.context instead, that will fix the issue, i.e. let luisAnalysis = await this.Luis.recognize(stepContext.context);