Sam*_*ith 5 javascript node.js discord.js
我刚刚开始使用 Javascript 和 Node.js,所以我真的不知道该怎么做。请对我有耐心。谢谢!
所以我在我的物理服务器上托管了一个 node.js。我想创建一个 Discord Bot,它在我的服务器上的特定时间发送每日消息,例如,我想每天早上 8 点向一个频道发送一条消息,说“早安”。我该怎么做?
目前,我只有这个代码来 ping 机器人(和服务器)
/*
A ping pong bot, whenever you send "ping", it replies "pong".
*/
// Import the discord.js module
const Discord = require('discord.js');
// Create an instance of a Discord client
const client = new Discord.Client();
// The token of your bot - https://discordapp.com/developers/applications/me
const token = 'your bot token here';
// The ready event is vital, it means that your bot will only start reacting to information
// from Discord _after_ ready is emitted
client.on('ready', () => {
console.log('I am ready!');
});
// Create an event listener for messages
client.on('message', message => {
// If the message is "ping"
if (message.content === 'ping') {
// Send "pong" to the same channel
message.channel.send('pong');
}
});
// Log our bot in
client.login(token);
Run Code Online (Sandbox Code Playgroud)
另外,我如何循环此代码以确保它每天发送一条消息?提前致谢。
所以有一个答案:
有两种方法可以做到这一点,使用cron(或其他平台上的其他东西)和setInterval
创建一个新文件,goodmorning.js如下:
const Discord = require('discord.js');
const client = new Discord.Client();
client.login("token").then(() => {
console.log("I am ready");
var guild = client.guilds.get('guildid');
if(guild && guild.channels.get('channelid')){
guild.channels.get('channelid').send("Good Morning").then(() => client.destroy());
} else {
console.log("nope");
//if the bot doesn't have guild with the id guildid
// or if the guild doesn't have the channel with id channelid
}
client.destroy();
});
Run Code Online (Sandbox Code Playgroud)
(编辑所有需要的值:token、guildid 和 channelid)
并添加一个 cronjob,每天早上 8 点运行。
此脚本将尝试登录 Discord,成功登录后继续查找公会和频道,然后发送消息,最后退出 ( client.destroy())。如果没有找到公会或频道,只需摧毁即可。
第一个问题是您需要在您希望代码运行的确切时间启动脚本,或者获取 setTimeout 以启动 setInterval 以一遍又一遍地重复代码。
未经测试,但可能需要进行一些调整:
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('message', message => {
//...
});
client.on('ready', () => {
setTimeout(function(){ // in leftToEight() milliseconds run this:
sendMessage(); // send the message once
var dayMillseconds = 1000 * 60 * 60 * 24;
setInterval(function(){ // repeat this every 24 hours
sendMessage();
}, dayMillseconds)
}, leftToEight())
})
function leftToEight(){
var d = new Date();
return (-d + d.setHours(8,0,0,0));
}
function sendMessage(){
var guild = client.guilds.get('guildid');
if(guild && guild.channels.get('channelid')){
guild.channels.get('channelid').send("Good Morning");
}
}
client.login("token");
Run Code Online (Sandbox Code Playgroud)
我肯定会选择cron选项,不需要您一直运行该进程(除非您已经拥有它)
| 归档时间: |
|
| 查看次数: |
39063 次 |
| 最近记录: |