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.IO;
using System.Linq; using System.Linq;
using System; using System;
using System.Threading.Tasks;
namespace DiscordCLI namespace DiscordCLI
{ {
@@ -21,7 +22,7 @@ namespace DiscordCLI
outputManager = outputMan; outputManager = outputMan;
} }
protected void ListGuilds(string args) protected async Task ListGuilds(string args)
{ {
int index = 1; int index = 1;
foreach (DiscordGuild guild in client.Guilds.Values) foreach (DiscordGuild guild in client.Guilds.Values)
@@ -29,9 +30,11 @@ namespace DiscordCLI
Console.WriteLine($"{index}. {guild.Name}"); Console.WriteLine($"{index}. {guild.Name}");
index++; index++;
} }
await Task.CompletedTask;
} }
protected void ListDms(string args) protected async Task ListDms(string args)
{ {
int index = 1; int index = 1;
foreach (DiscordDmChannel dmChannel in client.PrivateChannels) foreach (DiscordDmChannel dmChannel in client.PrivateChannels)
@@ -39,9 +42,10 @@ namespace DiscordCLI
Console.WriteLine($"{index}. {string.Join(", ", dmChannel.Recipients.Select(x => x.Username))}"); Console.WriteLine($"{index}. {string.Join(", ", dmChannel.Recipients.Select(x => x.Username))}");
index++; index++;
} }
await Task.CompletedTask;
} }
protected void ListGuildChannels(string args) protected async Task ListGuildChannels(string args)
{ {
IReadOnlyCollection<DiscordChannel> textChannels; IReadOnlyCollection<DiscordChannel> textChannels;
DiscordGuild guild; DiscordGuild guild;
@@ -88,9 +92,11 @@ namespace DiscordCLI
break; break;
} }
} }
await Task.CompletedTask;
} }
protected async void EnterChannel(string args) protected async Task EnterChannel(string args)
{ {
DiscordChannel textChannel; DiscordChannel textChannel;
@@ -117,20 +123,23 @@ namespace DiscordCLI
return; 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); await outputManager.WriteMessage(message, textChannel, GlobalInformation.currentGuild, false);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
} }
} }
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; DiscordDmChannel dmChannel;
@@ -153,23 +162,26 @@ namespace DiscordCLI
return; 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); await outputManager.WriteMessage(message, dmChannel, GlobalInformation.currentGuild, false);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
} }
} }
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); File.Delete(Program.tokenPath);
Environment.Exit(0); 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.Collections.Generic;
using System.Linq; using System.Linq;
using System; using System;
using System.Timers;
using System.Threading.Tasks;
namespace DiscordCLI namespace DiscordCLI
{ {
@@ -10,7 +12,8 @@ namespace DiscordCLI
{ {
private readonly DiscordClient client; 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) public CommandsManager(DiscordClient dicordClient, OutputManager outputManager) : base(dicordClient, outputManager)
{ {
@@ -27,19 +30,39 @@ namespace DiscordCLI
{ "enterc", ("enter channel args:<channel name/index>", EnterChannel) }, { "enterc", ("enter channel args:<channel name/index>", EnterChannel) },
{ "enterd", ("enter DM channel args:<channel name/index>", EnterDmChannel) }, { "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> /// <summary>
/// Check the command and return true if the program should exit /// Check the command and return true if the program should exit
/// </summary> /// </summary>
/// <param name="input"></param> /// <param name="input"></param>
/// <returns></returns> /// <returns>exit bool and write override bool</returns>
public bool CheckCommand(string input) 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'); input = input.Trim().ToLower().Replace('\n', '\0');
if (string.IsNullOrWhiteSpace(input)) if (string.IsNullOrWhiteSpace(input))
return false; return (false, false);
if (input.StartsWith(InputManager.prefix)) if (input.StartsWith(InputManager.prefix))
{ {
@@ -47,15 +70,16 @@ namespace DiscordCLI
} }
else if (GlobalInformation.currentTextChannel != null) else if (GlobalInformation.currentTextChannel != null)
{ {
cooldown++;
Console.Write("\r" + new string(' ', Console.WindowWidth)); Console.Write("\r" + new string(' ', Console.WindowWidth));
GlobalInformation.currentTextChannel.SendMessageAsync(input); await GlobalInformation.currentTextChannel.SendMessageAsync(input);
return false; return (false, false);
} }
Console.WriteLine(); Console.WriteLine();
if (input == "exit" || input is null) if (input == "exit" || input is null)
return true; return (true, false);
string args = input.Contains(" ") ? input[input.IndexOf(" ")..].Trim() : null; string args = input.Contains(" ") ? input[input.IndexOf(" ")..].Trim() : null;
input = input.Contains(" ") ? input.Substring(0, input.IndexOf(" ")) : input; input = input.Contains(" ") ? input.Substring(0, input.IndexOf(" ")) : input;
@@ -73,13 +97,13 @@ namespace DiscordCLI
} }
else if (CommandsList.ContainsKey(input)) else if (CommandsList.ContainsKey(input))
{ {
CommandsList[input].Item2(args); await CommandsList[input].Item2(args);
} }
else else
{ {
ConsoleExt.WriteLine("Command does not exist!", ConsoleColor.Red); 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> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
@@ -10,5 +10,4 @@
<PackageReference Include="DSharpPlus" Version="3.2.3" /> <PackageReference Include="DSharpPlus" Version="3.2.3" />
<PackageReference Include="Stone_Red-C-Sharp-Utilities" Version="1.0.0.2" /> <PackageReference Include="Stone_Red-C-Sharp-Utilities" Version="1.0.0.2" />
</ItemGroup> </ItemGroup>
</Project>
</Project>
+31 -29
View File
@@ -11,7 +11,7 @@ namespace DiscordCLI
private readonly CommandsManager commandsManager; private readonly CommandsManager commandsManager;
private readonly DiscordClient client; private readonly DiscordClient client;
public const string prefix = ">"; 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) public InputManager(DiscordClient dicordClient, CommandsManager commandsMan)
{ {
@@ -21,43 +21,45 @@ namespace DiscordCLI
public async Task ReadInput() public async Task ReadInput()
{ {
await Task.Run(() => bool exit = false;
bool printOverride = false;
string lastInput = prefix;
while (!exit)
{ {
bool exit = false; DiscordDmChannel dmChannel = GlobalInformation.currentTextChannel as DiscordDmChannel;
while (!exit) 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; keyInfo = Console.ReadKey(true);
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 (!char.IsControl(keyInfo.KeyChar))
if (Input.StartsWith(prefix)) Input += keyInfo.KeyChar.ToString();
Console.Write(Environment.NewLine + infoString);
Input = string.Empty; if (keyInfo.Key == ConsoleKey.Backspace && Input.Length > 0)
ConsoleKeyInfo keyInfo;
do
{ {
keyInfo = Console.ReadKey(true); Input = Input.Remove(Input.Length - 1);
if (!char.IsControl(keyInfo.KeyChar)) }
Input += keyInfo.KeyChar.ToString();
if (keyInfo.Key == ConsoleKey.Backspace && Input.Length > 0) Console.Write(keyInfo.KeyChar);
{ if (keyInfo.Key == ConsoleKey.Backspace)
Input = Input.Remove(Input.Length - 1); Console.Write(" ");
}
Console.Write(keyInfo.KeyChar); Console.CursorLeft = infoString.Length + Input.Length - 1;
if (keyInfo.Key == ConsoleKey.Backspace) } while (keyInfo.Key != ConsoleKey.Enter);
Console.Write(" ");
Console.CursorLeft = infoString.Length + Input.Length - 1; if (GlobalInformation.currentTextChannel == null && !Input.StartsWith(prefix))
} while (keyInfo.Key != ConsoleKey.Enter); Input = prefix + Input;
if (GlobalInformation.currentTextChannel == null && !Input.StartsWith(prefix)) lastInput = new string(Input);
Input = prefix + 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; 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 try
{ {
@@ -80,9 +80,13 @@ namespace DiscordCLI
WriteTop(string.Empty, Color.White, message); WriteTop(string.Empty, Color.White, message);
DiscordDmChannel dmChannel = GlobalInformation.currentTextChannel as DiscordDmChannel; 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); if (writeInfo)
Console.Write(InputManager.Input); {
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) 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); token = File.ReadAllText(tokenPath);
tokenInput: tokenInput:
while (string.IsNullOrEmpty(token))
{ {
Console.Write("Enter auth token: "); Console.Write("Enter auth token: ");
token = Console.ReadLine(); 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.