【发布时间】:2019-10-20 11:54:03
【问题描述】:
我想制作一个每 10 秒左右改变一次的播放状态,我知道如何在 JS 中做到这一点,但在 C# 中却不知道。有没有办法做到这一点,如果有,你是怎么做到的?
我一直在考虑是否可以尝试 for 循环,但我不知道它会如何工作。
【问题讨论】:
标签: c# .net bots discord discord.net
我想制作一个每 10 秒左右改变一次的播放状态,我知道如何在 JS 中做到这一点,但在 C# 中却不知道。有没有办法做到这一点,如果有,你是怎么做到的?
我一直在考虑是否可以尝试 for 循环,但我不知道它会如何工作。
【问题讨论】:
标签: c# .net bots discord discord.net
您可以通过多种方式完成此操作,首先我建议您研究一个简单的 Timer 类。 .NET Timer Doc
根据上面的文档,你可以制作一个简单的控制台应用
private static Timer timer;
private static List<string> status => new List<string>() { "Status1", "Status2", "Status3", "Status4" };
private static int currentStatus = 0;
static void Main(string[] args)
{
CreateTimer();
Console.ReadLine();
timer.Stop();
timer.Dispose();
}
private static void CreateTimer()
{
timer = new Timer(10000);
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;
}
private static async void OnTimedEvent(Object source, ElapsedEventArgs e)
{
DiscordSocketClient client = new DiscordSocketClient(new DiscordSocketConfig()
{
//Set config values, most likely API Key etc
});
await client.SetGameAsync("Game Name", status.ElementAtOrDefault(currentStatus), ActivityType.Playing);
currentStatus = currentStatus < status.Count - 1 ? currentStatus +=1 : currentStatus = 0;
}
OnTimedEvent 函数显示了一个快速示例,您可以如何使用 discord.net 库来做某事。
【讨论】:
您可以利用System.Threading.Timer 来实现此目的。
//add this namespace
using System.Threading;
//create your Timer
private Timer _timer;
//create your list of statuses and an indexer to keep track
private readonly List<string> _statusList = new List<string>() { "first status", "second status", "another status", "last?" };
private int _statusIndex = 0;
您可以使用 ready 事件来开始。只需在 DiscordSocketClient 上订阅 Ready 事件
private Task Ready()
{
_timer = new Timer(async _ =>
{//any code in here will run periodically
await _client.SetGameAsync(_statusList.ElementAtOrDefault(_statusIndex), type: ActivityType.Playing); //set activity to current index position
_statusIndex = _statusIndex + 1 == _statusList.Count ? 0 : _statusIndex + 1; //increment index position, restart if end of list
},
null,
TimeSpan.FromSeconds(1), //time to wait before executing the timer for the first time (set first status)
TimeSpan.FromSeconds(10)); //time to wait before executing the timer again (set new status - repeats indifinitely every 10 seconds)
return Task.CompletedTask;
}
【讨论】: