Okay so I am trying to make an announcement command for my server, but when I try to run this it says: ReferenceError: msg is not defined
I am not sure on what it is that I am doing incorrectly.
Here is the code in question:
'use strict';
//require discord.js package
const Discord = require("discord.js");
const config = require("./config.json")
//Create an instance of a Discord client
const client = new Discord.Client();
//The ready event is vital, only after this will your bot start reacting and responding
client.on('ready', () => {
console.log('I am ready!');
});
//create an event listener for messages
client.on('message', message => {
if (message.content === 'ping') {
message.channel.send('pong');
}
});
if (msg.content === "^ann"){
let channel = client.channels.cache.get('channel id');
msg.channel.send("What is your announcement? (^cancel to cancel)");
const collector = msg.channel.createMessageCollector(m => m.author.id === msg.author.id, { time: 100000000 });
collector.once('collect', m => {
if (m.content == "^cancel") {
m.author.send("Announcement cancelled.");
return;
} else {
var announcement = m.content;
channel.send(announcement);
msg.channel.send("Announcement made!");
return;
}
});
//Do stuff
client.on("message", function (msg) {
if (msg.content.indexOf("^mirror") === 0) {
let item = new Discord.MessageEmbed()
.setImage(msg.author.displayAvatarURL())
.setColor("#E6E6FA")
.setFooter("OMG! WHEW~");
msg.channel.send(item);
}
})
//Bot Token
client.login('token')}
This is what i have for the code that I am working on
The error appears because you have your code outside the message event. So all the code about the message etc. has to be in the message event.
The second thing, I suggest to create 1 message event. I see you have created 2 message events. That is not a big problem, but it will clean your code en is more effective. Now, if someone sends a message, he will check this message 2 times. I hope I made it a little bit clear!
Related
I created a queue named 'test_queue' with amqplib
then I deleted the 'test_queue' from the admin page of rabbitmq (http://localhost:15672/#/queues)
but when I excute the following code, it shows 'sent message successfully!'
there is no error even if the queue named 'test_queue' does't exist
How to get an error when queue doesn't exist?
Thanks for any help!
const amqp = require('amqplib');
const sendMsg=async ()=>{
const connection = await amqp.connect('amqp://localhost');
const ch = await connection.createConfirmChannel()
const msg= 'hello world'
const QUEUE_NAME = 'test_queue'
ch.sendToQueue(QUEUE_NAME, Buffer.from(msg),{},function(err, ok) {
if (err !== null) {
console.log(err);
} else {
console.log('sent message successfully!');
}
})
// await ch.close();
// await connection.close();
}
sendMsg();
If you add the mandatory flag to sendToQueue any message which cannot be routed to a queue will be sent back to the publisher. So from your example you would need:
ch.sendToQueue(QUEUE_NAME, Buffer.from(msg),{mandatory: true},function(err, ok)
You can then handle the return using the same channel object:
ch.on('return', (message) => {
console.log(`Unable to route message to ${QUEUE_NAME}`)
}
I am working on a Discord bot which could extract datas from an Excel sheet. For example when I will ask the bot : "!adress paul", I would like the bot to look for "paul" value in the column A of a sheet and return the value of the column B (of the row where the value Paul is) in the discord app.
So far, I succeeded to read data from the Excel sheet and report the datas in the console.log (when I call the console.log inside the function). However each time I call the value out of the function I have a 'Promise {}' that appears... I made many many research on the web, without finding the solution.
const discord = require('discord.js');
const {google} = require('googleapis');
const keys = require('./identifiants.json');
// Creation of the Spreadsheet client
const client1 = new google.auth.JWT(keys.client_email, null,
keys.private_key, ['https://www.googleapis.com/auth/spreadsheets']);
client1.authorize(function(err, tokens)
{
if(err)
{
console.log(err);
return;
}
else
{
console.log('Connected to Google Sheets');
}
});
// Creation of the Discrod client
const client2 = new discord.Client();
client2.on('ready', () =>
{
console.log('Connected to Discord');
});
// Create an event listener for messages
client2.on('message', message =>
{
if (message.content === '!address')
{
console.log("OK 1");
let paul = address(client1);
console.log(paul);
console.log("OK2");
}
});
async function address(client)
{
const gsapi = google.sheets({version:'v4',auth: client });
const opt1 = {spreadsheetId: 'ID OF MY SPREADSHEET', range: 'Sheet1!A1:B3'};
let data = await gsapi.spreadsheets.values.get(opt1);
return data.data.values;
}
client2.login("MY CLIENT LOGIN")
In the console the message "Promise {pending}" appears between "OK1" and "OK2". Can someone help me on that case please? I would be very grateful
Your address function is an async function so it will return a promise.
Therefore, you will need to use then to get the value:
client2.on('message', message => {
if (message.content === '!address') {
address(client1)
.then(paul => {
console.log(paul);
});
}
});
Alternatively, you could use async-await:
client2.on('message', async (message) => {
if (message.content === '!address') {
let paul = await address(client1);
console.log(paul);
}
});
I want to make my slackbot app to answer at the channel that the user mentioned, without manually writing the channel name inside the code.
-example-
problem : I invited my bot into channel #hello, #hi.I mentioned my bot at Channel #hello writing #mybot hi there, but it only replies to channel #hi which I manually wrote down in my code.
I want my bot to automatically find which channel the message came from, and answer back at the same channel that user mentioned.
Not like the code I wrote bot.postMessageToChannel('everyone', `Chuck Norris: ${joke}`,params);
Here is the link of the module that I used and my code
https://github.com/mishk0/slack-bot-api
const SlackBot = require('slackbots');
const axios = require('axios');
const bot = new SlackBot({
token : "",
name : ""
});
// Start Handler
bot.on('start', () =>{
const params = {
icon_emoji: ':)'
};
bot.postMessageToChannel('everyone', 'Feeling tired??? Have some fun with #Joker!'
, params);
});
// Error Handler
bot.on('error', (err) => console.log(err));
//Message Handler
bot.on('message', (data) => {
if(data.type !== 'message'){
return;
}
console.log(data);
handleMessage(data.text);
});
// Responding to Data
function handleMessage(message){
if(message.includes('chucknorris')){
chuckJoke();
}
else if(message.includes(' yomama')){
yoMamaJoke();
}
else if(message.includes(' random')){
randomJoke();
}
else if(message.includes(' help')){
runHelp();
}
}
// Tell a Chuck Norris Joke
function chuckJoke(){
axios.get('http://api.icndb.com/jokes/random/')
.then(res =>{
const joke = res.data.value.joke;
const params = {
icon_emoji: ':laughing:'
};
bot.postMessageToChannel('everyone', `Chuck Norris: ${joke}`,params);
});
}
From here you will find on message it returns you the data object whith channel id
then
you can use postMessage() from the api you have used
postMessage(id, text, params) (return: promise) - posts a message to channel | group | user by ID,
bot.on('message', (data) => {
bot.postMessage(data.channel, 'Feeling tired??? Have some fun with #Joker!'
, params);
console.log(data);
handleMessage(data.text);
});
i have problem with createReceiver. I have code:
client.on('message', message => {
// Voice only works in guilds, if the message does not come from a guild,
// we ignore it
if (!message.guild) return;
if (message.content === '/q') {
// Only try to join the sender's voice channel if they are in one themselves
const voiceChannel = message.member.voiceChannel;
if (message.member.voiceChannel) {
message.member.voiceChannel.join()
.then(connection => { // Connection is an instance of VoiceConnection
connection.on('error', console.error);
// const dispatcher = connection.playFile('C:/Denwer/ddradio/lyubov.mp3');
connection.on('speaking', (user, speaking) => {
if(speaking) {
const receiver = connection.createReceiver();
const stream = receiver.createPCMStream(user);
stream.on('data', chunk => {
console.log(chunk.length);
});
}
});
})
.catch(console.log);
} else {
message.reply('');
}
}
})
console.log(chunk.length); working only when playing music, those. only when the bot speaking. He does not hear other members. Please tell me what the problem is
I had this same problem, I don't know how to completely fix it forever, but if you play a short audio file, like a beep, when the bot joins the channel, your code should work.
When I run the following script ("node musicbot.js" in cmd) and "!play ytlink" within discord itself, the bot joins the voice channel and logs both the command and the link in the console. Yet, the music does not start playing. I have installed ffmpeg, ytdl-core, and discord.js.
Can someone help me out? I do not know which part is messing it up.
const Discord = require("discord.js");
const ytdl = require("ytdl-core");
const config = require("./config.json");
const bot = new Discord.Client();
let queue = [];
function play(connection, message) {
let audio = ytdl(queue[0], {filter: "audioonly"});
let dispatcher = connection.playStream(audio);
dispatcher.on("end", function() {
queue.shift();
if (queue[0]) play(connection, message);
else {
connection.disconnect();
message.channel.send("The queue has ended");
}
});
}
bot.on("message", function(message) {
if (message.channel.type === "dm") return;
if (!message.content.startsWith(config.prefix) || message.author.bot)
return;
let arguments = message.content.split(" ");
let command = arguments[0].toLowerCase();
arguments.shift();
console.log(command);
console.log(arguments);
if (command == "!play") {
if (!arguments[0]) {
message.channel.send("Please provide a YouTube link!");
message.delete();
return;
}
if (!message.member.voiceChannel) {
message.channel.send("Please join a Voice Channel first!");
message.delete();
return;
}
queue.push(arguments[0]);
message.member.voiceChannel.join()
.then(connection => {
play(connection, message);
});
}
});
bot.on("ready", function() {
console.log("Ready");
});
bot.login(config.token);
Ok, I have two solutions for you. This first one is a block of code I have used and I can say it works from experience.
It requires ffmpeg, opusscript and ytdl:
function play(connection, message){
var server = servers[message.guild.id];
server.dispatcher = connection.playStream(ytdl(server.queue[0], {filter:
"audioonly"}));
server.queue.shift();
server.dispatcher.on("end", function() {
if(server.queue[0]) play(connection, message);
else connection.disconnect();
});
}
This second option which I would highly recommend is a node module that has many more advanced features that are hard to implement such as:
musichelp [command]: Displays help text for commands by this addon, or help for a specific command.
play |: Play audio from YouTube.
skip [number]: Skip a song or multi songs with skip [some number],
queue: Display the current queue.
pause: Pause music playback.
resume: Resume music playback.
volume: Adjust the playback volume between 1 and 200.
leave: Clears the song queue and leaves the channel.
clearqueue: Clears the song queue.
owner: Various owner commands/actions. (W.I.P)
It is easy to install and get started, here is the node page with all the information about installation etc.