Как сделать вращающийся игровой статус на Discord.NET - PullRequest
0 голосов
/ 05 июня 2019

Я хочу создать игровой статус, который меняется каждые 10 секунд или около того, я знаю, как это сделать в JS, но не в C #.Есть ли способ сделать это, и если да, то как ты это делаешь?

Я думал, может быть, пробую цикл for, но я не знаю, как это будет работать.

Ответы [ 2 ]

0 голосов
/ 05 июня 2019

Вы можете использовать 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

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;
}
0 голосов
/ 05 июня 2019

Довольно много способов сделать это, во-первых, я бы посоветовал изучить простой класс 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.

...