private void ProcessCommand(string rawString, MessageCreateEventArgs e, CommandTrigger type) { // The first thing we do is get rid of the prefix string from the command. We take the message from looking like say this: // --say something // to // say something // that way we don't have any excess characters getting in the way. string rawCommand = rawString.Substring(config.Prefix.Length); // A try catch block for executing the command and catching various things and reporting on errors. try { if (type == CommandTrigger.MessageCreate) { commandManager.ExecuteOnMessageCommand(rawCommand, e.Channel, e.Author, e.Message, client); } else if (type == CommandTrigger.BotMentioned) { commandManager.ExecuteOnMentionCommand(rawCommand, e.Channel, e.Author, e.Message, client); } } catch (UnauthorizedAccessException ex) // Bad permission { e.Channel.SendMessageAsync(ex.Message); } catch (ModuleNotEnabledException x) // Module is disabled { e.Channel.SendMessageAsync($"{x.Message}"); } catch (Exception ex) // Any other error that could happen inside of the commands. { e.Channel.SendMessageAsync("Exception occurred while running command:\n```\n" + ex.Message + "\n```"); } }
private Task SetupEvents(CancellationToken token) { Console.ForegroundColor = ConsoleColor.White; return(Task.Run(() => { client.MessageReceived += (sender, e) => { if (!doingInitialRun) { if (owner == null) { owner = client.GetServersList().Find(x => x.GetMemberByKey(config.OwnerID) != null).GetMemberByKey(config.OwnerID); //prays } } if (e.Author == null) { string msg = $"Author had null id in message received!\nRaw JSON:\n```\n{e.RawJson}\n```\n"; msg += $"Args\nChannel: {e.Channel.Name}/{e.Channel.ID}\nMessage: {e.Message}"; try { owner.SlideIntoDMs(msg); } catch { } } else { Console.WriteLine($"[-- Message from {e.Author.Username} in #{e.Channel.Name} on {e.Channel.Parent.Name}: {e.Message.Content}"); if (doingInitialRun) { if (e.Message.Content.StartsWith("?authenticate")) { string[] split = e.Message.Content.Split(new char[] { ' ' }, 2); if (split.Length > 1) { if (codeToEnter.Trim() == split[1].Trim()) { config.OwnerID = e.Author.ID; doingInitialRun = false; e.Channel.SendMessage("Authentication successful! **You are now my owner, " + e.Author.Username + ".**"); CommandsManager.AddPermission(e.Author, PermissionType.Owner); owner = e.Author; } } } } else { if (e.Message.Content.Length > 0 && (e.Message.Content[0] == config.CommandPrefix)) { string rawCommand = e.Message.Content.Substring(1); try { CommandsManager.ExecuteOnMessageCommand(rawCommand, e.Channel, e.Author); } catch (UnauthorizedAccessException ex) { e.Channel.SendMessage(ex.Message); } catch (ModuleNotEnabledException x) { e.Channel.SendMessage($"{x.Message}"); } catch (Exception ex) { e.Channel.SendMessage("Exception occurred while running command:\n```" + ex.Message + "\n```"); } } } //Now, for fun. //if(e.author == owner) //{ // if (StringContainsObjectInArray(e.message.content.ToLower(), NaughtyWords)) // { // try // { // var msg = client.GetMessageLog()[client.GetMessageLog().Count - 1].Value; // if (msg.author == owner // && client.GetLastMessageSent(e.Channel).content != null && // client.GetLastMessageSent(e.Channel).content != "hey now") // { // //if(msg.timestamp.AddMinutes(1) < DateTime.Now) // int timebetween = (DateTime.Now.Minute - msg.timestamp.Minute); // if ((timebetween < 1) && (timebetween > -1)) //less than one minute between his message and my vulgarity // e.Channel.SendMessage("hey now"); // } // } // catch { } // } //} if (e.Channel.ID == "91265608326324224") //discord-sharp on discordapi { if (e.Author != owner) { if (e.Message.Content != null && e.Message.Content.ToLower().Contains("how")) { if (e.Message.Content.ToLower().Contains("bot") && e.Message.Content.ToLower().Contains("tag")) { e.Channel.SendMessage($"<#124294271900712960>");//#api-changes } } } } } }; client.VoiceClientDebugMessageReceived += (sender, e) => { if (e.message.Level != MessageLevel.Unecessary) { Console.WriteLine($"[{e.message.Level} {e.message.TimeStamp.ToString()}] {e.message.Message}"); } }; client.VoiceClientConnected += (sender, e) => { try { owner.SlideIntoDMs($"Voice connection complete."); } catch { } //player = new AudioPlayer(client.GetVoiceClient().VoiceConfig); //bufferedWaveProvider = new BufferedWaveProvider(waveFormat); //bufferedWaveProvider.BufferDuration = new TimeSpan(0, 0, 50); //volumeProvider = new VolumeWaveProvider16(bufferedWaveProvider); //volumeProvider.Volume = 1.1f; //outputDevice.Init(volumeProvider); //stutterReducingTimer = new System.Timers.Timer(500); //stutterReducingTimer.Elapsed += StutterReducingTimer_Elapsed; //PlayAudioAsync(cancelToken); }; client.AudioPacketReceived += (sender, e) => { if (bufferedWaveProvider != null) { byte[] potential = new byte[4000]; int decodedFrames = client.GetVoiceClient().Decoder.DecodeFrame(e.OpusAudio, 0, e.OpusAudioLength, potential); bufferedWaveProvider.AddSamples(potential, 0, decodedFrames); } }; client.GuildCreated += (sender, e) => { if (owner == null) { owner = client.GetServersList().Find(x => x.GetMemberByKey(config.OwnerID) != null).GetMemberByKey(config.OwnerID); } Console.WriteLine($"Joined server {e.Server.Name} ({e.Server.ID})"); try { owner.SlideIntoDMs($"Joined server {e.Server.Name} ({e.Server.ID})"); } catch { } }; client.GuildAvailable += (sender, e) => { Console.WriteLine($"Guild {e.Server.Name} became available."); }; client.SocketClosed += (sender, e) => { Console.Title = "Luigibot - Discord - Socket Closed.."; if (!actuallyExit) { WriteError($"\n\nSocket Closed Unexpectedly! Code: {e.Code}. Reason: {e.Reason}. Clear: {e.WasClean}.\n\n"); Console.WriteLine("Waiting 6 seconds to reconnect.."); Thread.Sleep(6 * 1000); LetsGoAgain(); } else { Console.WriteLine($"Shutting down ({e.Code}, {e.Reason}, {e.WasClean})"); } }; client.UnknownMessageTypeReceived += (sender, e) => { if (!Directory.Exists("dumps")) { Directory.CreateDirectory("dumps"); } string message = $"Ahoy! An unknown message type `{e.RawJson["t"].ToString()}` was discovered with the contents: \n\n"; message += $"```\n{e.RawJson.ToString()}\n```\nIt's been dumped to `dumps/{e.RawJson["t"].ToString()}.json` for your viewing pleasure."; string filename = $"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}dumps{Path.DirectorySeparatorChar}{e.RawJson["t"].ToString()}.json"; if (!File.Exists(filename)) { File.WriteAllText(e.RawJson.ToString(), filename); try { owner.SlideIntoDMs(message); } catch { } } }; client.TextClientDebugMessageReceived += (sender, e) => { if (e.message.Level == MessageLevel.Error || e.message.Level == MessageLevel.Critical) { WriteError($"(Logger Error) {e.message.Message}"); try { owner.SlideIntoDMs($"Bot error ocurred: ({e.message.Level.ToString()})```\n{e.message.Message}\n```"); } catch { } } if (e.message.Level == MessageLevel.Warning) { WriteWarning($"(Logger Warning) {e.message.Message}"); } }; client.Connected += (sender, e) => { Console.Title = "Luigibot - Discord - Logged in as " + e.User.Username; Console.WriteLine("Connected as " + e.User.Username); if (!String.IsNullOrEmpty(config.OwnerID)) { } else { doingInitialRun = true; RandomCodeGenerator rcg = new RandomCodeGenerator(); codeToEnter = rcg.GenerateRandomCode(); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("Important: "); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("\tPlease authenticate yourself as owner by typing the following into any Discord server you and the bot are in: "); Console.WriteLine($"\t{config.CommandPrefix}authenticate " + codeToEnter); } CommandsManager = new CommandsManager(client); if (File.Exists("permissions.json")) { var permissionsDictionary = JsonConvert.DeserializeObject <Dictionary <string, PermissionType> >(File.ReadAllText("permissions.json")); if (permissionsDictionary == null) { permissionsDictionary = new Dictionary <string, PermissionType>(); } if (permissionsDictionary.Count == 0 && owner != null) { permissionsDictionary.Add(owner.ID, PermissionType.Owner); } CommandsManager.OverridePermissionsDictionary(permissionsDictionary); } SetupCommands(); if (config.ModulesDictionary != null) { CommandsManager.OverrideModulesDictionary(config.ModulesDictionary); } //client.UpdateCurrentGame($"DiscordSharp {typeof(DiscordClient).Assembly.GetName().Version.ToString()}"); }; if (client.SendLoginRequest() != null) { client.Connect(UseBuiltInWebsocket); } }, token)); }
private void SetUpEvents() { this._client.Connected += (sender, e) => { Console.Title = $"KWRBot - Discord - logged in as {e.User.Username}"; Console.WriteLine($"Connected! Username: {e.User.Username}"); }; this._client.MessageReceived += (sender, e) => { if (owner == null) { owner = this._client.GetServerChannelIsIn(e.Channel).GetMemberByKey(this._config.OwnerID); } if (e.Author != owner && e.Author.Username != this._client.ClientPrivateInformation.Username) { Console.WriteLine($"Messag received from {e.Author.Username}: \"{e.MessageText}\""); } if (e.Message.Content.Length > 0 && e.Message.Content[0] == this._config.CommandPrefix && e.Author.ID != this._config.BotID) { string rawCommand = e.Message.Content.Substring(1); try { CommandsManager.ExecuteOnMessageCommand(rawCommand, e.Channel, e.Author); } catch (UnauthorizedAccessException) { this._client.SendMessageToChannel("You don't have permission to execute this command. Contact administrator for additional information", e.Channel); Console.WriteLine($"{e.Author.Username} attempted to execute command with low access level"); } } }; this._client.PrivateMessageReceived += (sender, e) => { if (e.Author.ID != this._config.OwnerID) { Console.WriteLine($"Private message received from {e.Author.Username}: \"{e.Message}\""); } if (e.Message.Length > 0 && e.Message[0] == this._config.CommandPrefix) { string rawCommand = e.Message.Substring(1); if (e.Author.ID == this._config.OwnerID) { this._client.AcceptInvite(rawCommand.Substring(rawCommand.LastIndexOf('/') + 1)); } } if (e.Message.StartsWith("?authenticate") && owner == null) { Console.BackgroundColor = ConsoleColor.Red; Console.Write("Kerrang!\nIn order to become an owner type in bot's password: "******"I'm welcoming you, my current owner {e.Author.Username}"); } Console.BackgroundColor = ConsoleColor.Black; owner.SlideIntoDMs("Welcome long lost father!"); File.WriteAllText(Path.GetFullPath("settings.json"), JsonConvert.SerializeObject(this._config)); } }; this._client.GuildCreated += (sender, e) => { Console.WriteLine($"Joined server: {e.Server.Name} ({e.Server.ID})"); }; }