我想让我的Discord机器人通过一个简单的命令告诉我当前的日期和时间,所以如果我说"几点了"它会告诉我的。目前我唯一的解决方案是让机器人在谷歌上发送当前时间的链接,但这并不理想,我希望它能在频道中以消息的形式显示。
感谢
您可以使用内置的Date
类生成日期时间字符串。
// inside a command
const currentDate = new Date();
message.channel.send(currentDate);
上面的例子将导致机器人用类似于";2020年12月12日星期六15:40:06 GMT+0100(中欧标准时间(";。
如果您想要一个更人性化的字符串,可以使用toLocaleString()
将其转换为区域设置字符串
message.channel.send(currentDate.toLocaleString());
这将导致类似于";2020年12月12日下午3:41:58";,日期和小时格式取决于您指定的区域设置,如果未指定,则取决于服务器区域设置。
此外,您可以创建两个不同的"时间"one_answers"日期"命令,而不是编写"toLocalString"只写";toLocalDateString"对于日期和";toLocalTimeString"目前。
你可以用你喜欢的语言创建一个discord bot,有多种语言的SDK。此外,还有一些方法可以用多种语言创建日期对象。
以下是Node.JS.中的一个示例
- 如何创建discord机器人Node.JS discord机器人
- 在回复邮件时,创建一个日期对象。在回复中返回
以下是示例代码:
const Discord = require('discord.js')
const client = new Discord.Client()
client.on('ready', () => {
console.log('Bot is now ready to communicate with discord server');
});
client.on('message', (receivedMessage) => {
// Prevent bot from responding to its own messages
if (receivedMessage.author == client.user) {
return
}
// Check if the bot's user was tagged in the message
if (receivedMessage.content.includes(client.user.toString())) {
// Check contents if client wants date
if(receivedMessage.content == '!date') {
let date = new Date();
// Send date
let content = date.getDate() + '/' + date.getMonth() + '/' + date.getFullYear();
receivedMessage.channel.send(content)
}
// Check contents if client wants time
if(receivedMessage.content == '!time') {
let date = new Date();
// Send time
let content = date.getHours() + ':' + date.getMinutes() + ';' + date.getSeconds();
receivedMessage.channel.send(content)
}
}
})
client.login("XXXXXXXXXXX") // Replace XXXXX with your bot token
如果你不想写太多代码,你也可以看看mee6。