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
Related
but I have a serious problem that I had a Discord channel with my friend and my Discord.js bot like bellow. But I left the channel and my friend is dead so Im unable to join the sever anymore.
const { Client, Intents } = require('discord.js')
const { prefix, token } = require("./config.json");
const ytdl = require("ytdl-core");
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]})
client.on('ready', () => {
console.log(client.user.tag + "I came home!")
})
client.on('message', message => {
// some code for message commands
})
client.login(token);
So I want to ask that is there anyway to make my Discord.js bot to generate an invite link of the sever it is in? Because I dont have any knowledge about Discord.js and it's really rushed so please help me with the code.
Thank you everyone for reading.
You will have to set that in your client.on('ready') :
client.on("ready", async() => {
const cache = await client.channels.cache;
const channels = [...cache.keys()];
const channel = await client.channels.fetch(channels[channels.length - 1]); // that depends of the differents kinds of channels, if this isnt working, try different indexes
let invite = await channel.createInvite({
maxAge: 10 * 60 * 1000,
maxUses: 10,
});
console.log(`discord.gg/${invite.code}`)
});
This will create a new invitation. Since you are not on the server, the bot will not be able to send it to you. console.log(discord.gg/${invite.code}) is here so you can copy and paste it into your browser. Then you will be able to join the server.
Have a good day!
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!
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!
I am using discord.js and I have a code where if someone votes for my bot on https://top.gg the bot will send a message, but it got this error
Web process failed to bind to $PORT within 60 seconds of launch
Here is my code:
const Discord = require('discord.js')
const bot = new Discord.Client();
const DBL = require('dblapi.js');
const dbl = new DBL(process.env.DBTOKEN, { webhookPort: 5000, webhookAuth: 'password' }, bot)
dbl.webhook.on('ready', hook => {
console.log(`Webhook running at http://${hook.hostname}:${hook.port}${hook.path}`);
});
dbl.webhook.on('vote', vote => {
let embed = new Discord.MessageEmbed()
.setTitle('A user just upvoted!')
.setDescription(`Thank you **${vote.user.tag}** for voting me!`)
.setColor('FF000')
.setThumbnail(vote.user.displayAvatarURL())
let votechannel = bot.channels.cache.find(x => x.id === '775360008786280468')
votechannel.send(embed)
})
Please help me that would be very appreciated
Heroku changes the Port that runs Node Application from time to time. Try changing your webhook port to process.env.PORT. Check the code below.
const Discord = require('discord.js')
const bot = new Discord.Client();
const DBL = require('dblapi.js');
const dbl = new DBL(process.env.DBTOKEN, { webhookPort: process.env.PORT || 5000, webhookAuth: 'password' }, bot)
dbl.webhook.on('ready', hook => {
console.log(`Webhook running at http://${hook.hostname}:${hook.port}${hook.path}`);
});
dbl.webhook.on('vote', vote => {
let embed = new Discord.MessageEmbed()
.setTitle('A user just upvoted!')
.setDescription(`Thank you **${vote.user.tag}** for voting me!`)
.setColor('FF000')
.setThumbnail(vote.user.displayAvatarURL())
let votechannel = bot.channels.cache.find(x => x.id === '775360008786280468')
votechannel.send(embed)
})
Heroku actually tells you which port you're supposed to bind your web server to through the PORT environment variable, which you can access at process.env.PORT on node.
Change your webhookPort from 5000 to that variable and it should work :)
I'm new in nodejs and I'm writing Viber-bot right now.
Viber-bot documentations is very bad and I really don't understand how to use some functions.
For example: I want to see some user's data, save that data on mobile device etc.
How can I use function:
bot.getUserDetails(userProfile)
I want to get name, id, phone number if it's possible and save it to some variables.
I have this code:
const ViberBot = require('viber-bot').Bot;
const BotEvents = require('viber-bot').Events;
const TextMessage = require('viber-bot').Message.Text;
const express = require('express');
const app = express();
if (!process.env.BOT_ACCOUNT_TOKEN) {
console.log('Could not find bot account token key.');
return;
}
if (!process.env.EXPOSE_URL) {
console.log('Could not find exposing url');
return;
}
const bot = new ViberBot({
authToken: process.env.BOT_ACCOUNT_TOKEN,
name: "I'm your bot",
avatar: ""
});
const port = process.env.PORT || 3000;
app.use("/viber/webhook", bot.middleware());
app.listen(port, () => {
console.log(`Application running on port: ${port}`);
bot.setWebhook(`${process.env.EXPOSE_URL}/viber/webhook`).catch(error => {
console.log('Can not set webhook on following server. Is it running?');
console.error(error);
process.exit(1);
});
});
Sorry if it's stupid questions.
Many thanks.
You can get the user profile data from the response triggered in these following events.
"conversation_started"
"message_received"
const ViberBot = require('viber-bot').Bot;
const BotEvents = require('viber-bot').Events;
const bot = new ViberBot(logger, {
authToken: process.env.VB_API_KEY,
name: "Bot Name",
avatar: ""
});
bot.on(BotEvents.CONVERSATION_STARTED, (response) => {
const roomname = response.userProfile.id;
const username = response.userProfile.name;
const profile_pic = response.userProfile.avatar;
const country_origin = response.userProfile.country;
const language_origin = response.userProfile.language;
//Do something with user data
})
bot.on(BotEvents.MESSAGE_RECEIVED, (message, response) => {
//Same as conversation started
});
If you want to fetch user info specifically, you can use this endpoint describe here in viber NodeJS developer documentation.
https://developers.viber.com/docs/all/#get_user_details
If you want to get bot info, try this endpoint.
https://developers.viber.com/docs/all/#get_account_info