コード例 #1
0
ファイル: Program.cs プロジェクト: NorbiPeti/DiscordSharp
        static Task ClientTask(DiscordClient client)
        {
            return(Task.Run(() =>
            {
                client.MessageReceived += (sender, e) =>
                {
                    string message = e.message.content;
                    if (message[0] == '?')
                    {
                        message = message.Substring(1); //to remove the command prefix
                        try
                        {
                            CommandManager.ExecuteCommand(message, e.Channel, e.author);
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            e.Channel.SendMessage(ex.Message);
                        }
                    }
                };
                client.Connected += (sender, e) =>
                {
                    Console.WriteLine("Connected as " + e.user.Username);
                    CommandManager = new CommandsManager(client);
                    CommandManager.AddCommand(new CommandStub("joinvoice",
                                                              "Joins a voice channel",
                                                              "Usage: ?joinvoice <channel name>", PermissionType.Owner, cmdArgs =>
                    {
                        if (cmdArgs.Args.Count < 1)
                        {
                            return;
                        }
                        DiscordChannel toJoin = cmdArgs.Channel.parent.channels.Find(x => (x.Name.ToLower() == cmdArgs.Args[0].ToLower() && x.Type == ChannelType.Voice));
                        if (toJoin != null)
                        {
                            client.ConnectToVoiceChannel(toJoin);
                        }
                    }));
                    CommandManager.AddCommand(new CommandStub("disconnect", "Disconnects from a voice channel.", "", PermissionType.Owner, cmdArgs =>
                    {
                        if (client.ConnectedToVoice())
                        {
                            client.DisconnectFromVoice();
                        }
                    }));
                    CommandManager.AddCommand(new CommandStub("khaled", "Anotha one.", "", cmdArgs =>
                    {
                        cmdArgs.Channel.SendMessage("Anotha one.\n***Bless up***");
                    }));
                    CommandManager.AddCommand(new CommandStub("test", "Tests", "", cmdArgs =>
                    {
                        cmdArgs.Channel.SendMessage("Hey whassup hello.");
                    }));

                    DiscordMember owner = client.GetServersList().Find(x => x.members.Find(y => y.Username == "Axiom") != null).members.Find(x => x.Username == "Axiom");
                    //CommandManager.AddPermission(owner, PermissionType.Owner);
                };
                client.Connect();
            }));
        }
コード例 #2
0
 private void Execute()
 {
     if (SelectedCommand != null)
     {
         _commandsManager.ExecuteCommand(SelectedCommand);
     }
     CommandsChain.Clear();
     Input = String.Empty;
 }
コード例 #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.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));
        }
コード例 #4
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));
        }