Skip to content

Commit

Permalink
Code optimizations
Browse files Browse the repository at this point in the history
  • Loading branch information
outerwinnie committed Sep 2, 2024
1 parent 1f49185 commit 7821ec9
Showing 1 changed file with 76 additions and 76 deletions.
152 changes: 76 additions & 76 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
using System.Threading.Tasks;
using Discord;
using Discord.WebSocket;
using Discord.Commands;
using Discord.Rest;
using CsvHelper;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
Expand All @@ -17,15 +15,15 @@ namespace DiscordBotExample
{
class Program
{
private static List<string> _imageUrls;
private static List<string> _imageUrls = new List<string>();
private static Random _random = new Random();
private static DiscordSocketClient _client;
private static ulong _channelId;
private static string _fileId;
private static string _credentialsPath;
private static TimeSpan _postTimeSpain;
private static TimeZoneInfo _spainTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
private static bool _isImageUrlsLoaded = false; // Flag to track if image URLs are loaded
private static bool _isImageUrlsLoaded = false;

static async Task Main(string[] args)
{
Expand All @@ -36,7 +34,7 @@ static async Task Main(string[] args)
_credentialsPath = Environment.GetEnvironmentVariable("GOOGLE_CREDENTIALS_PATH");
var postTimeStr = Environment.GetEnvironmentVariable("POST_TIME");

// Check if token, channelId, fileId, credentialsPath, or postTime is null or empty
// Validate environment variables
if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(channelIdStr) || string.IsNullOrEmpty(_fileId) || string.IsNullOrEmpty(_credentialsPath) || string.IsNullOrEmpty(postTimeStr))
{
Console.WriteLine("Environment variables are not set correctly.");
Expand Down Expand Up @@ -81,34 +79,6 @@ private static async Task OnReady()
{
Console.WriteLine("Bot is connected.");

// Download and process the CSV file from Google Drive
var csvData = await DownloadCsvFromGoogleDrive();

if (csvData != null)
{
using (var reader = new StringReader(csvData))
using (var csv = new CsvReader(reader, new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture)))
{
_imageUrls = csv.GetRecords<YourRecordClass>()
.Where(record => !string.IsNullOrWhiteSpace(record.image_url) && record.has_spoilers != "yes")
.Select(record => record.image_url.Trim())
.ToList();

_isImageUrlsLoaded = true; // Set flag to true when URLs are loaded
}

Console.WriteLine("Filtered URLs read from CSV:");
foreach (var url in _imageUrls)
{
Console.WriteLine(url);
}
}
else
{
Console.WriteLine("Failed to download or read the CSV file. Exiting...");
return;
}

// Register commands
await RegisterCommandsAsync();

Expand All @@ -122,7 +92,6 @@ private static async Task RegisterCommandsAsync()
.WithName("send")
.WithDescription("Send a random image from the list");

// Replace 'your_guild_id_here' with your actual guild ID
var guildId = ulong.Parse(Environment.GetEnvironmentVariable("GUILD_ID")); // Example: 123456789012345678
var guild = _client.GetGuild(guildId);

Expand All @@ -135,33 +104,36 @@ private static async Task RegisterCommandsAsync()

private static async Task HandleInteractionAsync(SocketInteraction interaction)
{
if (interaction is SocketSlashCommand command)
if (interaction is SocketSlashCommand command && command.Data.Name == "send")
{
if (command.Data.Name == "send")
{
await HandleSendCommandAsync(command);
}
await HandleSendCommandAsync(command);
}
}

private static async Task HandleSendCommandAsync(SocketSlashCommand command)
{
if (_isImageUrlsLoaded)
if (!_isImageUrlsLoaded)
{
if (_imageUrls.Count > 0)
{
int index = _random.Next(_imageUrls.Count);
string randomUrl = _imageUrls[index];
await command.RespondAsync(randomUrl);
}
else
{
await command.RespondAsync("No URLs available.");
}
await command.RespondAsync("The bot is still loading data. Please try again later.");
return;
}

if (_imageUrls.Count > 0)
{
string randomUrl = GetRandomImageUrl();
await command.RespondAsync(randomUrl);
}
else
{
await command.RespondAsync("The bot is still loading data. Please try again later.");
await command.RespondAsync("No URLs available.");
}
}

private static string GetRandomImageUrl()
{
lock (_random) // Ensure thread safety if accessing from multiple threads
{
return _imageUrls[_random.Next(_imageUrls.Count)];
}
}

Expand All @@ -170,36 +142,81 @@ private static async Task ScheduleNextPost()
var nowUtc = DateTime.UtcNow;
var spainTime = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, _spainTimeZone);

// Specify that nextPostTimeSpain is unspecified in terms of kind because we will convert it to a specific time zone
var nextPostTimeSpain = DateTime.SpecifyKind(DateTime.Today.Add(_postTimeSpain), DateTimeKind.Unspecified);

if (nextPostTimeSpain <= spainTime)
{
// If the time has already passed for today, schedule for tomorrow
nextPostTimeSpain = nextPostTimeSpain.AddDays(1);
}

// Convert the unspecified time to Spain time zone and then to UTC
nextPostTimeSpain = TimeZoneInfo.ConvertTimeToUtc(nextPostTimeSpain, _spainTimeZone);

// Calculate the delay
var delay = nextPostTimeSpain - nowUtc;

Console.WriteLine($"Scheduling next post in {delay.TotalMinutes} minutes.");

await Task.Delay(delay);

await PostRandomImageUrl();

// Schedule the next post
await ScheduleNextPost();
}

private static async Task PostRandomImageUrl()
{
var channel = _client.GetChannel(_channelId) as IMessageChannel;

if (channel != null)
{
if (!_isImageUrlsLoaded)
{
await channel.SendMessageAsync("The bot is still loading data. Please try again later.");
return;
}

if (_imageUrls.Count > 0)
{
string randomUrl = GetRandomImageUrl();
await channel.SendMessageAsync(randomUrl);
}
else
{
await channel.SendMessageAsync("No URLs available.");
}
}
}

private static async Task LoadImageUrls()
{
var csvData = await DownloadCsvFromGoogleDrive();

if (csvData != null)
{
using (var reader = new StringReader(csvData))
using (var csv = new CsvReader(reader, new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture)))
{
_imageUrls = csv.GetRecords<YourRecordClass>()
.Where(record => !string.IsNullOrWhiteSpace(record.image_url) && record.has_spoilers != "yes")
.Select(record => record.image_url.Trim())
.ToList();

_isImageUrlsLoaded = true; // Set flag to true when URLs are loaded
}

Console.WriteLine("Filtered URLs read from CSV:");
foreach (var url in _imageUrls)
{
Console.WriteLine(url);
}
}
else
{
Console.WriteLine("Failed to download or read the CSV file.");
}
}

private static async Task<string> DownloadCsvFromGoogleDrive()
{
try
{
// Set up Google Drive API service
var credential = GoogleCredential.FromFile(_credentialsPath)
.CreateScoped(DriveService.Scope.DriveReadonly);

Expand All @@ -209,7 +226,6 @@ private static async Task<string> DownloadCsvFromGoogleDrive()
ApplicationName = "DiscordBotExample",
});

// Download the file
var request = service.Files.Get(_fileId);
var stream = new MemoryStream();
request.MediaDownloader.ProgressChanged += progress =>
Expand All @@ -235,22 +251,6 @@ private static async Task<string> DownloadCsvFromGoogleDrive()
}
}

private static async Task PostRandomImageUrl()
{
var channel = _client.GetChannel(_channelId) as IMessageChannel;

if (channel != null && _imageUrls.Count > 0)
{
int index = _random.Next(_imageUrls.Count);
string randomUrl = _imageUrls[index];
await channel.SendMessageAsync(randomUrl);
}
else
{
Console.WriteLine("No URLs available.");
}
}

public class YourRecordClass
{
public string image_url { get; set; }
Expand Down

0 comments on commit 7821ec9

Please sign in to comment.