diff options
author | uzvkl <dennis.kobert@student.kit.edu> | 2019-05-20 00:54:14 +0200 |
---|---|---|
committer | uzvkl <dennis.kobert@student.kit.edu> | 2019-05-20 00:54:14 +0200 |
commit | ed26623e17e8dfcc036f88cca6de10d5a35697ec (patch) | |
tree | 26dae8b824631e6542c876c82ce0e15260c411bc /DiscordBot | |
parent | 2ab4051c6fe720dc47e99b0c305a0d779ee02d51 (diff) |
Reorganize Code delete ZoBotanica
Diffstat (limited to 'DiscordBot')
-rw-r--r-- | DiscordBot/Auxiliary/CommandExtension.cs | 98 | ||||
-rw-r--r-- | DiscordBot/Auxiliary/Dice.cs | 31 | ||||
-rw-r--r-- | DiscordBot/Auxiliary/Permissions.cs | 32 | ||||
-rw-r--r-- | DiscordBot/Auxiliary/RandomMisc.cs | 36 | ||||
-rw-r--r-- | DiscordBot/Auxiliary/SpellCorrect.cs | 105 | ||||
-rw-r--r-- | DiscordBot/CommandHandler.cs | 112 | ||||
-rw-r--r-- | DiscordBot/Commands/CommandHelper.cs | 119 | ||||
-rw-r--r-- | DiscordBot/Commands/FileHandler.cs | 24 | ||||
-rw-r--r-- | DiscordBot/Commands/MiscCommands.cs | 190 | ||||
-rw-r--r-- | DiscordBot/DiscordBot.csproj | 12 | ||||
-rw-r--r-- | DiscordBot/Program.cs | 58 | ||||
-rw-r--r-- | DiscordBot/Rework/Permissions.cs | 38 |
12 files changed, 855 insertions, 0 deletions
diff --git a/DiscordBot/Auxiliary/CommandExtension.cs b/DiscordBot/Auxiliary/CommandExtension.cs new file mode 100644 index 0000000..690f352 --- /dev/null +++ b/DiscordBot/Auxiliary/CommandExtension.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Discord; +using Discord.Commands; + +namespace DiscordBot.Auxiliary +{ + public static class CommandExtension + { + private static WebClient _client; + + public static async Task ReplyTimedAsync(this ModuleBase m, string message, TimeSpan time) + { + var token = message.GetHashCode(); + var send = m.Context.Channel.SendMessageAsync($"#{token}\n```xl\n{message}```"); + + var barInvoker = new BackgroundWorker(); + barInvoker.DoWork += delegate + { + Thread.Sleep(time); + Delete(token, m); + }; + + await send; + barInvoker.RunWorkerAsync(); + } + + private static void Delete(int token, ModuleBase m) + { + var messagesAsync = m.Context.Channel.GetMessagesAsync(); + Task.WaitAll(messagesAsync.ToArray()); + var list = messagesAsync.ToEnumerable().ToList(); + var messages = new List<IMessage>(); + foreach (var task in list) messages.AddRange(task.ToList()); + + var test = messages.Where(x => x.Content.StartsWith($"#{token}\n") && x.Author.IsBot).Select(c => c); + Task.WaitAll(test.Select(message => (message as IUserMessage)?.DeleteAsync()).ToArray()); + } + + public static async Task ReplyAsync(this ModuleBase m, IEnumerable<string> message, bool directMessage = false) + { + var sb = new StringBuilder(); + foreach (var re in message) + { + if (sb.Length + re.Length > 1798) + { + if (directMessage) + await m.Context.User.SendMessageAsync("```xl\n" + sb + "\n```"); + else + await m.Context.Channel.SendMessageAsync("```xl\n" + sb + "\n```"); + + sb.Clear(); + } + + sb.AppendLine(re); + } + + if (directMessage) + await m.Context.User.SendMessageAsync("```xl\n" + sb + "\n```"); + else + await m.Context.Channel.SendMessageAsync("```xl\n" + sb + "\n```"); + } + + public static async Task ReplyAsync(this ModuleBase m, IEnumerable<string> message, TimeSpan time) + { + var sb = new StringBuilder(); + foreach (var re in message) + { + if (sb.Length + re.Length > 1798) + { + await m.ReplyTimedAsync(sb.ToString(), time); + + + sb.Clear(); + } + + sb.AppendLine(re); + } + + await m.ReplyTimedAsync(sb.ToString(), TimeSpan.FromSeconds(90)); + } + + public static async Task SendWebFile(this IMessageChannel channel, + string url = "https://i.imgur.com/0iHEycJ.png") + { + if (_client == null) _client = new WebClient(); + + var stream = _client.OpenRead(url); + await channel.SendFileAsync(stream, url.Split('/').Last()); + } + } +}
\ No newline at end of file diff --git a/DiscordBot/Auxiliary/Dice.cs b/DiscordBot/Auxiliary/Dice.cs new file mode 100644 index 0000000..c44e87e --- /dev/null +++ b/DiscordBot/Auxiliary/Dice.cs @@ -0,0 +1,31 @@ +using System; + +namespace DiscordBot.Auxiliary +{ + public static class Dice // roll it! + { + private static readonly Random Rnd = new Random(); + + public static int Roll(int d = 20) + { + return Rnd.Next(d) + 1; + } + + + public static int Roll(int count, int d) + { + if (d <= 0) return 0; + + var sum = 0; + for (var i = 0; i < Math.Abs(count); i++) + { + var roll = Roll(d); + sum += roll; + } + + sum *= Math.Abs(count) / count; + + return sum; + } + } +}
\ No newline at end of file diff --git a/DiscordBot/Auxiliary/Permissions.cs b/DiscordBot/Auxiliary/Permissions.cs new file mode 100644 index 0000000..c2cb058 --- /dev/null +++ b/DiscordBot/Auxiliary/Permissions.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; +using System.Linq; +using Discord.Commands; +using Discord.WebSocket; + +namespace DiscordBot.Auxiliary +{ + public static class Permissions + { + public static bool Check(ICommandContext c, string role) + { + return ((SocketGuildUser) c.User).Roles.ToList().Exists(v => v.Name.Equals(role)); + } + + public static bool Check(ICommandContext c, IEnumerable<string> roles) + { + return roles.Any(role => ((SocketGuildUser) c.User).Roles.ToList().Exists(v => v.Name.Equals(role))); + } + + public static bool Test(ICommandContext c, string role) + { + if (Check(c, role)) return true; + c.Channel.SendMessageAsync("```xl\n Keine ausreichenden Berechtigungen\n```").Wait(); + return false; + } + + public static void Test(ICommandContext c, string[] roles) + { + if (!Check(c, roles)) c.Channel.SendMessageAsync("```xl\n Keine ausreichenden Berechtigungen\n```").Wait(); + } + } +}
\ No newline at end of file diff --git a/DiscordBot/Auxiliary/RandomMisc.cs b/DiscordBot/Auxiliary/RandomMisc.cs new file mode 100644 index 0000000..f7c5186 --- /dev/null +++ b/DiscordBot/Auxiliary/RandomMisc.cs @@ -0,0 +1,36 @@ +using System; +using System.Linq; +using System.Text; + +namespace DiscordBot.Auxiliary +{ + public static class RandomMisc + { + public static string Roll(string input) + { + var output = new StringBuilder(); + var strings = input.Split('w', 'd').ToList(); + var count = Convert.ToInt32(strings[0]); + strings = strings[1].Split(' ').ToList(); + var d = Convert.ToInt32(strings[0]); + + if (strings.Count > 0) + { + } + + var sum = 0; + for (var i = 0; i < count; i++) + { + var roll = Dice.Roll(d); + sum += roll; + output.Append("[" + roll + "] "); + } + + if (strings.Count <= 1) return output.ToString(); + sum += Convert.ToInt32(strings[1]); + output.Append("sum: " + sum); + + return output.ToString(); + } + } +}
\ No newline at end of file diff --git a/DiscordBot/Auxiliary/SpellCorrect.cs b/DiscordBot/Auxiliary/SpellCorrect.cs new file mode 100644 index 0000000..a2ba91a --- /dev/null +++ b/DiscordBot/Auxiliary/SpellCorrect.cs @@ -0,0 +1,105 @@ +using System; +using System.Diagnostics; + +namespace DiscordBot.Auxiliary +{ + public class SpellCorrect : StringComparer + { + public const int ErrorThreshold = 94100; + + public override int Compare(string x, string y) + { + return CompareEasy(x, y); + } + + public static int CompareEasy(string x, string y) + { + if (string.IsNullOrEmpty(x)) throw new ArgumentException("message", nameof(x)); + + if (string.IsNullOrEmpty(y)) throw new ArgumentException("message", nameof(y)); + + if (x.Equals(y)) return 0; + + x = x.ToLower(); + y = y.ToLower(); + if (x.Equals(y)) return 1; + + var subs = y.Split(' ', '/'); + var score = subs.Length; + foreach (var s in subs) + if (s.Equals(x)) + score--; + + if (score < subs.Length) return score + 1; + + return 100000 - (int) (CompareExact(x, y) * 1000.0); + /*if (y.Contains(x)) + return 6;*/ + } + + public override bool Equals(string x, string y) + { + Debug.Assert(x != null, nameof(x) + " != null"); + return x.Equals(y); + } + + public override int GetHashCode(string obj) + { + throw new NotImplementedException(); + } + + public static double CompareExact(string s, string q) + { + s = s.ToLower(); + q = q.ToLower(); + + int i, j; + const double match = 3.0; + const double gap = -2.0; + const double mismatch = -2.0; + + double decay; + + var matrix = new double[s.Length + 1, q.Length + 1]; + var max = 0.0; + matrix[0, 0] = 0.0; + + for (i = 1; i < s.Length; i++) + // matrix[i, 0] = 0.0; + matrix[i, 0] = i * gap; + + for (i = 1; i < q.Length; i++) matrix[0, i] = 0.0; + + + for (i = 1; i <= s.Length; i++) + for (j = 1; j <= q.Length; j++) + { + decay = j / (double) (s.Length * 1000); + var add = s[i - 1] == q[j - 1] ? match - decay : mismatch; + var score = matrix[i - 1, j - 1] + add; + + if (score < matrix[i - 1, j] + gap) score = matrix[i - 1, j] + gap; + + if (score < matrix[i, j - 1] + gap) score = matrix[i, j - 1] + gap; + + if (i > 1 && j > 1) + if (s[i - 1] == q[j - 2] && s[i - 2] == q[j - 1]) + { + add = 3 / 2.0 * match - decay; + if (score < matrix[i - 2, j - 2] + add) score = matrix[i - 2, j - 2] + add; + } + + // if (score < 0) + // { + // score = 0; + // } + + if (max < score && i == s.Length) max = score; + + matrix[i, j] = score; + } + + return max; + } + } +}
\ No newline at end of file diff --git a/DiscordBot/CommandHandler.cs b/DiscordBot/CommandHandler.cs new file mode 100644 index 0000000..0f6aa7e --- /dev/null +++ b/DiscordBot/CommandHandler.cs @@ -0,0 +1,112 @@ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Reflection; +using System.Threading.Tasks; +using Discord; +using Discord.Commands; +using Discord.WebSocket; + +namespace DiscordBot +{ + public class CommandHandler + { + private readonly DiscordSocketClient _client; + private readonly CommandService _commands; + private static readonly HttpClient _HttpClient = new HttpClient(); + + public CommandHandler(DiscordSocketClient client, CommandService commands) + { + _commands = commands; + _client = client; + } + + public async Task InstallCommandsAsync() + { + // Hook the MessageReceived event into our command handler + _client.MessageReceived += HandleCommandAsync; + + // Here we discover all of the command modules in the entry + // assembly and load them. Starting from Discord.NET 2.0, a + // service provider is required to be passed into the + // module registration method to inject the + // required dependencies. + // + // If you do not use Dependency Injection, pass null. + // See Dependency Injection guide for more information. + await _commands.AddModulesAsync(assembly: Assembly.GetEntryAssembly(), + services: null); + } + + private async Task HandleCommandAsync(SocketMessage messageParam) + { + // Don't process the command if it was a system message + var message = messageParam as SocketUserMessage; + if (message == null) return; + + // Create a number to track where the prefix ends and the command begins + int argPos = 0; + + // Determine if the message is a command based on the prefix and make sure no bots trigger commands + if (!(message.HasCharPrefix('!', ref argPos) || + message.HasMentionPrefix(_client.CurrentUser, ref argPos)) || + message.Author.IsBot) + return; + + // Create a WebSocket-based command context based on the message + var context = new SocketCommandContext(_client, message); + + // Execute the command with the command context we just + // created, along with the service provider for precondition checks. + + // Keep in mind that result does not indicate a return value + // rather an object stating if the command executed successfully. + var result = await _commands.ExecuteAsync( + context: context, + argPos: argPos, + services: null); + + // Optionally, we may inform the user if the command fails + // to be executed; however, this may not always be desired, + // as it may clog up the request queue should a user spam a + // command. + + if (result.Error == CommandError.UnknownCommand) + { + var response = await SendCommand(message.Author.Username, message.Content,"https://kobert.dev/api/dsa/commands"); + //var response = "invalid"; + await context.Channel.SendMessageAsync(response); + } + else if (!result.IsSuccess) await context.Channel.SendMessageAsync(result.ErrorReason); + } + + + + private static async Task<string> SendCommand(string name, string command, string url) + { + command = command.Remove(0, 1); + var args = command.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + + var cmdContent = string.Empty; + if (args.Length > 1) cmdContent = "\"" + args.Skip(1).Aggregate((s, n) => s + "\", \"" + n) + "\""; + + var values = new Dictionary<string, string> + { + { "Name", name }, + { "CmdIdentifier", args.First()}, + { "CmdTexts", "[" + cmdContent + "]"} + }; + + var content = new FormUrlEncodedContent(values); + + var response = await _HttpClient.PostAsync(url, content); + + return await response.Content.ReadAsStringAsync(); + } + + } +} diff --git a/DiscordBot/Commands/CommandHelper.cs b/DiscordBot/Commands/CommandHelper.cs new file mode 100644 index 0000000..162c65d --- /dev/null +++ b/DiscordBot/Commands/CommandHelper.cs @@ -0,0 +1,119 @@ +namespace DiscoBot.Auxiliary +{ + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.IO; + using System.Linq; + using System.Net; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + + using Discord; + using Discord.Commands; + + public static class CommandHelper + { + private static WebClient client; + + public static async Task ReplyTimedAsync(this ModuleBase m, string message, TimeSpan time) + { + var token = message.GetHashCode(); + var send = m.Context.Channel.SendMessageAsync($"#{token}\n```xl\n{message}```", false); + + var barInvoker = new BackgroundWorker(); + barInvoker.DoWork += delegate + { + Thread.Sleep(time); + Delete(token, m); + }; + + await send; + barInvoker.RunWorkerAsync(); + } + + private static void Delete(int token, ModuleBase m) + { + var messagesAsync = m.Context.Channel.GetMessagesAsync(); + Task.WaitAll(messagesAsync.ToArray()); + var list = messagesAsync.ToEnumerable().ToList(); + var messages = new List<IMessage>(); + foreach (var task in list) + { + messages.AddRange(task.ToList()); + } + + var test = messages.Where(x => x.Content.StartsWith($"#{token}\n") && x.Author.IsBot).Select(c=>c ); + var waiters = new List<Task>(); + foreach (var message in test) + { + waiters.Add((message as IUserMessage).DeleteAsync()); + } + Task.WaitAll(waiters.ToArray()); + } + + public static async Task ReplyAsync(this ModuleBase m, IEnumerable<string> message, bool directMessage = false) + { + var sb = new StringBuilder(); + foreach (string re in message) + { + if (sb.Length + re.Length > 1798) + { + if (directMessage) + { + await m.Context.User.SendMessageAsync("```xl\n" + sb + "\n```"); + } + else + { + await m.Context.Channel.SendMessageAsync("```xl\n" + sb + "\n```"); + } + + sb.Clear(); + } + + sb.AppendLine(re); + } + + if (directMessage) + { + await m.Context.User.SendMessageAsync("```xl\n" + sb + "\n```"); + } + else + { + await m.Context.Channel.SendMessageAsync("```xl\n" + sb + "\n```"); + } + } + + public static async Task ReplyAsync(this ModuleBase m, IEnumerable<string> message, TimeSpan time) + { + var sb = new StringBuilder(); + foreach (string re in message) + { + if (sb.Length + re.Length > 1798) + { + + await m.ReplyTimedAsync(sb.ToString(), time); + + + sb.Clear(); + } + + sb.AppendLine(re); + } + + await m.ReplyTimedAsync(sb.ToString(), TimeSpan.FromSeconds(90)); + } + + public static async Task SendWebFile(this IMessageChannel channel, string url = "https://i.imgur.com/0iHEycJ.png") + { + if (client == null) + { + client = new WebClient(); + } + + Stream stream = client.OpenRead(url); + await channel.SendFileAsync(stream, url.Split('/').Last()); + } + } +} diff --git a/DiscordBot/Commands/FileHandler.cs b/DiscordBot/Commands/FileHandler.cs new file mode 100644 index 0000000..e3cd82d --- /dev/null +++ b/DiscordBot/Commands/FileHandler.cs @@ -0,0 +1,24 @@ +using System; +using System.Linq; +using Discord.Commands; + +namespace DiscordBot.Commands +{ + public class FileHandler : ModuleBase + { + //[Command("send"), Summary("fügt Helden hinzu")] + public void AddChar() + { + var msg = Context.Message; + if (msg.Attachments == null) throw new ArgumentException("Es wurde keine Datei angehängt"); + + var attachments = msg.Attachments.ToList(); + + if (!attachments.Any(x => x.Filename.EndsWith(".xml"))) + throw new ArgumentException("Es wurde kein xml Held mitgeschickt"); + + foreach (var attachment in attachments.Where(x => x.Filename.EndsWith(".xml"))) + throw new NotImplementedException("send File to Server"); + } + } +}
\ No newline at end of file diff --git a/DiscordBot/Commands/MiscCommands.cs b/DiscordBot/Commands/MiscCommands.cs new file mode 100644 index 0000000..5707de7 --- /dev/null +++ b/DiscordBot/Commands/MiscCommands.cs @@ -0,0 +1,190 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DiscoBot.Auxiliary; +using Discord; +using Discord.Commands; +using DiscordBot.Auxiliary; + +namespace DiscordBot.Commands +{ + public class MiscCommands : ModuleBase + { + [Command("r")] + [Summary("Würfelt ")] + [Alias("R", "Roll", "roll", "Würfle")] + public Task RollAsync([Remainder] [Summary("Weapon")] string roll) + { + //return this.ReplyAsync("```xl\n" + new Auxiliary.Calculator.StringSolver(roll).Solve() + "\n```"); + return ReplyAsync("```xl\n" + RandomMisc.Roll(roll) + "\n```"); + } + + + [Command("say")] + [Summary("Echos a message.")] + [Alias("s")] + public Task SayAsync([Remainder] [Summary("The text to echo")] + string echo) + { + return ReplyAsync(echo); + } + + [Command("liebe")] + [Summary("Echos a message.")] + [Alias("Liebe", "<3", "love")] + public async Task LoveAsync() + { + var rand = new Random(); + var user = Context.Channel.GetUsersAsync().ToList().Result.ToList().First() + .Where(x => x.Status != UserStatus.Offline).OrderBy(x => rand.Next()).First(); + await ReplyAsync( + ":heart: :heart: :heart: Verteilt die Liebe! :heart: :heart: :heart: \n Besondere Liebe geht an " + + user.Username); + //await this.ReplyAsync("!liebe"); + } + + [Command("maul")] + [Summary("Echos a message.")] + public Task MaulAsync() + { + return ReplyAsync( + "Maul...? Du meintest doch sicher Maulwürfe oder? \n:heart: :heart: :heart: \nGanz viel Liebe für Maulwürfe !\n:heart: :heart: :heart:"); + } + + + [Command("match")] + [Summary("Tinder.")] + [Alias("mach", "pass", "passt")] + public Task TinderAsync(string s1, string s2) + { + var rand = new Random((s1 + s2).GetHashCode()); + + var wert = Math.Log10(Math.Floor(1000.0 * (SpellCorrect.CompareExact(s1, s2) + rand.NextDouble() * 10.0)) / + 1000.0); + wert = wert * 100.0 < 100.0 ? wert * 100.0 : 100.0 - wert; + wert = wert < 0 ? -wert : wert; + return ReplyAsync($"Ihr passt zu {Math.Floor(100.0 * wert) / 100.0}% zusammen"); + } + + [Command("reddit")] + [Summary("Reddit.")] + public Task RedditAsync() + { + return ReplyAsync( + "Ein Archiv der Vergangenen Aktionen findet man hier: https://www.reddit.com/r/ReconquistaInternet/"); + } + + [Command("compare")] + [Summary("Echos a message.")] + public async Task KickAsync() + { + //await this.Context.Guild.DownloadUsersAsync(); + var users = Context.Guild.GetUsersAsync(); + var test = File.ReadAllLines("RG.txt"); + await users; + var us = users.Result.Select(x => x.Username); + + var lines = test.Where(x => !x.Equals(string.Empty)).ToList(); + + + var sc = new SpellCorrect(); + + var res = new List<string>(); + + foreach (var line in lines) + { + var best = us.OrderBy(user => sc.Compare(user, line)).First(); + + double fit = sc.Compare(best, line); + + if (!(fit < SpellCorrect.ErrorThreshold - 20000)) continue; + res.Add(fit.Equals(0) ? $"@\t{best} !!! => {line}" : $"-\t{best} hat Ähnlichkeit mit: {line}"); + } + + var sb = new StringBuilder(); + foreach (var re in res) + { + if (sb.Length + re.Length > 1798) + { + await CommandHelper.ReplyTimedAsync(this, sb.ToString(), TimeSpan.FromSeconds(90)); + sb.Clear(); + } + + sb.AppendLine(re); + } + + if (Permissions.Check(Context, new[] {"Admin", "Mod"})) + await CommandHelper.ReplyTimedAsync(this, sb.ToString(), TimeSpan.FromSeconds(90)); + + //await this.ReplyAsync($"{count} Duplikate gefunden"); + } + + + [Command("clear")] + [Summary("Cleans up messages.")] + public void DeleteAsync(int count) + { + var messagesAsync = Context.Channel.GetMessagesAsync(count); + if (messagesAsync != null) + { + Task.WaitAll(messagesAsync.ToArray()); + var list = messagesAsync.ToEnumerable().ToList(); + var messages = new List<IMessage>(); + foreach (var task in list) messages.AddRange(task.ToList()); + + if (Permissions.Check(Context, new[] {"Admin", "Mod", "Meister"})) + { + var waiters = new List<Task>(); + foreach (var message in messages) waiters.Add(((IUserMessage) message).DeleteAsync()); + + Task.WaitAll(waiters.ToArray()); + } + } + } + + [Command("check")] + [Summary("Echos a message.")] + [Alias("Check")] + public async Task CheckAsync(string quarry) + { + var perm = new List<string> {"Admin", "Mod", "Privatpolizei"}; + + Permissions.Test(Context, perm.ToArray()); + + var test = File.ReadAllLines("RG.txt"); + + var lines = test.Where(x => !x.Equals(string.Empty)).ToList(); + + + var sc = new SpellCorrect(); + var count = lines.OrderBy(line => sc.Compare(quarry, line)).First(); + + var fit = sc.Compare(count, quarry); + + string antwort; + + antwort = fit < SpellCorrect.ErrorThreshold - 20000 + ? $"```xl\nAuf anderem Server Match gefunden: {count}" + : $"```xl\nAuf anderem Server Kein Match gefunden: {quarry}"; + + + var users = Context.Guild.GetUsersAsync(); + await users; + var us = users.Result.Select(x => x.Username); + + sc = new SpellCorrect(); + count = us.OrderBy(line => sc.Compare(quarry, line)).First(); + + fit = sc.Compare(count, quarry); + + antwort = fit < SpellCorrect.ErrorThreshold - 20000 + ? $"{antwort}\nAuf unserem Server Match gefunden: {count}\n```" + : $"{antwort}\nAuf unserem Server Kein Match gefunden: {quarry} \n```"; + + await ReplyAsync(antwort); + } + } +}
\ No newline at end of file diff --git a/DiscordBot/DiscordBot.csproj b/DiscordBot/DiscordBot.csproj new file mode 100644 index 0000000..620a3a6 --- /dev/null +++ b/DiscordBot/DiscordBot.csproj @@ -0,0 +1,12 @@ +<Project Sdk="Microsoft.NET.Sdk"> + + <PropertyGroup> + <OutputType>Exe</OutputType> + <TargetFramework>netcoreapp2.2</TargetFramework> + </PropertyGroup> + + <ItemGroup> + <PackageReference Include="Discord.Net" Version="2.1.0" /> + </ItemGroup> + +</Project> diff --git a/DiscordBot/Program.cs b/DiscordBot/Program.cs new file mode 100644 index 0000000..60febcd --- /dev/null +++ b/DiscordBot/Program.cs @@ -0,0 +1,58 @@ +using System; +using System.IO; +using System.Linq; +using System.Net; +using System.Threading.Tasks; +using Discord; +using Discord.Commands; +using Discord.WebSocket; + +namespace DiscordBot +{ + class Program + { + public static void Main(string[] args) + => new Program().MainAsync().GetAwaiter().GetResult(); + + private DiscordSocketClient _client; + private CommandHandler cHandler; + + public async Task MainAsync() + { + _client = new DiscordSocketClient(); + + _client.Log += Log; + + + cHandler = new CommandHandler(_client, new CommandService()); + // Remember to keep token private or to read it from an + // external source! In this case, we are reading the token + // from an environment variable. If you do not know how to set-up + // environment variables, you may find more information on the + // Internet or by using other methods such as reading from + // a configuration. + await cHandler.InstallCommandsAsync(); + + try + { + await _client.LoginAsync(TokenType.Bot, + Environment.GetEnvironmentVariable("DiscordToken")); + } + catch + { + await _client.LoginAsync(TokenType.Bot, File.ReadAllText("Token")); + } + + await _client.StartAsync(); + + // Block this task until the program is closed. + await Task.Delay(-1); + } + + private Task Log(LogMessage msg) + { + Console.WriteLine(msg.ToString()); + return Task.CompletedTask; + } + } +} diff --git a/DiscordBot/Rework/Permissions.cs b/DiscordBot/Rework/Permissions.cs new file mode 100644 index 0000000..119e628 --- /dev/null +++ b/DiscordBot/Rework/Permissions.cs @@ -0,0 +1,38 @@ +using System.Linq; +using Discord.Commands; +using Discord.WebSocket; + +namespace DiscordBot.Rework +{ + public static class Permissions + { + public static bool Check(ICommandContext c, string role) + { + return ((SocketGuildUser)c.User).Roles.ToList().Exists(v => v.Name.Equals(role)); + } + + public static bool Check(ICommandContext c, string[] roles) + { + return roles.Any(role => ((SocketGuildUser)c.User).Roles.ToList().Exists(v => v.Name.Equals(role))); + } + + public static bool Test(ICommandContext c, string role) + { + if (!Check(c, role)) + { + c.Channel.SendMessageAsync("```xl\n Keine ausreichenden Berechtigungen\n```").Wait(); + return false; + } + + return true; + } + + public static void Test(ICommandContext c, string[] roles) + { + if (!Check(c, roles)) + { + c.Channel.SendMessageAsync("```xl\n Keine ausreichenden Berechtigungen\n```").Wait(); + } + } + } +} |