我一直在为Discord Bot编写轮询命令。它在Discord.JS中,但是当我要运行命令时,它会出现以下错误:
一段时间以来,我一直在尝试解决此问题,但仍会解决此问题。我更改了一些代码行,尤其是65行和70-80行。
代码:
const options = [
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'',
];
const pollLog = {};
function canSendPoll(user_id) {
if (pollLog[user_id]) {
const timeSince = Date.now() - pollLog[user_id].lastPoll;
if (timeSince < 1) {
return false;
}
}
return true;
}
exports.run = async (client, message, args, level, Discord) => {
if (args) {
if (!canSendPoll(message.author.id)) {
return message
.channel
.send(`${message.author} please wait before sending another poll.`);
} else if (args.length === 1) { // yes no unsure question
const question = args[0];
pollLog[message.author.id] = {
lastPoll: Date.now()
};
return message
.channel
.send(`${message.author} asks: ${question}`)
.then(async (pollMessage) => {
await pollMessage.react('');
await pollMessage.react('');
await pollMessage.react(message.guild.emojis.get('475747395754393622'));
});
} else { // multiple choice
args = args.map(a => a.replace(/"/g, ''));
const question = args[0];
const questionOptions = message.content.match(/"(.+?)"/g);
if (questionOptions.length > 20) {
return message.channel.send(`${message.author} Polls are limited to 20 options.`);
} else {
pollLog[message.author.id] = {
lastPoll: Date.now()
};
return message
.channel
.send(`${message.author} asks: ${question}
${questionOptions
.map((option, i) => `${options[i]} - ${option}`).join('\n')}
`)
.then(async (pollMessage) => {
for (let i = 0; i < questionOptions.length; i++) {
await pollMessage.react(options[i]);
}
});
}
}
} else {
return message.channel.send(`**Poll |** ${message.author} invalid Poll! Question and options should be wrapped in double quotes.`);
}
}
答案 0 :(得分:0)
将某些问题列为选择项的原因是因为您将question
定义为args[0]
,这只是给出的第一个单词。您可以通过循环遍历所有参数并添加那些似乎不是问题的选择来解决此问题。请参见下面的示例代码。
const args = message.content.trim().split(/ +/g);
// Defining the question...
let question = [];
for (let i = 1; i < args.length; i++) {
if (args[i].startsWith('"')) break;
else question.push(args[i]);
}
question = question.join(' ');
// Defining the choices...
const choices = [];
const regex = /(["'])((?:\\\1|\1\1|(?!\1).)*)\1/g;
let match;
while (match = regex.exec(args.join(' '))) choices.push(match[2]);
// Creating and sending embed...
let content = [];
for (let i = 0; i < choices.length; i++) content.push(`${options[i]} ${choices[i]}`);
content = content.join('\n');
var embed = new Discord.RichEmbed()
.setColor('#8CD7FF')
.setTitle(`**${question}**`)
.setDescription(content);
message.channel.send(`:bar_chart: ${message.author} started a poll.`, embed)
.then(async m => {
for (let i = 0; i < choices.length; i++) await m.react(options[i]);
});
使用的正则表达式来自this answer(包括说明)。它删除了周围的引号,允许使用转义的引号等,但是需要诸如this之类的解决方案才能访问所需的捕获组。
请注意,您仍然必须检查是否有问题以及是否存在选择,并根据需要显示任何错误。