Skip to content

Commit

Permalink
Reverted somethings and try to fix the command !send
Browse files Browse the repository at this point in the history
  • Loading branch information
outerwinnie committed Sep 4, 2024
1 parent 336d9a8 commit b646412
Showing 1 changed file with 81 additions and 79 deletions.
160 changes: 81 additions & 79 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,78 +7,73 @@
using Discord;
using Discord.WebSocket;
using Discord.Commands;
using Discord.Rest;
using CsvHelper;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Microsoft.Extensions.DependencyInjection;

namespace DiscordBotExample
{
class Program
{
private static List<string> _imageUrls;
private static Random _random = new Random();
internal static List<string> _imageUrls; // Changed from private to internal
internal static Random _random = new Random(); // Changed from private to internal
internal static bool _isImageUrlsLoaded = false; // Changed from private to internal
private static DiscordSocketClient _client;
private static CommandService _commands;
private static IServiceProvider _services;
private static ulong _channelId;
private static ulong _specificUserId; // User ID of the specific user
private static ulong _specificChannelId; // Channel ID of the specific channel
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

static async Task Main(string[] args)
{
// Read environment variables
var token = Environment.GetEnvironmentVariable("DISCORD_BOT_TOKEN");
var channelIdStr = Environment.GetEnvironmentVariable("DISCORD_CHANNEL_ID");
var specificUserIdStr = Environment.GetEnvironmentVariable("SPECIFIC_USER_ID");
_fileId = Environment.GetEnvironmentVariable("GOOGLE_DRIVE_FILE_ID");
_credentialsPath = Environment.GetEnvironmentVariable("GOOGLE_CREDENTIALS_PATH");
var postTimeStr = Environment.GetEnvironmentVariable("POST_TIME");

// Check if token, channelId, fileId, credentialsPath, or postTime is null or empty
if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(channelIdStr) || string.IsNullOrEmpty(_fileId) ||
string.IsNullOrEmpty(_credentialsPath) || string.IsNullOrEmpty(postTimeStr) ||
string.IsNullOrEmpty(specificUserIdStr))
if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(channelIdStr) || string.IsNullOrEmpty(_fileId) || string.IsNullOrEmpty(_credentialsPath) || string.IsNullOrEmpty(postTimeStr))
{
Console.WriteLine("Environment variables are not set correctly.");
return;
}

// Parse channel ID, specific user ID, and specific channel ID
if (!ulong.TryParse(channelIdStr, out _channelId))
{
Console.WriteLine("Invalid DISCORD_CHANNEL_ID format.");
return;
}

if (!ulong.TryParse(specificUserIdStr, out _specificUserId))
{
Console.WriteLine("Invalid SPECIFIC_USER_ID format.");
return;
}

// Parse post time
if (!TimeSpan.TryParse(postTimeStr, out _postTimeSpain))
{
Console.WriteLine("Invalid POST_TIME format. It must be in the format HH:mm:ss.");
return;
}

// Initialize the Discord client
_client = new DiscordSocketClient();
_commands = new CommandService();

_client.Log += Log;
_client.Ready += OnReady;
_client.MessageReceived += HandleCommandAsync; // Handle messages for non-slash commands
_client.InteractionCreated += HandleInteractionAsync;
_client.MessageReceived += HandleMessageReceivedAsync; // Listen for message events

// Start the bot
_services = new ServiceCollection()
.AddSingleton(_client)
.AddSingleton(_commands)
.BuildServiceProvider();

await _commands.AddModulesAsync(System.Reflection.Assembly.GetEntryAssembly(), _services);

await _client.LoginAsync(TokenType.Bot, token);
await _client.StartAsync();

// Block the application until it is closed
await Task.Delay(-1);
}

Expand All @@ -92,7 +87,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)
Expand All @@ -105,7 +99,7 @@ private static async Task OnReady()
.Select(record => record.image_url.Trim())
.ToList();

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

Console.WriteLine("Filtered URLs read from CSV:");
Expand All @@ -120,10 +114,7 @@ private static async Task OnReady()
return;
}

// Register slash commands
await RegisterCommandsAsync();

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

Expand All @@ -133,65 +124,77 @@ 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 guildId = ulong.Parse(Environment.GetEnvironmentVariable("GUILD_ID"));
var guild = _client.GetGuild(guildId);

await guild.DeleteApplicationCommandsAsync(); // Clear existing commands in the guild
await _client.Rest.DeleteAllGlobalCommandsAsync(); // Optionally clear global commands
await guild.DeleteApplicationCommandsAsync();
await _client.Rest.DeleteAllGlobalCommandsAsync();
await guild.CreateApplicationCommandAsync(sendCommand.Build());

Console.WriteLine("Slash command /send registered for guild");
}

private static async Task HandleInteractionAsync(SocketInteraction interaction)
private static async Task HandleCommandAsync(SocketMessage message)
{
if (interaction is SocketSlashCommand command)
{
// Check if the command is "/send"
if (command.Data.Name == "send")
{
await HandleSendCommandAsync(command.Channel);
}
}
var userMessage = message as SocketUserMessage;
if (userMessage == null) return;

int argPos = 0;
if (!(userMessage.HasCharPrefix('!', ref argPos) || userMessage.HasMentionPrefix(_client.CurrentUser, ref argPos)) || userMessage.Author.IsBot)
return;

var context = new SocketCommandContext(_client, userMessage);
var result = await _commands.ExecuteAsync(context, argPos, _services);

if (!result.IsSuccess)
Console.WriteLine(result.ErrorReason);
}

private static async Task HandleMessageReceivedAsync(SocketMessage message)
private static async Task HandleInteractionAsync(SocketInteraction interaction)
{
// Ensure the message is from a user and not a bot
//if (message.Author.IsBot)
//return;

// Check if the message is from the specific user in the specific channel
if (message.Author.Id == _specificUserId && message.Channel.Id == _specificChannelId)
if (interaction is SocketSlashCommand command)
{
// Check if the message content matches the trigger (e.g., "send" command)
if (message.Content.Equals("send", StringComparison.OrdinalIgnoreCase))
if (command.Data.Name == "send")
{
await HandleSendCommandAsync(message.Channel);
Console.Write("Sending");
await HandleSendCommandAsync(command);
}
}
}

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

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.");
}
}

Expand All @@ -200,36 +203,27 @@ 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<string> DownloadCsvFromGoogleDrive()
{
try
{
// Set up Google Drive API service
var credential = GoogleCredential.FromFile(_credentialsPath)
.CreateScoped(DriveService.Scope.DriveReadonly);

Expand All @@ -239,7 +233,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 @@ -265,26 +258,35 @@ private static async Task<string> DownloadCsvFromGoogleDrive()
}
}

private static async Task PostRandomImageUrl()
public class YourRecordClass
{
var channel = _client.GetChannel(_channelId) as IMessageChannel;
public string image_url { get; set; }
public string has_spoilers { get; set; }
}
}

if (channel != null && _imageUrls.Count > 0)
public class SendCommandModule : ModuleBase<SocketCommandContext>
{
[Command("send")]
public async Task SendAsync()
{
if (Program._isImageUrlsLoaded)
{
int index = _random.Next(_imageUrls.Count);
string randomUrl = _imageUrls[index];
await channel.SendMessageAsync(randomUrl);
if (Program._imageUrls.Count > 0)
{
int index = Program._random.Next(Program._imageUrls.Count);
string randomUrl = Program._imageUrls[index];
await ReplyAsync(randomUrl);
}
else
{
await ReplyAsync("No URLs available.");
}
}
else
{
Console.WriteLine("No URLs available.");
await ReplyAsync("The bot is still loading data. Please try again later.");
}
}

public class YourRecordClass
{
public string image_url { get; set; }
public string has_spoilers { get; set; }
}
}
}

0 comments on commit b646412

Please sign in to comment.