How to make Slack bot dynamically reply at the same channel using node.js - node.js

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);
});

Related

socket emits does not do anything, no messages are reflected in ReactsJs UI

i am a newbie in socket.io, i apologize for any bad practices or outright errors in code below, any help would be really appreciated.
i am trying to make a simple chats app where two people can join a room and chat with each other using Socket.io and Reactjs + Nodejs
my server file is as below
io.on("connect", (socket) => {
console.log(socket.id, " connected"); //prints
socket.on("disconnect", () => {
console.log(socket.id, " Disconnected"); //prints
});
socket.on("join", ({ room, username }) => {
console.log(`${username} joined room ${room}`) //prints
socket.on("message", (payload) => {
console.log(`${username} says - ${payload.message}`); //prints
socket.emit("message", payload) //does not reflect in front-end
})
socket
.to(room)
.emit("message", {
message: `${username} has joined the Room`,
isToast: true,
}); //does not reflect on front-end
socket.emit("message", {
message: `Hello ${username}, Welcome to Room ${room}`,
isToast: true,
}); //does not reflect on front-end
});
});
my frontend is as following
const Home = ({ socket }) => {
const msgRef = useRef();
const { setSession } = useSessionContext();
const [msg, setMsg] = useState([]);
socket.on("message", (payload) => {
// setMsg(prev => [...prev, payload]); //remains empty for some reason
console.log(payload); //prints correctly only when user himself sends, texts from others dont reflect
});
const handleMsgSend = (e) => {
e.preventDefault();
const newText = msgRef.current.value;
socket.emit("message", { message: newText, isToast: false })
e.target.reset();
};
.
.
.
.
thankyou for your time, i have been banging my head on this since days, rage quitting and trying again in the verge of tears.
Expected behavior :-
user connects - xyz connected (log)
on room join - xyz joined room abc (log)
xyz sends text - xyz says qwerty (log)
text gets emited to other connected user including sender via message
xys has joined room get emited to all users in room except the sender via message
hello xyz welcome to room abc gets emited to only sender via message

msg.content not being defined

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!

How to avoid pending promises when sending data from google api to discord.js?

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);
}
});

Bot receiver listen only to itself

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.

Slackbot api can't receive messages

I'm building a SlackBot with NodeJS.
I'm currently using this library slackbots, but the problem is that after the initialization, the bot does not appear in the Apps category, but it's inside SlackBot and every time I type a message it returns an error message:
I'm sorry, I don't understand! Sometimes I have an easier time with a few simple keywords. Or you can head to our wonderful Help Center for more assistance!
On the other side, when I send a message to a user I can see the bot I have set up:
How can I make the bot Hugo separated from the SlackBot inside Slack?
That's how I set it up:
var SlackBot = require('slackbots');
var bot = new SlackBot({
token: process.env.SLACK_TOKEN,
name: 'Hugo'
});
function get() {
return bot;
}
exports.get = function() {
return bot;
}
exports.send_message = function(user_ref, message) {
bot.postMessage(user_ref, message).then((data) => {
return data;
});
}
exports.get_users = function() {
var user_list = get().getUsers();
return user_list;
}
And this is how I send the test message:
var bot = require('./modules/bot.js');
bot.get().on('message', function(data) {
console.log("#######################################"); // -> debug only
console.log(data);
console.log("#######################################");
bot.send_message('USER_ID', 'test response');
});

Resources