Everytime I run the command !ping it gives me a huge error in my client.js saying that if(message.author.bot || !message.guild || message.content.toLowerCase().startWith(!)) return; <- this line is an error! Here is the rest of the code:
const { Collection, Client, MessageEmbed } = require('discord.js');
class GiveawayClient extends Client {
constructor() {
super();
this.giveaways = new Collection();
this.commands = new Collection();
this.ms = require('ms');
this.fs = require('fs');
this.path = require('path');
this.discord = require('discord.js');
}
commandHandler(path) {
this.fs.readdirSync(this.path.join(__dirname, `..`, path)).map((f) => {
let File = require(this.path.join(__dirname, `..`, path, f));
this.commands.set(File.name, File)
})
};
start(token, path) {
this.commandHandler(path);
this.login(token);
this.on('ready', () => {
console.log(`${this.user.username} is now online!`);
});
this.on('message', async(message) => {
if(message.author.bot || !message.guild || message.content.toLowerCase().startWith(`!`)) return;
const cmd = args.shift().toLowerCase();
if(this.commands.has(cmd)) this.commands.get(cmd).run(this, message, args).catch(console.error);
});
}
embed(data, message) {
return new MessageEmbed(data).setFooter(message.author.tag, message.author.displayAvatarURL({ dynamic: true}))
}
}
module.exports = GiveawayClient;
I think you made a small, but deadly typo in this line, the message.content.toLowerCase().startsWith("!") shouldn't be returned, but continued, after filtering in only the ones that starts with !.
if(message.author.bot || !message.guild || message.content.toLowerCase().startsWith(`!`)) return;
Also, .startWith() is not a function, .startsWith() is.
Try changing the code above to this:
if(message.author.bot || !message.guild || !message.content.toLowerCase().startsWith(`!`)) return;
This will filter out messages that doesn't start with ! rather than filter out the ones with.
Just change: startWith() to startsWith.
It's just a simple typo error, make sure to read the log next time ^.
Related
Ok, so i'm trying to make a push notification for my discord.
i found this script online.
but it will not post the embed....
This is my monitor code:
TwitchMonitor.onChannelLiveUpdate((streamData) => {
const isLive = streamData.type === "live";
// Refresh channel list
try {
syncServerList(false);
} catch (e) { }
// Update activity
StreamActivity.setChannelOnline(streamData);
// Generate message
const msgFormatted = `${streamData.user_name} is nu live op twitch <:bday:967848861613826108> kom je ook?`;
const msgEmbed = LiveEmbed.createForStream(streamData);
// Broadcast to all target channels
let anySent = false;
for (let i = 0; i < targetChannels.length; i++) {
const discordChannel = targetChannels[i];
const liveMsgDiscrim = `${discordChannel.guild.id}_${discordChannel.name}_${streamData.id}`;
if (discordChannel) {
try {
// Either send a new message, or update an old one
let existingMsgId = messageHistory[liveMsgDiscrim] || null;
if (existingMsgId) {
// Fetch existing message
discordChannel.messages.fetch(existingMsgId)
.then((existingMsg) => {
existingMsg.edit(msgFormatted, {
embed: msgEmbed
}).then((message) => {
// Clean up entry if no longer live
if (!isLive) {
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
}
});
})
.catch((e) => {
// Unable to retrieve message object for editing
if (e.message === "Unknown Message") {
// Specific error: the message does not exist, most likely deleted.
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
// This will cause the message to be posted as new in the next update if needed.
}
});
} else {
// Sending a new message
if (!isLive) {
// We do not post "new" notifications for channels going/being offline
continue;
}
// Expand the message with a #mention for "here" or "everyone"
// We don't do this in updates because it causes some people to get spammed
let mentionMode = (config.discord_mentions && config.discord_mentions[streamData.user_name.toLowerCase()]) || null;
if (mentionMode) {
mentionMode = mentionMode.toLowerCase();
if (mentionMode === "Nu-Live") {
// Reserved # keywords for discord that can be mentioned directly as text
mentionMode = `#${mentionMode}`;
} else {
// Most likely a role that needs to be translated to <#&id> format
let roleData = discordChannel.guild.roles.cache.find((role) => {
return (role.name.toLowerCase() === mentionMode);
});
if (roleData) {
mentionMode = `<#&${roleData.id}>`;
} else {
console.log('[Discord]', `Cannot mention role: ${mentionMode}`,
`(does not exist on server ${discordChannel.guild.name})`);
mentionMode = null;
}
}
}
let msgToSend = msgFormatted;
if (mentionMode) {
msgToSend = msgFormatted + ` ${mentionMode}`
}
let msgOptions = {
embed: msgEmbed
};
discordChannel.send(msgToSend, msgOptions)
.then((message) => {
console.log('[Discord]', `Sent announce msg to #${discordChannel.name} on ${discordChannel.guild.name}`)
messageHistory[liveMsgDiscrim] = message.id;
liveMessageDb.put('history', messageHistory);
})
.catch((err) => {
console.log('[Discord]', `Could not send announce msg to #${discordChannel.name} on ${discordChannel.guild.name}:`, err.message);
});
}
anySent = true;
} catch (e) {
console.warn('[Discord]', 'Message send problem:', e);
}
}
}
liveMessageDb.put('history', messageHistory);
return anySent;
});
This is the embed code:
const Discord = require('discord.js');
const moment = require('moment');
const humanizeDuration = require("humanize-duration");
const config = require('../data/config.json');
class LiveEmbed {
static createForStream(streamData) {
const isLive = streamData.type === "live";
const allowBoxArt = config.twitch_use_boxart;
let msgEmbed = new Discord.MessageEmbed();
msgEmbed.setColor(isLive ? "RED" : "BLACK");
msgEmbed.setURL(`https://twitch.tv/${(streamData.login || streamData.user_name).toLowerCase()}`);
// Thumbnail
let thumbUrl = streamData.profile_image_url;
if (allowBoxArt && streamData.game && streamData.game.box_art_url) {
thumbUrl = streamData.game.box_art_url;
thumbUrl = thumbUrl.replace("{width}", "288");
thumbUrl = thumbUrl.replace("{height}", "384");
}
msgEmbed.setThumbnail(thumbUrl);
if (isLive) {
// Title
msgEmbed.setTitle(`:red_circle: **${streamData.user_name} is live op Twitch!**`);
msgEmbed.addField("Title", streamData.title, false);
} else {
msgEmbed.setTitle(`:white_circle: ${streamData.user_name} was live op Twitch.`);
msgEmbed.setDescription('The stream has now ended.');
msgEmbed.addField("Title", streamData.title, true);
}
// Add game
if (streamData.game) {
msgEmbed.addField("Game", streamData.game.name, false);
}
if (isLive) {
// Add status
msgEmbed.addField("Status", isLive ? `Live with ${streamData.viewer_count} viewers` : 'Stream has ended', true);
// Set main image (stream preview)
let imageUrl = streamData.thumbnail_url;
imageUrl = imageUrl.replace("{width}", "1280");
imageUrl = imageUrl.replace("{height}", "720");
let thumbnailBuster = (Date.now() / 1000).toFixed(0);
imageUrl += `?t=${thumbnailBuster}`;
msgEmbed.setImage(imageUrl);
// Add uptime
let now = moment();
let startedAt = moment(streamData.started_at);
msgEmbed.addField("Uptime", humanizeDuration(now - startedAt, {
delimiter: ", ",
largest: 2,
round: true,
units: ["y", "mo", "w", "d", "h", "m"]
}), true);
}
return msgEmbed;
}
}
module.exports = LiveEmbed;
But it won't post the embed, only the msg. as you can see it updates teh msg aswell.
enter image description here
i'm stuck on this for four days now, can someone help?
I have trouble about sending message from cross-domain iframe in React. I read many articles, most of them are about sending message to iframe.
The issue is that it didn't show any error message in the page that embed the iframe , and when I go to the see the page that I embed, it did show a error message.
Scene.js:230 Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://thewebsite.com') does not match the recipient window's origin ('https://mywebsite').
so I can't tell if I the message have been sent successfully or not.
Here is my code :
confirm = () => {
const { homeId, correctData } = this.state
const form = new FormData();
//process data
form.append('scene_id', homeId)
form.append('material_id', correctData[0].id)
form.append('material_img', correctData[0].component_img)
const obj = JSON.parse(JSON.stringify(form));
//
//way 1
parent.postMessage(obj, '*')
//way 2
parent.postMessage(obj, 'https://www.thewebsite.com/pro_wall.html')
//way 3
window.frames.postMessage(obj, '*')
//way 4
window.top.postMessage(obj, '*')
//way 5
const targetWindow = window.open('https://www.thewebsite.com/pro_wall.html')
setTimeout(() => {
targetWindow?.postMessage(obj, '*')
}, 3000)
}
Sorry for writing too many ways to post message, Just want to make sure I tried every possibility.
After few tries, I got positive feedback from the client. They got data. This is my code I wrote eventually.
confirm = () => {
const { homeId, correctData } = this.state
const formData = new FormData();
formData.append('scene_id', homeId)
formData.append('material_id', correctData[0]?.id)
formData.append('material_img', correctData[0]?.component_img)
var object = {};
formData.forEach((value, key) => {object[key] = value});
var json = JSON.stringify(object);
parent.postMessage(json, `https://www.thewebsite.com/pro_wall.html`)
}
and I saw the code at client's side from web devTool, it looks like this,
<script>
window.addEventListener("message", receivewall, false);
function receivewall(event){
var origin = event.origin;
if(origin == 'https://mywebsite'){
var params = JSON.parse(event.data);
$('#result').html($.param(params));
// console.log(params);
}
// $('#result').html(data);
}
function getQueryVariable(query) {
var vars = query.split('&');
var params = {};
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return params;
}
</script>
static description = 'Get information on a mentioned user.';
static usage = '<#user|id>';
static names = ['userinfo', 'ui'];
static userPerms = [];
static botPerms = [];
async execute(client, message) {
var permissions = [];
var acknowledgements = 'None';
const args = this.message.content.trim().split(/ +/g);
var user = this.message.mentions.users.first() || this.message.author;
const member = this.message.mentions.members.first() || this.message.guild.members.cache.get(args[0]) || this.message.member;
const randomColor = "#000000".replace(/0/g, function () { return (~~(Math.random() * 16)).toString(16); });
if(this.message.member.hasPermission("KICK_MEMBERS")){
permissions.push("Kick Members");
}
if(this.message.member.hasPermission("BAN_MEMBERS")){
permissions.push("Ban Members");
}
if(this.message.member.hasPermission("ADMINISTRATOR")){
permissions.push("Administrator");
}
if(this.message.member.hasPermission("MANAGE_MESSAGES")){
permissions.push("Manage Messages");
}
if(this.message.member.hasPermission("MANAGE_CHANNELS")){
permissions.push("Manage Channels");
}
if(this.message.member.hasPermission("MENTION_EVERYONE")){
permissions.push("Mention Everyone");
}
if(this.message.member.hasPermission("MANAGE_NICKNAMES")){
permissions.push("Manage Nicknames");
}
if(this.message.member.hasPermission("MANAGE_ROLES")){
permissions.push("Manage Roles");
}
if(this.message.member.hasPermission("MANAGE_WEBHOOKS")){
permissions.push("Manage Webhooks");
}
if(this.message.member.hasPermission("MANAGE_EMOJIS")){
permissions.push("Manage Emojis");
}
if(!permissions.length == 0){
permissions.push("No Key Permissions Found");
}
if(this.member.user.id == message.guild.ownerID){
acknowledgements = 'Server Owner';
}
const embed = new Discord.MessageEmbed()
.setDescription(`<#${member.user.id}>`)
.setAuthor(`${member.user.tag}`, member.user.displayAvatarURL)
.setColor(randomColor)
.setFooter(`ID: ${message.author.id}`)
.setThumbnail(member.user.displayAvatarURL)
.setTimestamp()
.addField("Status",`${status[member.user.presence.status]}`, true)
.addField('Joined at: ',`${moment(member.joinedAt).format("dddd, MMMM Do YYYY, HH:mm:ss")}`, true)
.addField("Created at: ",`${moment(message.author.createdAt).format("dddd, MMMM Do YYYY, HH:mm:ss")}`, true)
.addField("Permissions: ", `${permissions.join(', ')}`, true)
.addField(`Roles [${member.roles.cache.filter(r => r.id !== message.guild.id).map(roles => `\`${roles.name}\``).length}]`,`${member.roles.cache.filter(r => r.id !== message.guild.id).map(roles => `<#&${roles.id }>`).join(" **|** ") || "No Roles"}`, true)
.addField("Acknowledgements: ", `${acknowledgements}`, true);
this.message.channel.send({embed});
}
}
**I have tried to define user but it's not working. error:
TypeError: Cannot read property 'user' of undefined.
Whenever i used ,userinfo it's not responding anything. I don't know why this happend, but if you find any other error in the code, can you help me fix it too? Thank you.
but that didn't do anything to help.
What am i missing here?**
this.member.user.id
Should be
member.user.id
Look for “something”.user for errors like that. Then figure out why the something is undefined.
Im trying to make a stopwatch command that when you say !duty on and then !duty off it will calculate the time took to stop it. It works like a regular stopwatch but it is for discord. I have been trying to fix the err for a week but i cant understand why it doesnt work pls help me. The err is in line 10 id where it says message.guild.id
the code:
const Discord = require('discord.js');
const StopWatch = require("timer-stopwatch-dev");
const moment = require('moment');
module.exports = {
name: 'duty',
description: "This is a stopwatch command",
async execute(client, message, args, CurrentTimers) {
try {
let guildTimers = CurrentTimers.get(message.guild.id);
let guildTimersUser = guildTimers.get(message.author.id);
if(!guildTimersUser){ guildTimers.set(message.author.id, new StopWatch()); guildTimersUser = guildTimers.get(message.author.id); };
if(!args[0] || args[0] === 'on'){
if(guildTimersUser.isRunning()) return message.channel.send('You need to stop your shift first!')
guildTimersUser.start();
message.channel.send('You have started your shift')
} else if(args[0] === 'off'){
if(!guildTimersUser.isRunning()) return message.channel.send('You need to start the Stopwatch first!')
guildTimersUser.stop();
message.channel.send(new Discord.RichEmbed().setTitle('You have stopped the Stopwatch!').setDescription('Total Time: ' + dhm(guildTimersUser.ms)).setTimestamp());
}
}
catch(err) {
console.log(err)
}
function dhm(ms){
days = Math.floor(ms / (24*60*60*1000));
daysms=ms % (24*60*60*1000);
hours = Math.floor((daysms)/(60*60*1000));
hoursms=ms % (60*60*1000);
minutes = Math.floor((hoursms)/(60*1000));
minutesms=ms % (60*1000);
sec = Math.floor((minutesms)/(1000));
return days+" days, "+hours+" hours, "+minutes+" minutes, "+sec+" seconds.";
}
}
}
my main:
require('dotenv').config();
//create cooldowns map
const cooldowns = new Map();
module.exports = (Discord, client, message) => {
const prefix = '!';
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd) ||
client.commands.find(a => a.aliases && a.aliases.includes(cmd));
if(command){
//If cooldowns map doesn't have a command.name key then create one.
if(!cooldowns.has(command.name)){
cooldowns.set(command.name, new Discord.Collection());
}
const current_time = Date.now();
const time_stamps = cooldowns.get(command.name);
const cooldown_amount = (command.cooldown) * 1000;
//If time_stamps has a key with the author's id then check the expiration time to send a message to a user.
if(time_stamps.has(message.author.id)){
const expiration_time = time_stamps.get(message.author.id) + cooldown_amount;
if(current_time < expiration_time){
const time_left = (expiration_time - current_time) / 1000;
return message.reply(`Please wait ${time_left.toFixed(1)} more seconds before using ${command.name}`);
}
}
//If the author's id is not in time_stamps then add them with the current time.
time_stamps.set(message.author.id, current_time);
//Delete the user's id once the cooldown is over.
setTimeout(() => time_stamps.delete(message.author.id), cooldown_amount);
}
try{
command.execute(message,args, cmd, client, Discord, CurrentTimers);
} catch (err){
message.reply("There was an error trying to execute this command!");
console.log(err);
}
}
You didn’t show the actual error but I suspect that it is something like Cannot read property 'id' of undefined. The way to fix this is to make sure of 2 things:
Make sure the message is not in DM
Make sure your execution parameters are passed in correctly.
command.execute(client, message, args, CurrentTimers)
//these may not be the same variable names, but make sure the values are correct
Here is my entire code for my ban command. Good to note I am using Discord.JS Commando as well I have been struggling with this error but literally cannot figure out why I am getting it everything looks fine unless I have used a deprecated function. Would really appreciate someone to help me on this one I've been getting along quite well creating a rich featured bot before this happened.
const { Command } = require('discord.js-commando');
const { MessageEmbed } = require('discord.js');
const db = require('quick.db');
module.exports = class banCommand extends Command {
constructor(client) {
super(client, {
name: 'ban',
memberName: "ban",
group: 'moderation',
guildOnly: true,
userPermissions: ['BAN_MEMBERS'],
description: 'Bans the mentioned user from the server with additional modlog info.'
});
}
async run(message, args) {
if (!args[0]) return message.channel.send('**Please Provide A User To Ban!**')
let banMember = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find(r => r.user.username.toLowerCase() === args[0].toLocaleLowerCase()) || message.guild.members.cache.find(ro => ro.displayName.toLowerCase() === args[0].toLocaleLowerCase());
if (!banMember) return message.channel.send('**User Is Not In The Guild**');
if (banMember === message.member) return message.channel.send('**You Cannot Ban Yourself**')
var reason = args.slice(1).join(' ');
if (!banMember.bannable) return message.channel.send('**Cant Kick That User**')
banMember.send(`**Hello, You Have Been Banned From ${message.guild.name} for - ${reason || 'No Reason'}**`).then(() =>
message.guild.members.ban(banMember, { days: 7, reason: reason })).catch(() => null)
message.guild.members.ban(banMember, { days: 7, reason: reason })
if (reason) {
var sembed = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned for ${reason}`)
message.channel.send(sembed)
} else {
var sembed2 = new MessageEmbed()
.setColor('GREEN')
.setAuthor(message.guild.name, message.guild.iconURL())
.setDescription(`**${banMember.user.username}** has been banned`)
message.channel.send(sembed2)
}
let channel = db.fetch(`modlog_${message.guild.id}`)
if (channel == null) return;
if (!channel) return;
const embed = new MessageEmbed()
.setAuthor(`${message.guild.name} Modlogs`, message.guild.iconURL())
.setColor('#ff0000')
.setThumbnail(banMember.user.displayAvatarURL({ dynamic: true }))
.setFooter(message.guild.name, message.guild.iconURL())
.addField('**Moderation**', 'ban')
.addField('**Banned**', banMember.user.username)
.addField('**ID**', `${banMember.id}`)
.addField('**Banned By**', message.author.username)
.addField('**Reason**', `${reason || '**No Reason**'}`)
.addField('**Date**', message.createdAt.toLocaleString())
.setTimestamp();
var sChannel = message.guild.channels.cache.get(channel)
if (!sChannel) return;
sChannel.send(embed)
}
};
The reason you are getting the TypeError: args.slice(...).join is not a function error is because the slice method creates a new array of the sliced data, and so can not join(' ') since there is no space to join with. (i.e. it is not a string)
What you are looking for is args.slice(1).toString().replace(",", " ")
This removes the 2nd part of the args array object, then converts it to a string, then removes the commas in the string and replaces them with spaces.