Made more code async and added request cooldown

This commit is contained in:
Stone-Red-Code
2021-04-14 11:53:53 +02:00
parent 74f40593ba
commit f0fcbc03c5
14 changed files with 106 additions and 66 deletions
Binary file not shown.
+32 -20
View File
@@ -6,6 +6,7 @@ using System.Diagnostics;
using System.IO;
using System.Linq;
using System;
using System.Threading.Tasks;
namespace DiscordCLI
{
@@ -21,7 +22,7 @@ namespace DiscordCLI
outputManager = outputMan;
}
protected void ListGuilds(string args)
protected async Task ListGuilds(string args)
{
int index = 1;
foreach (DiscordGuild guild in client.Guilds.Values)
@@ -29,9 +30,11 @@ namespace DiscordCLI
Console.WriteLine($"{index}. {guild.Name}");
index++;
}
await Task.CompletedTask;
}
protected void ListDms(string args)
protected async Task ListDms(string args)
{
int index = 1;
foreach (DiscordDmChannel dmChannel in client.PrivateChannels)
@@ -39,9 +42,10 @@ namespace DiscordCLI
Console.WriteLine($"{index}. {string.Join(", ", dmChannel.Recipients.Select(x => x.Username))}");
index++;
}
await Task.CompletedTask;
}
protected void ListGuildChannels(string args)
protected async Task ListGuildChannels(string args)
{
IReadOnlyCollection<DiscordChannel> textChannels;
DiscordGuild guild;
@@ -88,9 +92,11 @@ namespace DiscordCLI
break;
}
}
await Task.CompletedTask;
}
protected async void EnterChannel(string args)
protected async Task EnterChannel(string args)
{
DiscordChannel textChannel;
@@ -117,20 +123,23 @@ namespace DiscordCLI
return;
}
foreach (DiscordMessage message in (await textChannel.GetMessagesAsync(10)).Reverse())
try
{
try
foreach (DiscordMessage message in (textChannel.GetMessagesAsync(10).Result).Reverse())
{
await outputManager.WriteMessage(message, textChannel, GlobalInformation.currentGuild);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
await outputManager.WriteMessage(message, textChannel, GlobalInformation.currentGuild, false);
}
}
catch (Exception ex)
{
ConsoleExt.WriteLine(ex.Message, ConsoleColor.Red);
GlobalInformation.currentTextChannel = null;
}
await Task.CompletedTask;
}
protected async void EnterDmChannel(string args)
protected async Task EnterDmChannel(string args)
{
DiscordDmChannel dmChannel;
@@ -153,23 +162,26 @@ namespace DiscordCLI
return;
}
foreach (DiscordMessage message in (await dmChannel.GetMessagesAsync(10)).Reverse())
try
{
try
foreach (DiscordMessage message in (await dmChannel.GetMessagesAsync(10)).Reverse())
{
await outputManager.WriteMessage(message, dmChannel, GlobalInformation.currentGuild);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
await outputManager.WriteMessage(message, dmChannel, GlobalInformation.currentGuild, false);
}
}
catch (Exception ex)
{
ConsoleExt.WriteLine(ex, ConsoleColor.Red);
GlobalInformation.currentTextChannel = null;
}
}
protected void DeleteToken(string args)
protected async Task DeleteToken(string args)
{
File.Delete(Program.tokenPath);
Environment.Exit(0);
await Task.CompletedTask;
}
}
}
+33 -9
View File
@@ -3,6 +3,8 @@ using Stone_Red_Utilities.ColorConsole;
using System.Collections.Generic;
using System.Linq;
using System;
using System.Timers;
using System.Threading.Tasks;
namespace DiscordCLI
{
@@ -10,7 +12,8 @@ namespace DiscordCLI
{
private readonly DiscordClient client;
private readonly Dictionary<string, (string, Action<string>)> CommandsList;
private readonly Dictionary<string, (string, Func<string, Task>)> CommandsList;
private int cooldown = 0;
public CommandsManager(DiscordClient dicordClient, OutputManager outputManager) : base(dicordClient, outputManager)
{
@@ -27,19 +30,39 @@ namespace DiscordCLI
{ "enterc", ("enter channel args:<channel name/index>", EnterChannel) },
{ "enterd", ("enter DM channel args:<channel name/index>", EnterDmChannel) },
};
Timer cooldownTimer = new Timer(1000);
cooldownTimer.Elapsed += CooldownTimer_Elapsed;
cooldownTimer.Start();
}
private void CooldownTimer_Elapsed(object sender, ElapsedEventArgs e)
{
if (cooldown > 0)
cooldown--;
}
/// <summary>
/// Check the command and return true if the program should exit
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public bool CheckCommand(string input)
/// <returns>exit bool and write override bool</returns>
public async Task<(bool, bool)> CheckCommand(string input)
{
cooldown++;
if (cooldown > 1)
{
Console.WriteLine();
ConsoleExt.WriteLine("You are beeing rate limited!", ConsoleColor.Yellow);
ConsoleExt.WriteLine("Wait a few seconds before making another request!", ConsoleColor.Yellow);
return (false, true);
}
input = input.Trim().ToLower().Replace('\n', '\0');
if (string.IsNullOrWhiteSpace(input))
return false;
return (false, false);
if (input.StartsWith(InputManager.prefix))
{
@@ -47,15 +70,16 @@ namespace DiscordCLI
}
else if (GlobalInformation.currentTextChannel != null)
{
cooldown++;
Console.Write("\r" + new string(' ', Console.WindowWidth));
GlobalInformation.currentTextChannel.SendMessageAsync(input);
return false;
await GlobalInformation.currentTextChannel.SendMessageAsync(input);
return (false, false);
}
Console.WriteLine();
if (input == "exit" || input is null)
return true;
return (true, false);
string args = input.Contains(" ") ? input[input.IndexOf(" ")..].Trim() : null;
input = input.Contains(" ") ? input.Substring(0, input.IndexOf(" ")) : input;
@@ -73,13 +97,13 @@ namespace DiscordCLI
}
else if (CommandsList.ContainsKey(input))
{
CommandsList[input].Item2(args);
await CommandsList[input].Item2(args);
}
else
{
ConsoleExt.WriteLine("Command does not exist!", ConsoleColor.Red);
}
return false;
return (false, false);
}
}
}
+2 -3
View File
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
@@ -10,5 +10,4 @@
<PackageReference Include="DSharpPlus" Version="3.2.3" />
<PackageReference Include="Stone_Red-C-Sharp-Utilities" Version="1.0.0.2" />
</ItemGroup>
</Project>
</Project>
+31 -29
View File
@@ -11,7 +11,7 @@ namespace DiscordCLI
private readonly CommandsManager commandsManager;
private readonly DiscordClient client;
public const string prefix = ">";
public string Input { get; private set; } = prefix;
public string Input { get; private set; } = string.Empty;
public InputManager(DiscordClient dicordClient, CommandsManager commandsMan)
{
@@ -21,43 +21,45 @@ namespace DiscordCLI
public async Task ReadInput()
{
await Task.Run(() =>
bool exit = false;
bool printOverride = false;
string lastInput = prefix;
while (!exit)
{
bool exit = false;
while (!exit)
DiscordDmChannel dmChannel = GlobalInformation.currentTextChannel as DiscordDmChannel;
string infoString = $"\r[{client.CurrentUser.Username}#{client.CurrentUser.Discriminator}] [{(dmChannel is null ? GlobalInformation.currentGuild?.Name : "DMs")}/{(dmChannel is null ? GlobalInformation.currentTextChannel?.Name : string.Join(", ", dmChannel.Recipients.Select(x => x.Username)))}] ==> ";
if (lastInput.StartsWith(prefix) || printOverride)
Console.Write(Environment.NewLine + infoString);
printOverride = false;
ConsoleKeyInfo keyInfo;
do
{
DiscordDmChannel dmChannel = GlobalInformation.currentTextChannel as DiscordDmChannel;
string infoString = $"\r[{client.CurrentUser.Username}#{client.CurrentUser.Discriminator}] [{(dmChannel is null ? GlobalInformation.currentGuild?.Name : "DMs")}/{(dmChannel is null ? GlobalInformation.currentTextChannel?.Name : string.Join(", ", dmChannel.Recipients.Select(x => x.Username)))}] ==> ";
if (Input.StartsWith(prefix))
Console.Write(Environment.NewLine + infoString);
keyInfo = Console.ReadKey(true);
if (!char.IsControl(keyInfo.KeyChar))
Input += keyInfo.KeyChar.ToString();
Input = string.Empty;
ConsoleKeyInfo keyInfo;
do
if (keyInfo.Key == ConsoleKey.Backspace && Input.Length > 0)
{
keyInfo = Console.ReadKey(true);
if (!char.IsControl(keyInfo.KeyChar))
Input += keyInfo.KeyChar.ToString();
Input = Input.Remove(Input.Length - 1);
}
if (keyInfo.Key == ConsoleKey.Backspace && Input.Length > 0)
{
Input = Input.Remove(Input.Length - 1);
}
Console.Write(keyInfo.KeyChar);
if (keyInfo.Key == ConsoleKey.Backspace)
Console.Write(" ");
Console.Write(keyInfo.KeyChar);
if (keyInfo.Key == ConsoleKey.Backspace)
Console.Write(" ");
Console.CursorLeft = infoString.Length + Input.Length - 1;
} while (keyInfo.Key != ConsoleKey.Enter);
Console.CursorLeft = infoString.Length + Input.Length - 1;
} while (keyInfo.Key != ConsoleKey.Enter);
if (GlobalInformation.currentTextChannel == null && !Input.StartsWith(prefix))
Input = prefix + Input;
if (GlobalInformation.currentTextChannel == null && !Input.StartsWith(prefix))
Input = prefix + Input;
lastInput = new string(Input);
Input = string.Empty;
exit = commandsManager.CheckCommand(Input);
}
});
(exit, printOverride) = await commandsManager.CheckCommand(lastInput);
}
}
}
}
+8 -4
View File
@@ -21,7 +21,7 @@ namespace DiscordCLI
client = discordClient;
}
public async Task WriteMessage(DiscordMessage message, DiscordChannel channel, DiscordGuild guild)
public async Task WriteMessage(DiscordMessage message, DiscordChannel channel, DiscordGuild guild, bool writeInfo = true)
{
try
{
@@ -80,9 +80,13 @@ namespace DiscordCLI
WriteTop(string.Empty, Color.White, message);
DiscordDmChannel dmChannel = GlobalInformation.currentTextChannel as DiscordDmChannel;
string infoString = $"\r[{client.CurrentUser.Username}#{client.CurrentUser.Discriminator}] [{(dmChannel is null ? GlobalInformation.currentGuild?.Name : "DMs")}/{(dmChannel is null ? GlobalInformation.currentTextChannel?.Name : string.Join(", ", dmChannel.Recipients.Select(x => x.Username)))}] ==> ";
Console.Write(infoString);
Console.Write(InputManager.Input);
if (writeInfo)
{
string infoString = $"\r[{client.CurrentUser.Username}#{client.CurrentUser.Discriminator}] [{(dmChannel is null ? GlobalInformation.currentGuild?.Name : "DMs")}/{(dmChannel is null ? GlobalInformation.currentTextChannel?.Name : string.Join(", ", dmChannel.Recipients.Select(x => x.Username)))}] ==> ";
Console.Write(infoString);
Console.Write(InputManager.Input);
}
}
private void WriteTop(string message, Color color, DiscordMessage discordMessage, bool removeText = true, bool newLine = true, string info = null)
-1
View File
@@ -27,7 +27,6 @@ namespace DiscordCLI
token = File.ReadAllText(tokenPath);
tokenInput:
while (string.IsNullOrEmpty(token))
{
Console.Write("Enter auth token: ");
token = Console.ReadLine();
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.