Slack request signing verification failed in nodeJs - javascript

I am trying to setup slack bot and facing below issue.
Error: Slack request signing verification failed
I am exactly following this YT tutorial, even tried git clone his repo to try out but still facing same error.
I even tried to search other slack bot setup tutorial and come back to same issue.
Please help if any of you have experience in fixing this.
Followed tutorial: https://www.youtube.com/watch?v=Awuh2I6iFb0
-> Environment: NodeJS
-> app.js file
require('dotenv').config();
const { WebClient } = require('#slack/web-api');
const { createEventAdapter } = require('#slack/events-api');
const slackSigningSecret = process.env.SLACK_SIGNING_SECRET;
const slackToken = process.env.SLACK_TOKEN;
const port = process.env.SLACK_PORT || 3000;
const slackEvents = createEventAdapter(slackSigningSecret);
const slackClient = new WebClient(slackToken);
slackEvents.on('app_mention', (event) => {
console.log(`Got message from user ${event.user}: ${event.text}`);
(async () => {
try {
await slackClient.chat.postMessage({ channel: event.channel, text: `Hello <#${event.user}>! :tada:` })
} catch (error) {
console.log(error.data)
}
})();
});
slackEvents.on('error', console.error);
slackEvents.start(port).then(() => {
console.log(`Server started on port ${port}`)
});
Full error code:
Error: Slack request signing verification failed
at Server. (/Users/byao/CD/playground/slackcicd/node_modules/#slack/events-api/dist/http-handler.js:148:39)
at Server.emit (events.js:375:28)
at parserOnIncoming (_http_server.js:897:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:126:17) {
code: 'SLACKHTTPHANDLER_REQUEST_SIGNATURE_VERIFICATION_FAILURE'
}
Very appreciated and full of thank you if any of you are willing to help!

Related

I can get response with postman but cannot get with axios

I started a full stack app. I wrote models and routers on backend part. On frontend part, I installed axios and add "proxy": "http://localhost:xxxx/api" to package.json file. When I send get request with postman, it response me the data. But when I go to http://localhost:xxxx, on chrome console it says "AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST'"
Its my package.json file's last line;
}, "proxy": "http://localhost:8800/api"
}
Its my get router;
router.get("/", async (req,res) => {
try {
const pins = await Pin.find();
res.status(200).json(pins);
} catch (err) {
res.status(500).json(err)
}
});
and its my frontend app.js useEffect code:
useEffect( () => {
const getPins = async () => {
try {
const res = await axios.get("/pins");
setPins(res.data);
} catch (err) {
console.log(err);
}
};
getPins();
}, []);
Thanks for helps
Instead of attempting to ping axios.get("/pins") try to ping axios.get("/")`
I believe you are getting a 404 not found on the route as your frontend and backend routes don't match.
I restarted Visual Studio Code and the problem solved.

Discord JS: Deploy Commands

I am using discord.js v13. I have successfully created a bot with scopes bot and application.commands and successfully add it to a channel on my server. Now I am following the tutorial for registering slash commands. I created a file deploy-commands.js with the following content:
const { SlashCommandBuilder } = require('#discordjs/builders');
const { REST } = require('#discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, guildId, token } = require('./config.json');
const commands = [
new SlashCommandBuilder().setName('ping').setDescription('Replies with pong!'),
new SlashCommandBuilder().setName('server').setDescription('Replies with server info!'),
new SlashCommandBuilder().setName('user').setDescription('Replies with user info!'),
]
.map(command => command.toJSON());
const rest = new REST({ version: '9' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
Then I run command node deploy-commands.js and I get error:
DiscordAPIError[50001]: Missing Access
at SequentialHandler.runRequest (/home/evalenzuela/apps/discord-aurasix/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.js:198:23)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async SequentialHandler.queueRequest (/home/evalenzuela/apps/discord-aurasix/node_modules/#discordjs/rest/dist/lib/handlers/SequentialHandler.js:99:20) {
rawError: { message: 'Missing Access', code: 50001 },
code: 50001,
status: 403,
method: 'put',
url: 'https://discord.com/api/v9/applications/901217590259617813/guilds/901235476399280138/commands'
}
I have reviewed a lot of info on the internet but could not find the solution. I have triple checked the clientId, guildId and application token.
Adding on to Pedro's comment,
From Trying to register commands: DiscordAPIError[50001]: Missing Access:
"Have you made sure that the 'applications.commands' scope is checked in the scopes section of the OAuth2 settings for your bot in the discord developer portal?"
You mention you remade the application and bot but did not verify you correctly set the application.commands scope permission. This is likely your issue.

"Users is not a function" -- Discord.JS and Javascript

I'm a bit new to Javascript and Discord.JS and was wondering if I could get some help? I keep getting "Users is not a function" in my terminal after trying to run the bot. I'm also wondering if I coded the bot correctly or not. My goal is to have the bot privately message someone at a set time every day.
Thank you.
const e = require('express')
const client = new Discord.Client()
const config = require('./config.json')
const privateMessage = require('./private-message')
const cron = require('node-cron');
const express = require('express');
cron.schedule('42 23 * * *', function() {
console.log('cron is working');
}, {
scheduled: true,
timezone: "America/New_York"
});
client.login(config.token).then(() => {
console.log('The client is ready!');
var dm = client.users.fetch('749097582227357839');
if(users && client.users.fetch('749097582227357839'))
client.users.fetch('749097582227357839').send("hello").then(() => client.destroy());
else
console.log("nope");
client.destroy();
});
client.login(config.token)
if you want to make the bot message someone you can do this-
client.users
.fetch('749097582227357839')
.then((user) => {
user.send(`Hello`,);
});
I hope this fixes your problem :D

Node.js / Socket.io Chat App Works Fine ... Until Real Traffic Causes A TypeError?

I'm (trying) to run a chat app on Heroku. I'm a front-end guy trying to build out my back-end skills, so I was aware this was going to be a bit of stretch for me, but I tested the app out locally before deploying it Heroku. Once it was deployed to Heroku, I asked several friends to log on & off and help me kick the tires. It worked fine. Fast forward to tonight, when the time time for the app to handle actual traffic from strangers (as part of a holiday marathon) and ... it crashed. Almost immediately.
Here's the Heroku error log:
heroku[web.1]: State changed from starting to up
[web.1]: /app/server.js:44
[web.1]: io.to(user.room).emit('message', formatMessage(user.username, msg));
[web.1]: ^
[web.1]:
[web.1]: TypeError: Cannot read property 'room' of undefined
[web.1]: at Socket.<anonymous> (/app/server.js:44:16)
[web.1]: at Socket.emit (events.js:314:20)
[web.1]: at Socket.onevent (/app/node_modules/socket.io/dist/socket.js:253:20)
[web.1]: at Socket._onpacket (/app/node_modules/socket.io/dist/socket.js:216:22)
[web.1]: at /app/node_modules/socket.io/dist/client.js:205:28
[web.1]: at processTicksAndRejections (internal/process/task_queues.js:79:11)
[web.1]: Process exited with status 1
[web.1]: State changed from up to crashed
Ok, I get that there's some undefined wonkiness going on here - although, with my limited Node/JS skills I'm hard-pressed to quickly zero in on the source - but wouldn't this error cause the app to simple not work at all, rather than initially work then crash as soon as it encountered any real traffic?
I'd like to get this app in robust working order, so I'd be greatly appreciative if someone with better JS chops than mine could help me out here.
Here's my server.js file:
const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const formatMessage = require('./utils/messages');
const { userJoin, getCurrentUser, userLeave, getRoomUsers } = require('./utils/users');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// Set static folder
app.use(express.static(path.join(__dirname, 'web_apps--listener_chat')));
const botName = '🤖 Jon Solobot 🤖';
// Run when a client connects
io.on('connection', socket => {
socket.on('joinRoom', ({ username, room }) => {
const user = userJoin(socket.id, username, room);
socket.join(user.room);
// Welcome current user
socket.emit('message', formatMessage(botName, `Welcome to the WPRBXmas Listener Chat, ${user.username}!`));
// Broadcast when a user connects
socket.broadcast
.to(user.room)
.emit('message', formatMessage(botName, `${user.username} has entered the chat, bearing tidings of comfort & oi.`));
// Send users and room info.
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
});
// Listen for chatMessage
socket.on('chatMessage', (msg) => {
const user = getCurrentUser(socket.id);
io.to(user.room).emit('message', formatMessage(user.username, msg));
});
// Broadcast when a user disconnects
socket.on('disconnect', () => {
const user = userLeave(socket.id);
if(user) {
io.to(user.room).emit('message', formatMessage(botName, `${user.username} has left the chat for a long winter's nap.`)
);
// Send users and room info.
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
}
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Here's my users.js file:
const users = [];
// Join user to chat
function userJoin(id, username, room) {
const user = { id, username, room};
users.push(user);
return user;
}
// Get current user
function getCurrentUser (id) {
return users.find(user => user.id === id);
}
// User leaves chat
function userLeave(id) {
const index = users.findIndex(user => user.id === id);
if(index !== -1) {
return users.splice(index, 1)[0];
}
}
// Get room users
function getRoomUsers (room) {
return users.filter(user => user.room === room);
}
module.exports = {
userJoin,
getCurrentUser,
userLeave,
getRoomUsers
};
And here's my messages.js file:
const moment = require('moment');
function formatMessage(username, text) {
return {
username,
text,
time: moment().format('h:mm a')
};
}
module.exports = formatMessage;
I realize this is a lot but I'm guessing someone with whose more familiar with Socket.io will be able to take on look at this and see the problem immediately.
Many thanks to anyone taking the time to read and respond! Happy holidays!
I've actually just built a socket.io chat yestarday,deployed it on heroku,something'
s wrong with heroku servers.If your app managed to work on heroku,and crashed after some time because of the traffic you can use "heroku restart" in the app folder,that worked for me,you could try to host it somewhere else.Merry Christmas!

400 Bad Request with Adonisjs websocket

I'm runing a localhost adonisjs project with a websocket. I followed the adonis get started here. Everything in the server looks ok, but when I tried to connect in my react-native application a got this error:
{
"isTrusted": false,
"message": "Expected HTTP 101 response but was '400 Bad Request'",
}
This is my cliente code:
const ws = new WebSocket("ws://192.168.0.11:3333")
ws.onopen = () => {
ws.send(JSON.stringify({
t: 1,
d: { topic: 'prelista:5999c0ea-6bbb-4e0f-9496-f62658bbac5' }
}))
}
ws.onmessage = (e) => {
console.log(e)
}
ws.onerror = (event) => {
console.log(event)
}
This is my server code:
'use strict'
const Ws = use('Ws')
Ws.channel('prelista:*', ({ socket }) => {
console.log(socket.topic)
})
I found my mistake. Whe we use Adonis websocket on the server side, we need to add /adonis-ws in the end of ws path. Well, changed this const ws = new WebSocket("ws://192.168.0.11:3333")
to this const ws = new WebSocket("ws://192.168.0.11:3333/adonis-ws")
worked now 👍

Categories

Resources