在Discord.NET机器人中监听定时事件的实现方案咨询
在Discord.NET中实现Socket消息监听与Cron定时任务
1. 依赖安装
先通过NuGet安装必要的包:
Discord.Net.WebSocket:Discord Socket客户端核心Quartz:用于Cron风格的定时任务调度
2. 基础Socket客户端初始化与消息监听
Discord.NET已封装WebSocket连接,无需手动处理底层ws逻辑,直接通过客户端事件监听消息:
using Discord.WebSocket; using System; using System.Threading.Tasks; class DiscordBot { private DiscordSocketClient _client; public async Task InitializeAsync() { _client = new DiscordSocketClient(); // 监听收到的消息(等效原JS中ws监听消息逻辑) _client.MessageReceived += OnMessageReceived; // 登录并启动客户端 await _client.LoginAsync(TokenType.Bot, "你的机器人Token"); await _client.StartAsync(); // 保持程序持续运行 await Task.Delay(-1); } private async Task OnMessageReceived(SocketMessage message) { // 忽略机器人自身发送的消息 if (message.Author.IsBot) return; // 自定义消息处理逻辑示例 Console.WriteLine($"收到消息:{message.Content}"); if (message.Content.Equals("!ping", StringComparison.OrdinalIgnoreCase)) { await message.Channel.SendMessageAsync("Pong!"); } } }
3. Cron定时任务实现(定时发送消息)
使用Quartz.NET实现Cron表达式驱动的定时任务,定时向指定Discord频道发送消息:
定义定时任务类
using Discord.WebSocket; using Quartz; using System.Threading.Tasks; public class SendDiscordMessageJob : IJob { private readonly DiscordSocketClient _client; private readonly ulong _targetChannelId; public SendDiscordMessageJob(DiscordSocketClient client, ulong targetChannelId) { _client = client; _targetChannelId = targetChannelId; } public async Task Execute(IJobExecutionContext context) { var channel = _client.GetChannel(_targetChannelId) as SocketTextChannel; if (channel != null) { await channel.SendMessageAsync("这是定时发送的消息!"); } } }
配置并启动调度器
在DiscordBot类中添加调度器初始化逻辑:
using Quartz; using Quartz.Impl; public async Task StartSchedulerAsync(ulong targetChannelId) { // 创建调度器工厂与实例 var schedulerFactory = new StdSchedulerFactory(); var scheduler = await schedulerFactory.GetScheduler(); await scheduler.Start(); // 定义定时任务 var job = JobBuilder.Create<SendDiscordMessageJob>() .UsingJobData("TargetChannelId", targetChannelId) .Build(); // 配置Cron触发器(示例:每天12点发送,可替换为自定义Cron表达式) var trigger = TriggerBuilder.Create() .WithCronSchedule("0 0 12 * * ?") .Build(); // 绑定任务与触发器到调度器 await scheduler.ScheduleJob(job, trigger); }
整合到Bot初始化流程
修改InitializeAsync方法,启动定时任务:
public async Task InitializeAsync() { _client = new DiscordSocketClient(); _client.MessageReceived += OnMessageReceived; await _client.LoginAsync(TokenType.Bot, "你的机器人Token"); await _client.StartAsync(); // 启动定时任务,传入目标频道ID await StartSchedulerAsync(123456789012345678); // 替换为实际频道ID await Task.Delay(-1); }
关键说明
- Discord.NET自动维护WebSocket连接,无需手动处理
ws库的连接、重连等逻辑,通过客户端事件即可监听消息。 - Quartz.NET是.NET生态中成熟的定时任务框架,完全支持Cron表达式,替代原JS中的cron任务脚本。
- 确保机器人Token拥有目标频道的消息发送权限,频道ID可通过Discord开发者模式获取。
内容的提问来源于stack exchange,提问作者muttley91
相关产品推荐
相关产品推荐

