C#Discord.netbot-如何每X小时发布一次消息?

C#Discord.netbot-如何每X小时发布一次消息?,c#,discord.net,C#,Discord.net,我正在用C#和discord.netAPI编写一个discord机器人 我想知道我是否能得到一些关于如何让我的机器人每6小时在频道上发布一条消息的建议 堆栈溢出所需的详细信息: 我已经设置好了命令。我遵循了一个教程,找到了一些代码来达到这个目的。我知道我必须使用计时器,但我不确定如何将其连接到discord.NETAPI中 多谢各位 这是我到目前为止的代码 Program.cs 使用Discord; 使用不协调命令; 使用Discord.WebSocket; 使用Newtonsoft.Json

我正在用C#和discord.netAPI编写一个discord机器人

我想知道我是否能得到一些关于如何让我的机器人每6小时在频道上发布一条消息的建议

堆栈溢出所需的详细信息:

我已经设置好了命令。我遵循了一个教程,找到了一些代码来达到这个目的。我知道我必须使用计时器,但我不确定如何将其连接到discord.NETAPI中

多谢各位

这是我到目前为止的代码

Program.cs

使用Discord;
使用不协调命令;
使用Discord.WebSocket;
使用Newtonsoft.Json;
使用制度;
使用System.IO;
运用系统反思;
使用System.Threading.Tasks;
使用Microsoft.Extensions.DependencyInjection;
使用SQLitePCL;
名字空间祈祷者
{
班级计划
{
静态void Main(字符串[]args)=>new Program().RunBot().GetAwaiter().GetResult();
//创建必要的变量
公共静态DiscordSocketClient _client;
私有命令服务(private CommandService)命令;;
私人IServiceProvider服务;
私有BotConfig配置;
//Runbot任务
公共异步任务RunBot()
{
_client=new DiscordSocketClient();//定义_client
_commands=newcommandservice();//定义_命令
_services=newServiceCollection()//定义_服务
.AddSingleton(_客户端)
.AddSingleton(_命令)
.BuildServiceProvider();
config=JsonConvert.DeserializeObject(File.ReadAllText(“config.json”);
string botToken=config.token;//为令牌创建一个字符串
_client.Log+=Log;//日志记录
等待RegisterCommandsAsync();//调用registercommands
wait _client.LoginAsync(TokenType.Bot,botToken);//登录到Bot用户
等待_client.StartAsync();//启动bot用户
wait _client.SetGameAsync(config.game);//设置机器人正在玩的游戏
wait Task.Delay(-1);//延迟-1以保持控制台窗口打开
}
专用异步任务注册表CommandsAsync()
{
_client.MessageReceived+=HandleCommandAsync;//MessageReceived
wait _commands.AddModulesAsync(Assembly.GetEntryAssembly(),null);//将模块添加到_命令
}
专用任务日志(LogMessage arg)//日志记录
{
Console.WriteLine(arg);//将日志打印到控制台
return Task.CompletedTask;//返回CompletedTask
}
专用异步任务HandleCommandAsync(SocketMessage参数)
{
字符串messageLower=arg.Content.ToLower();//将消息转换为较低的值
var message=arg as SocketUserMessage;//创建一个变量,该变量的消息为SocketUserMessage
if(message为null | | message.Author.IsBot)return;//检查消息是空的还是由bot发送的
int argumentPos=0;//将argpos设置为0(消息的开头)
if(message.HasStringPrefix(config.prefix,ref argumentPos)| | | message.hasAttentionPrefix(_client.CurrentUser,ref argumentPos))//如果消息的开头有前缀,或者开头有人提到bot
{
var context=new SocketCommandContext(_client,message);//创建一个名为context的变量
var result=await _commands.ExecuteAsync(context,argumentPos,_services);//创建一个可验证的调用结果
if(!result.issucess)//如果结果不成功
{
Console.WriteLine(result.ErrorReason);//将错误打印到Console
wait message.Channel.SendMessageAsync(result.ErrorReason);//将错误打印到导致错误的通道(例如“未知命令”)
}
}
}
}
类BotConfig
{
公共字符串标记{get;set;}
公共字符串前缀{get;set;}
公共字符串游戏{get;set;}
}
}
Commands.cs

使用Discord.Commands;
使用Microsoft.Data.Sqlite;
使用制度;
使用System.Threading.Tasks;
名字空间祈祷者
{
公共类命令:ModuleBase
{
[命令(“ping”)]
专用异步任务Ping()
{

等待replySync(“Pong!您需要在代码中使用一个简单的计时器:

using Discord;
using Discord.Commands;
using Discord.WebSocket;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using SQLitePCL;
 
namespace PrayerBot
{
    class Program
    {
        static void Main(string[] args) => new Program().RunBot().GetAwaiter().GetResult();
 
        // Creating the necessary variables
        public static DiscordSocketClient _client;
        private CommandService _commands;
        private IServiceProvider _services;
 
        private BotConfig config;
 
        // Runbot task
        public async Task RunBot()
        {
            _client = new DiscordSocketClient(); // Define _client
            _commands = new CommandService(); // Define _commands
 
            _services = new ServiceCollection() // Define _services
                .AddSingleton(_client)
                .AddSingleton(_commands)
                .BuildServiceProvider();
 
            config = JsonConvert.DeserializeObject<BotConfig>(File.ReadAllText("config.json"));
 
            string botToken = config.token; // Make a string for the token
 
            _client.Log += Log; // Logging
 
            await RegisterCommandsAsync(); // Call registercommands
 
            await _client.LoginAsync(TokenType.Bot, botToken); // Log into the bot user
 
            await _client.StartAsync(); // Start the bot user
 
            await _client.SetGameAsync(config.game); // Set the game the bot is playing
 
            await Task.Delay(-1); // Delay for -1 to keep the console window opened
        }
 
        private async Task RegisterCommandsAsync()
        {
            _client.MessageReceived += HandleCommandAsync; // Messagerecieved
 
            await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), null); // Add module to _commands
        }
 
        private Task Log(LogMessage arg) // Logging
        {
            Console.WriteLine(arg); // Print the log to Console
            return Task.CompletedTask; // Return with completedtask
        }
 
        private async Task HandleCommandAsync(SocketMessage arg)
        {
            string messageLower = arg.Content.ToLower(); // Convert the message to a Lower
            var message = arg as SocketUserMessage; // Create a variable with the message as SocketUserMessage
            if (message is null || message.Author.IsBot) return; // Checks if the message is empty or sent by a bot
            int argumentPos = 0; // Sets the argpos to 0 (the start of the message)
            if (message.HasStringPrefix(config.prefix, ref argumentPos) || message.HasMentionPrefix(_client.CurrentUser, ref argumentPos)) // If the message has the prefix at the start or starts with someone mentioning the bot
            {
                var context = new SocketCommandContext(_client, message); // Create a variable called context
                var result = await _commands.ExecuteAsync(context, argumentPos, _services); // Create a veriable called result
                if (!result.IsSuccess) // If the result is unsuccessful
                {
                    Console.WriteLine(result.ErrorReason); // Print the error to console
                    await message.Channel.SendMessageAsync(result.ErrorReason); // Print the error to the channel where the error was caused (e.g "Unknown Command")
                }
            }
        }
    }
 
    class BotConfig
    {
        public string token { get; set; }
        public string prefix { get; set; }
        public string game { get; set; }
    }
}
using Discord.Commands;
using Microsoft.Data.Sqlite;
using System;
using System.Threading.Tasks;
 
namespace PrayerBot
{
    public class Commands : ModuleBase<SocketCommandContext>
    {
        [Command("ping")]
        private async Task Ping()
        {
            await ReplyAsync("Pong! You need to use a simple timer in your code:

myTimer = new System.Timers.Timer(6 * 60 * 60 * 1000); //calculate six hours in milliseconds
myTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
myTimer.Start();

private static void OnTimedEvent(object sender, ElapsedEventArgs e)
{
    YourMethod();
}