[英]discord.js - How to randomly split messages between mentioned users?
我正在嘗試制作系統,該系統將 dm 提到消息的用戶和作者,每個消息都有一條隨機消息*。 但我想知道是否有更簡單的方法,然后使用if 。
*例子:
用戶名作者:Test2
用戶名提及[0]:Test4
用戶名提及[1]:Test1
用戶名提及[2]:Test3
(只是不會發生某人與其他人有相同的信息)
const userNameAuthor = message.author;
const userNameMentioned = message.mentions.users.map(u => u);
let replies1 = [
"Test1",
"Test2",
"Test3",
"Test4",
];
let replies2 = [
"Test1",
"Test2",
"Test3",
"Test4",
];
let replies3 = [
"Test1",
"Test2",
"Test3",
"Test4",
];
let replies4 = [
"Test1",
"Test2",
"Test3",
"Test4",
];
let result1 = Math.floor((Math.random() * replies1.length));
let result2 = Math.floor((Math.random() * replies2.length));
let result3 = Math.floor((Math.random() * replies3.length));
let result4 = Math.floor((Math.random() * replies4.length));
userNameAuthor.send(replies1[result1])
userNameMentioned[0].send(replies2[result2])
userNameMentioned[1].send(replies3[result3])
userNameMentioned[2].send(replies4[result4])
實現目標的一種更規范、更簡單的方法是使用Array#splice()
方法,該方法刪除或替換數組中預設數量的元素,並可選擇用另一個元素替換它們(不必要的東西在此刻)。
在您的代碼中,我們可以形成一個forEach()
迭代器來遍歷提到的成員,向他們發送隨機消息,並從我們的數組中刪除相同的消息。
const mentioned = message.mentions.users
let replies = [
'test1',
'test2',
'test3',
'test4'
]
mentioned.forEach(user => {
const random = Math.floor(Math.random() * replies.length)
user.send(replies[random])
replies.splice(random, 1) // Removes the element from the array
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.