我想使播放状态每 10 秒左右更改一次,我知道如何在 JS 中做到这一点,但在 C# 上却不知道。有没有办法做到这一点,如果有,你怎么做?
我一直在想也许尝试一个for
循环,但我不知道这将如何工作。
您可以利用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;
}
有很多
方法可以实现这一点,首先我建议研究一个简单的 Timer 类。网络计时器文档
根据上面的文档,您可以制作一个简单的控制台应用程序
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 库执行某些操作的快速示例。