discord.js prefix throwing error without command - discord.js

So my bots prefix is ., whenever a user just sends . the bot responds with there was an error trying to execute that command! Which is very annoying. I can not figure out how to get it to not respond to the . with the error
This line should be preventing that, but it is not const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName)); if (!command) return;
client.on("message", message => {
const prefixes = ['.'];
const prefix = prefixes.find(p => message.content.startsWith(p));
if (!prefix) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (command.guildOnly && message.channel.type === 'dm') {
return message.reply('I can\'t execute that command inside DMs!');
}
if (command.permissions) {
const authorPerms = message.channel.permissionsFor(message.author);
if (!authorPerms || !authorPerms.has(command.permissions)) {
return message.reply('You can not do this!');
}
}
if (command.args && !args.length) {
let reply = `You didn't provide any arguments, ${message.author}!`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
const { cooldowns } = client;
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown || 0) * 1000;
if (timestamps.has(message.guild.id)) {
const expirationTime = timestamps.get(message.guild.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command.name}\` command.`);
}
}
timestamps.set(message.guild.id, now);
setTimeout(() => timestamps.delete(message.guild.id), cooldownAmount);
try {
command.execute(client, message, args, Discord);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});```

You should try checking, if the message is longer than the prefix itself, try changing const prefix to this:
const prefix = prefixes.find(p => message.content.startsWith(p) && message.content.length>p.length);

Related

TypeError: client.execute is not a function

most if not all commands start to not work.
not sure what type of code i should have put it in so i put it in css
What comes out
The code
client.on("message", (message) => {
if (message.author.bot) return;
if (!message.guild) return;
const prefixRegex = new RegExp(`^(<#!?${client.user.id}>|${escapeRegex(config.prefix)})\\s*`);
if (!prefixRegex.test(message.content)) return;
const [, matchedPrefix] = message.content.match(prefixRegex);
const args = message.content.slice(matchedPrefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command =
client.commands.get(commandName) ||
client.commands.find((cmd) => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown || 1) * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(
`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command.name}\` command.`
);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply("There was an error executing that command.").catch(console.error);
}
});
Just having problems with finding a better function for replacement of command.execute
please and thank you it would be the world for me.
client.commands.get(commandName).execute(message, args);
replace command.execute(message, args); with this^ and it should work.
If that doesnt work i suggest you put
if (command.args && !args.length) {
let reply = `You didn't provide any arguments, ${message.author}!`;
}
return message.channel.send(reply);
}
right before the if (!command) return
Hope this helps and please correct me if said anything wrong

How to convert a componentDidUpdate to useEffect when prevProps are used in a nested if/else statement?

I'm not sure how to convert this section to fit into a useEffect. I can't pull the prevProps conditional out since it should only run within the loop. I dont think I can just add the props to dependency array either, as I need to do something else whenever selectedCurrency does not change.
public componentDidUpdate(prevProps: Readonly<Props>): void {
if (api != null) {
const MyData: {}[] = [];
api.forEach(el=> {
if (!el.data) {
return;
}
if (selectedCurrency === "") {
el.setDataValue("val1", "-");
el.setDataValue("val2", "-");
el.setDataValue("val3", "-");
el.setDataValue("val4", "-");
} else {
const originalCcy = el.data.Currency;
const exchangeRate = referenceCurrencies
.filter(x => x.originalCurrency === originalCcy)
.flatMap(value => value.conversionCurrencies)
.find(value => value.currency === selectedCurrency);
const middleMarketRate = exchangeRate ? exchangeRate.middleMarketRate : 1;
el.setDataValue("val2", el.data.val2 * middleMarketRate);
el.setDataValue(
"val3",
el.data.val3 * middleMarketRate
);
el.setDataValue("val1", middleMarketRate);
if (
prevProps.dateFrom === dateFrom &&
prevProps.dateTo === dateTo &&
prevProps.selectedCurrency !== selectedCurrency
) {
const dateToMoment = moment(dateTo);
const dateFromMoment = moment(dateFrom);
const totalValBalCols = dateToMoment.diff(dateFromMoment, "days");
for (let i = 0; i <= totalValBalCols; i += 1) {
const dayDiff = i;
const currentDate = moment(dateFrom)
.add(dayDiff, "days")
.format("DD-MMM-YYYY");
el.setDataValue(
"refCol",
el.data[currentDate]
);
}
} else {
MyData.push(el.data);
}
}
});
}
}
You can use useRef() to hold the previous props, with a 2nd useEffect() to update preProps.current after you check if anything changed.
Example (not tested):
const prevProps = useRef();
useEffect(() => {
// skip the effect since this is the initial render
if(!prevProps.current) return;
api?.forEach(el => {
if (!el.data) return;
if (selectedCurrency === "") {
// Do something
return;
}
if (
prevProps.current.dateFrom === dateFrom &&
prevProps.current.dateTo === dateTo &&
prevProps.current.selectedCurrency !== selectedCurrency
) {
//Do something
return;
}
//Do something else
});
}, [api, dateFrom, dateTo, selectedCurrency]);
useEffect(() => { prevProps.current = props; })

clearinterval is not working in react typescript

i am struggling in clearInterval function for typescript in react, don't know why it is not clearing interval, for that i have defined variable let interval_counter; and this variable i using as this interval_counter = setInterval(interval,1000); , but when i used clearInterval(interval_counter);, it is not working for me, here i have put my whole code, can anyone please look my code and help me to resolve this issue ? any help will be really appreciated.
interface Props {
gameId: string;
}
let interval_counter;
export const GameInner: React.FC<Props> = (
{
gameId,
}
) => {
const gameData = useDataStore(GameDataStore);
const userData = useDataStore(UserDataStore);
const chatData = useDataStore(ChatDataStore);
const params = useParams<{ throwaway?: string }>();
const history = useHistory();
const [updateShowTimer, setUpdateShowTimer] = React.useState('02:00');
const [isCalled, setIsCalled] = React.useState<any>('0');
let setSeconds = 30;
//const interval_counter = React.useRef<any>();
//React.createRef<any>();
const {
dateCreated,
started,
chooserGuid,
ownerGuid,
spectators,
pendingPlayers,
players,
settings,
kickedPlayers
} = gameData.game ?? {};
const {
playerGuid
} = userData;
const iWasKicked = !!kickedPlayers?.[playerGuid];
const amInGame = playerGuid in (players ?? {});
const skipPlayer = (game_string_id: any, target_turn: any, chooserGuid: any) => {
return GameDataStore.skipPlayer(game_string_id, target_turn, chooserGuid);
}
const interval = () => {
let timer = setSeconds, minutes, seconds;
let chooserGuid = localStorage.getItem('chooserGuid');
let game_string_id = localStorage.getItem('game_id');
let target_turn = localStorage.getItem('target_turn');
let is_called = localStorage.getItem('is_called');
if (typeof timer !== undefined && timer != null) {
minutes = parseInt(timer / 60 as any, 10);
seconds = parseInt(timer % 60 as any, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
//console.log("test");
console.log(minutes + ":" + seconds);
setUpdateShowTimer(minutes+":"+seconds);
if (timer == 0) {
if(gameData?.game?.roundStarted) {
} else {
skipPlayer(game_string_id, target_turn, chooserGuid);
}
clearInterval(interval_counter);
}
if (--timer < 0) {
clearInterval(interval_counter);
}
setSeconds -= 1;
}
}
const startTimer = () => {
console.log("called again");
interval_counter = setInterval(interval,1000);
}
const isOwner = ownerGuid === userData.playerGuid;
const isChooser = playerGuid === chooserGuid;
const amSpectating = playerGuid in { ...(spectators ?? {}), ...(pendingPlayers ?? {}) };
const playerGuids = Object.keys(players ?? {});
const roundsToWin = getTrueRoundsToWin(gameData.game as ClientGameItem);
const winnerGuid = playerGuids.find(pg => (players?.[pg].wins ?? 0) >= roundsToWin);
const inviteLink = (settings?.inviteLink?.length ?? 0) > 25
? `${settings?.inviteLink?.substr(0, 25)}...`
: settings?.inviteLink;
const meKicked = kickedPlayers?.[playerGuid];
const tablet = useMediaQuery('(max-width:1200px)');
const canChat = (amInGame || amSpectating) && moment(dateCreated).isAfter(moment(new Date(1589260798170)));
const chatBarExpanded = chatData.sidebarOpen && !tablet && canChat;
/**********************************************/
if(gameData?.game?.players && gameData?.game?.id) {
let game_id = gameData.game.id;
let all_players = gameData.game.players;
let all_player_id = Object.keys(all_players);
let filteredAry = all_player_id.filter(e => e !== userData.playerGuid);
console.log("user player guid:"+userData.playerGuid);
console.log("guid:"+chooserGuid);
console.log("all players:"+all_player_id);
console.log("new array:"+filteredAry);
let target_item = filteredAry.find((_, i, ar) => Math.random() < 1 / (ar.length - i));
if(typeof target_item !== undefined && target_item!=null) {
localStorage.setItem('target_turn',target_item);
}
localStorage.setItem('is_started','0');
if(typeof game_id !== undefined && game_id!=null) {
localStorage.setItem('game_id',game_id);
}
if(typeof chooserGuid !== undefined && chooserGuid!=null) {
localStorage.setItem('chooserGuid',chooserGuid);
}
if(isChooser) {
if(isCalled == '0') {
setIsCalled("1");
startTimer();
}
} else {
clearInterval(interval_counter);
}
if(gameData?.game?.roundStarted) {
console.log("round is started");
clearInterval(interval_counter);
}
}
/********************************************/
return (
<div style={{ maxWidth: chatBarExpanded ? "calc(100% - 320px)" : "100%" }}>
</div>
);
};
I believe your problem will be solved when you store your interval also in state.
const [interval, setInterval] = useState(null as NodeJS.Timeout | null);

how can i call method dynamically in react hooks

In my React hooks I defined two functions for setting variables:
setProjectMiddleCode
and setProjectToolCode.
I hope to call this two method in my react hooks to avoid duplicate code.
I would like to do it like this:
//variable define
let data;
let index = res.data.indexOf(res.code.value);
//call dynamic
if(some state ==='A'){
data= "setProjectMiddleCode"
}else{
data = "setProjectToolCode"
}
if (index < 0) {
this[data](res.data.concat(res.code.value));
} else {
this[data](res.data.filter((_, i) => i !== index));
}
My current code:
const [projectMiddleCode, setProjectMiddleCode] = useState([]);
const [projectToolCode, setProjectToolCode] = useState([]);
const ProjectWrite = memo(({}) => {
let component;
const dispatch = useDispatch();
const [projectMiddleCode, setProjectMiddleCode] = useState([]);
const [projectToolCode, setProjectToolCode] = useState([]);
const callbackFromChild = useCallback(
res => () => {
let index = res.data.indexOf(res.code.value);
if (res.codeName === 'PROJECT_MIDDLE_CODE') {
if (index < 0) {
setProjectMiddleCode(res.data.concat(res.code.value));
} else {
setProjectMiddleCode(res.data.filter((_, i) => i !== index));
}
} else if (res.codeName === 'TOOL_LIST') {
if (index < 0) {
setProjectToolCode(res.data.concat(res.code.value));
} else {
setProjectToolCode(res.data.filter((_, i) => i !== index));
}
}
},
[]
);
One way to do this is to create a map of res.codeName to your functions:
const { codeName, code, data } = res;
const index = data.indexOf(code.value);
const funcMap = {
PROJECT_MIDDLE_CODE: setProjectMiddleCode,
TOOL_LIST: setProjectToolCode
}
const newData = index < 0 ? data.concat(code.value) : data.filter((_, i) => i !== index);
const func = funcMap[codeName];
func(newData);

Run code after state update

I have this function, it's registered on click.
mobileZoomClick () {
const elem = this.state.scale.carousel
if (this.state.zoom && elem.scale < 1.1) {
this.zoomOut()
}
}
<div ref='carousel'
onClick={this.mobileZoomClick.bind(this)}
className='carousel' style={this.fullscreen('carousel')}
test={this.state.carouselTransition === 'transitionEnd' && !this.state.zoom && this.flickity()}
>
I would like to add this.flickity() into the function:
mobileZoomClick () {
const elem = this.state.scale.carousel
if (this.state.zoom && elem.scale < 1.1) {
this.zoomOut()
}
if(this.state.carouselTransition === 'transitionEnd' && !this.state.zoom){
this.flickity()
}
}
but I need it to be updated on state-change. The current solution technically works but throws an error.
this is how the new states are set (this first one is for checking if certain elements are in a css transition:
transitionState (target) {
// den här behöver fallback för inte transition
const done = (e) => {
this.setState({[stateName]: 'transitionEnd'}, () => {
this.setState({[stateName]: 'transitionComplete'})
})
e.target.removeEventListener(e.type, done)
}
const elem = this.refs[target]
const stateName = target + 'Transition'
this.setState({[stateName]: 'transitionStarted'})
elem.addEventListener('transitionend', done)
}
this is for zooming out:
zoomOut () { this.setState({zoom: false}) }

Resources