Esempio n. 1
0
        private Task SetupEvents(CancellationToken token)
        {
            Console.ForegroundColor = ConsoleColor.White;
            return(Task.Run(() =>
            {
                client.MessageReceived += (sender, e) =>
                {
                    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.ExecuteCommand(rawCommand, e.Channel, e.author);
                            }
                            catch (UnauthorizedAccessException ex)
                            {
                                e.Channel.SendMessage(ex.Message);
                            }
                            catch (Exception ex)
                            {
                                e.Channel.SendMessage("Exception occurred while running command:\n```" + ex.Message + "\n```");
                            }
                        }
                    }
                };
                client.GuildCreated += (sender, e) =>
                {
                    Console.WriteLine("Joined server " + e.server.name);
                };
                client.Connected += (sender, e) =>
                {
                    Console.WriteLine("Connected as " + e.user.Username);
                    loginDate = DateTime.Now;

                    if (!String.IsNullOrEmpty(config.OwnerID))
                    {
                        owner = client.GetServersList().Find(x => x.members.Find(y => y.ID == config.OwnerID) != null).members.Find(x => x.ID == 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"));
                        CommandsManager.OverridePermissionsDictionary(permissionsDictionary);
                    }
                    SetupCommands();
                };
                if (client.SendLoginRequest() != null)
                {
                    client.Connect();
                }
            }, token));
        }
Esempio n. 2
0
        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));
        }
Esempio n. 3
0
        private Task SetupEvents(CancellationToken token)
        {
            Console.ForegroundColor = ConsoleColor.White;
            return(Task.Run(() =>
            {
                client.MessageReceived += (sender, e) =>
                {
                    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.ExecuteCommand(rawCommand, e.Channel, e.author);
                            }
                            catch (UnauthorizedAccessException ex)
                            {
                                e.Channel.SendMessage(ex.Message);
                            }
                            catch (Exception ex)
                            {
                                e.Channel.SendMessage("Exception occurred while running command:\n```" + ex.Message + "\n```");
                            }
                        }
                    }
                };
                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) =>
                {
                    owner.SlideIntoDMs($"Voice connection complete.");
                    //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) =>
                {
                    owner.SlideIntoDMs($"Joined server {e.server.name} ({e.server.id})");
                };
                client.SocketClosed += (sender, e) =>
                {
                    if (e.Code != 1000 && !e.WasClean)
                    {
                        WriteError($"Socket Closed! Code: {e.Code}. Reason: {e.Reason}. Clear: {e.WasClean}.");
                        Console.WriteLine("Waiting 6 seconds to reconnect..");
                        Thread.Sleep(6 * 1000);
                        client.Connect();
                    }
                    else
                    {
                        Console.WriteLine($"Shutting down ({e.Code}, {e.Reason}, {e.WasClean})");
                    }
                };
                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.WriteLine("Connected as " + e.user.Username);
                    loginDate = DateTime.Now;

                    if (!String.IsNullOrEmpty(config.OwnerID))
                    {
                        owner = client.GetServersList().Find(x => x.members.Find(y => y.ID == config.OwnerID) != null).members.Find(x => x.ID == 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"));
                        CommandsManager.OverridePermissionsDictionary(permissionsDictionary);
                    }
                    SetupCommands();
                };
                if (client.SendLoginRequest() != null)
                {
                    client.Connect();
                }
            }, token));
        }