You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Node.js+Discord.js为Discord服务器创建每周定时活动

问题:为Discord.js机器人添加每周定时活动功能

我使用Discord.js SDK开发了一款Discord机器人,希望为其添加每周创建定时活动的功能。查阅Discord.js官方指南与Discord API文档后,仍未找到实现方法,特此寻求技术提示。

机器人主文件代码

require('dotenv').config();

const {
    Client,
    Events,
    GatewayIntentBits,
    ActionRowBuilder,
    ButtonBuilder,
    ButtonStyle,
    Message,
    Thread,
    channelMention,
    MessageActionRow,
    MessageButton,
    ChannelType,
    GuildScheduledEvent,
    GuildScheduledEventManager    
} = require('discord.js');

const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
        GatewayIntentBits.GuildMessageReactions,
        GatewayIntentBits.GuildMembers,
        GatewayIntentBits.GuildScheduledEvents
    ],
    presence: {
        activities: [{
            name: "Aqui é a casa do Playstation!",
            type: 0
        }],
        status: 'dnd'
    }    
});

const util = require('util');
const axios = require('axios');
const cron = require('node-cron');
const { stringify } = require('querystring');

const messages = require('./handlers/messages')
const startBot = require('./modules/startBot')

let rulesChannel = ''
var tentativas = {}

const AuthenticationToken = process.env.DISCORD_TOKEN;
if (!AuthenticationToken) {
    console.warn("[CRASH] Authentication Token for Discord bot is required! Use Envrionment Secrets or config.js.".red)
    return process.exit();
};

// Login to the bot:
client.login(AuthenticationToken)
    .catch((err) => {
        console.error("[CRASH] Something went wrong while connecting to your bot...");
        console.error("[CRASH] Error from Discord API:" + err);
        return process.exit();
    });

// Handle errors:
process.on('unhandledRejection', async (err, promise) => {
    console.error(`[ANTI-CRASH] Unhandled Rejection: ${err}`.red);
    console.error(promise);
});

//importar modulos
const { handleMessage } = require('./modules/messageHandler');

const { token, noobId, serverId, botId, urlRegex, rulesChannelId, generalChatId } = require('./config')

startBot(client)
messages(client)

我尝试的代码

client.GuildScheduledEventManager.create({
    name: 'teste',
    scheduledStartTime: '1690745648000',
    privacyLevel:'GuildOnly',
    entityType: '2',
})

解决方案

你尝试的代码存在几个关键问题,以下是修正后的实现方案:

问题点分析

  1. 调用对象错误:client.GuildScheduledEventManager是类而非实例,必须通过具体的服务器(Guild)实例调用活动管理器,即guild.scheduledEvents
  2. 参数格式错误:
    • scheduledStartTime 需要传入Date对象或数字类型的时间戳,不能是字符串
    • privacyLevel和entityType应该使用Discord.js提供的枚举常量,而非字符串或原始数字
  3. 缺少必要参数:创建语音类活动时,必须指定entityMetadata.channelId,同时建议添加scheduledEndTime明确活动时长

完整实现代码

结合你已引入的node-cron,可以实现每周定时创建活动:

// 先导入需要的枚举(如果没导入的话)
const { PrivacyLevel, EntityType } = require('discord.js');

// 在客户端就绪事件中设置定时任务
client.on(Events.ClientReady, async () => {
  console.log(`机器人已登录:${client.user.tag}`);

  // cron表达式:每周日20:00执行(可根据需求调整,比如每周一12点是'0 12 * * 1')
  cron.schedule('0 20 * * 0', async () => {
    // 获取目标服务器
    const guild = client.guilds.cache.get(serverId);
    if (!guild) return console.error('未找到目标服务器');

    try {
      // 计算活动时间:下周同一时间开始,持续2小时
      const startTime = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
      const endTime = new Date(startTime.getTime() + 2 * 60 * 60 * 1000);

      // 创建定时活动
      const event = await guild.scheduledEvents.create({
        name: '每周Playstation游戏夜',
        scheduledStartTime: startTime,
        scheduledEndTime: endTime,
        privacyLevel: PrivacyLevel.GuildOnly, // 仅服务器成员可见
        entityType: EntityType.Voice, // 语音频道活动
        entityMetadata: {
          channelId: '你的语音频道ID', // 替换为实际的语音频道ID
        },
        description: '每周固定游戏聚会,欢迎所有Playstation玩家参与!',
      });

      console.log(`已成功创建定时活动:${event.url}`);
    } catch (error) {
      console.error('创建活动失败:', error);
    }
  });
});

注意事项

  • 确保机器人在目标服务器中拥有管理活动的权限,否则会创建失败
  • 替换代码中的serverId和语音频道ID为实际值
  • cron表达式规则:分 时 日 月 周,可根据需要调整执行时间
  • 如果需要创建其他类型的活动(如舞台频道、外部链接),只需修改entityType和对应的entityMetadata参数

内容的提问来源于stack exchange,提问作者Rafael Tuneca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 09:14:53