I have a small C# bot that check for an available date/time and book it if any, it uses…
- User
I have a small C# bot that check for an available date/time and book it if any, it uses 2 external APIs which many other users use so it is a race, My main goal is to get an available date/time that I didn't use before if possible,
Please let me know if you have a better approach or any optimization on the logic:
private static readonly Dictionary<string, List> TestedDateTimes = new();
public async void Main() { // Checking string? date, time; while (true) { (date, time) = await SelectAvailableDateTime().ConfigureAwait(false); if (date != null && time != null) break;
await Task.Delay(3000).ConfigureAwait(false); } //Do something with the date/time...}
public async Task<(string date, string time)> SelectAvailableDateTime() { var date = await GetNonUsedRandomDate().ConfigureAwait(false); if (date == default) return default;
var time = await GetNonUsedRandomTimeByDate(date).ConfigureAwait(false); if (time == null) return default; if (!TestedDateTimes.ContainsKey(date)) TestedDateTimes[date] = new List<string>(); if (!TestedDateTimes[date].Contains(time)) TestedDateTimes[date].Add(time); return (date, time);} private async Task<string?> GetNonUsedRandomDate() { var allDates = await GetAllDates(_applicant.CentreId, _applicant.CategoryId, _applicant.VisaTypeId).ConfigureAwait(false);
var availableDates = allDates ?.Where(d => d.AppointmentDateType == AppointmentDateType.Available && (_applicant.Members.Count < 2 || d.SingleSlotAvailable)) .ToArray(); if (availableDates == null || availableDates.Length == 0) return default; var nonUsedDates = availableDates.Where(d => !TestedDateTimes.ContainsKey(d.DateText)).ToArray(); if (nonUsedDates.Length == 0) { TestedDateTimes.Clear(); nonUsedDates = availableDates; } // So if the user uses a custom date selector and there is no date fulfill his needs, search on all return (GetRandomDate(nonUsedDates) ?? GetRandomDate(availableDates))?.DateText;} private async Task<string?> GetNonUsedRandomTimeByDate(string date) { var allTimes = await GetAllTimes(date, _applicant.CentreId, _applicant.CategoryId, _applicant.VisaTypeId).ConfigureAwait(false);
var availableTimes = allTimes ?.Where(d => d.Count >= _applicant.Members.Count) .ToArray(); if (availableTimes == null || availableTimes.Length == 0) return default; var nonUsedTimes = availableTimes.Where(d => !TestedDateTimes.ContainsKey(date) || !TestedDateTimes["date"].Contains(d.Id)).ToArray(); if (nonUsedTimes.Length == 0) { TestedDateTimes.Clear(); nonUsedTimes = availableTimes; } return FetchHelper.GetRandomElement(nonUsedTimes)?.Id;} private Date? GetRandomDate(IEnumerable? enumerable) { if (enumerable == null) return default; var dates = enumerable as Date[] ?? enumerable.ToArray();
- Assistant