【问题标题】:Schedule telegram bot to send message?安排电报机器人发送消息?
【发布时间】:2020-08-03 20:43:20
【问题描述】:

我不能这样做

public static void myBot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs msg)
{
    if (DateTime.Now.Hour == 01)
    {
        myBot.SendTextMessageAsync(msg.Message.Chat.Id, "Good Night");
    }
}

因为这要求用户首先在该确切时间发送消息,以便他们接收消息。我怎样才能让它自动向任何启动它的人自动发送消息,而无需该人在发送自动消息的确切时间发送消息?

【问题讨论】:

    标签: c# telegram telegram-bot


    【解决方案1】:

    您应该使用 Windows 提供的界面来安排任务。 此外,您应该将用户的 ID 存储在数据库中,并在每次调度任务运行时对其进行迭代。

    你可以在这里Creating Scheduled Tasks找到更多关于C#任务调度的信息

    【讨论】:

      【解决方案2】:

      如果您使用.net core 开发,您可以使用IHostedService 来实现后台任务。还有一个用于计划任务的库。我推荐Hangfire。 它是免费且易于使用的。您可以像这样添加任务:

      var nextDay = DateTime.Now.AddDays(1);
      var sendDate = new DateTime(nextDay.Year, nextDay.Month, nextDay.Day, 1,0,0);
      var jobId = BackgroundJob.Schedule(
         () => myBot.SendTextMessageAsync(msg.Message.Chat.Id, "Good Night");
         (sendDate - DateTime.Now));
      

      使用 Hangfire 需要数据库。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-19
        • 1970-01-01
        • 2017-09-01
        • 2016-03-11
        • 2019-10-30
        • 2019-12-31
        • 2017-05-11
        • 2021-01-29
        相关资源
        最近更新 更多