Ejemplo n.º 1
0
        public UserConnect()
        {
            _config = new Settings();
            _client = new DiscordClient(x =>

            {
                x.AppName  = "EtherealClient";
                x.LogLevel = LogSeverity.Error;
            });


            _client.Log.Message += (s, e) => Console.WriteLine($"[{e.Severity}] [{e.Source}] [User] {e.Message}");

            _client.ExecuteAndWait(async() =>
            {
                while (true)
                {
                    try
                    {
                        await _client.Connect(_config.UserToken, TokenType.User);
                        _client.SetGame(_config.CurrentGame, GameType.Twitch, _config.DiscordUrl);
                        break;
                    }
                    catch (Exception ex)
                    {
                        _client.Log.Error($"Failed to login, retrying in {_client.Config.FailedReconnectDelay}", ex);
                        await Task.Delay(_client.Config.FailedReconnectDelay);
                    }
                }
            });
        }
Ejemplo n.º 2
0
        public static void InitBot()
        {

            bot = new DiscordClient();

            bot.MessageReceived += Bot_MessagedReceived;

            bot.ExecuteAndWait(async () => {
                await bot.Connect(discordBotToken);
            });
        }
Ejemplo n.º 3
0
        public BotConnect()
        {
            _config = new Settings();
            _client = new DiscordClient(x =>

            {
                x.AppName  = "Ethereal";
                x.LogLevel = LogSeverity.Info;
            })
                      .UsingCommands(x =>
            {
                x.PrefixChar = _config.Prefix;
                x.HelpMode   = HelpMode.Public;
            })
                      .UsingPermissionLevels((u, c) => (int)GetPermission(u, c))
                      .UsingModules();

            _client.Log.Message += (s, e) => Console.WriteLine($"[{e.Severity}] [{e.Source}] [Bot] {e.Message}");

            _client.AddModule <Modules.Commands>("Commands", ModuleFilter.None);

            _client.UserJoined += _client_UserJoined;

            _client.UserUpdated += _client_UserUpdated;

            _client.RoleUpdated += _client_RoleUpdated;

            //_client.MessageReceived += _client_MsgReceived;

            _client.ExecuteAndWait(async() =>
            {
                while (true)
                {
                    try
                    {
                        await _client.Connect(_config.BotToken, TokenType.Bot);
                        _client.SetGame(_config.CurrentGame, GameType.Twitch, _config.DiscordUrl);
                        UserConnect userConnect = new UserConnect();
                        return;
                    }
                    catch (Exception ex)
                    {
                        _client.Log.Error("Failed to log in", ex);
                        await Task.Delay(_client.Config.FailedReconnectDelay);
                    }
                }
            });
        }
Ejemplo n.º 4
0
 public void Init(YAMLConfiguration conf)
 {
     try
     {
         Config = conf;
         string token = Config.ReadString("discord.token", null);
         if (token == null)
         {
             Logger.Output(LogType.INFO, "Discord bot not configured!");
             return;
         }
         Client = new DiscordClient();
         Client.MessageReceived += messageReceived;
         Client.ExecuteAndWait(async () => await Client.Connect(token, TokenType.Bot));
     }
     catch (Exception ex)
     {
         Logger.Output(LogType.ERROR, ex.ToString());
     }
 }
Ejemplo n.º 5
0
        public Bot()
        {
            try
            {
                r = new Random();


                discordBot = new DiscordClient(x =>
                {
                    x.AppName    = "IluvatarSuperBot";
                    x.LogLevel   = LogSeverity.Info;
                    x.LogHandler = Log;
                });

                discordBot.UsingCommands(x =>
                {
                    x.PrefixChar         = '~';
                    x.AllowMentionPrefix = true;
                    x.HelpMode           = HelpMode.Public;
                });

                discordBot.UsingPermissionLevels((u, c) => (int)GetPermissions(u, c));

                discordBot.UsingAudio(x =>
                {
                    x.Mode = AudioMode.Outgoing;
                });

                CreateCommand();

                discordBot.ExecuteAndWait(async() =>
                {
                    await discordBot.Connect(token);
                });
            }
            catch (Exception ex) { Console.WriteLine(ex); }
        }
Ejemplo n.º 6
0
        static void Main() {
            //load credentials from credentials.json
            bool loadTrello = false;
            try {
                creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json"));
                botMention = creds.BotMention;
                if (string.IsNullOrWhiteSpace(creds.GoogleAPIKey)) {
                    Console.WriteLine("No google api key found. You will not be able to use music and links won't be shortened.");
                } else {
                    Console.WriteLine("Google API key provided.");
                    GoogleAPIKey = creds.GoogleAPIKey;
                }
                if (string.IsNullOrWhiteSpace(creds.TrelloAppKey)) {
                    Console.WriteLine("No trello appkey found. You will not be able to use trello commands.");
                } else {
                    Console.WriteLine("Trello app key provided.");
                    TrelloAppKey = creds.TrelloAppKey;
                    loadTrello = true;
                }
                if (creds.ForwardMessages != true)
                    Console.WriteLine("Not forwarding messages.");
                else {
                    ForwardMessages = true;
                    Console.WriteLine("Forwarding messages.");
                }
                if(string.IsNullOrWhiteSpace(creds.SoundCloudClientID))
                    Console.WriteLine("No soundcloud Client ID found. Soundcloud streaming is disabled.");
                else
                    Console.WriteLine("SoundCloud streaming enabled.");

                OwnerID = creds.OwnerID;
                password = creds.Password;
            } catch (Exception ex) {
                Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}");
                Console.ReadKey();
                return;
            }

            //create new discord client
            client = new DiscordClient(new DiscordConfigBuilder() {
                MessageCacheSize = 0,
                ConnectionTimeout = 60000,
            });

            //create a command service
            var commandService = new CommandService(new CommandServiceConfigBuilder {
                AllowMentionPrefix = false,
                CustomPrefixHandler = m => 0,
                HelpMode = HelpMode.Disabled
            });
            
            //reply to personal messages and forward if enabled.
            client.MessageReceived += Client_MessageReceived;

            //add command service
            var commands = client.Services.Add<CommandService>(commandService);

            //create module service
            var modules = client.Services.Add<ModuleService>(new ModuleService());

            //add audio service
            var audio = client.Services.Add<AudioService>(new AudioService(new AudioServiceConfigBuilder()  {
                Channels = 2,
                EnableEncryption = false,
                EnableMultiserver = true,
                Bitrate = 128,
            }));

            //install modules
            modules.Add(new Administration(), "Administration", ModuleFilter.None);
            modules.Add(new PermissionModule(), "Permissions", ModuleFilter.None);
            modules.Add(new Conversations(), "Conversations", ModuleFilter.None);
            modules.Add(new Gambling(), "Gambling", ModuleFilter.None);
            modules.Add(new Games(), "Games", ModuleFilter.None);
            modules.Add(new Music(), "Music", ModuleFilter.None);
            modules.Add(new Searches(), "Searches", ModuleFilter.None);
            if (loadTrello)
                modules.Add(new Trello(), "Trello", ModuleFilter.None);
            modules.Add(new NSFW(), "NSFW", ModuleFilter.None);

            //run the bot
            client.ExecuteAndWait(async () => {
                await client.Connect(creds.Username, creds.Password);
                Console.WriteLine("-----------------");
                Console.WriteLine(NadekoStats.Instance.GetStats());
                Console.WriteLine("-----------------");

                try {
                    OwnerPrivateChannel = await client.CreatePrivateChannel(OwnerID);
                } catch  {
                    Console.WriteLine("Failed creating private channel with the owner");
                }

                Classes.Permissions.PermissionsHandler.Initialize();

                client.ClientAPI.SendingRequest += (s, e) =>
                {
                    var request = e.Request as Discord.API.Client.Rest.SendMessageRequest;
                    if (request != null) {
                        if (string.IsNullOrWhiteSpace(request.Content))
                            e.Cancel = true;
                        request.Content = request.Content.Replace("@everyone", "@everyοne");
                    }
                };
            });
            Console.WriteLine("Exiting...");
            Console.ReadKey();
        }        
Ejemplo n.º 7
0
        private static void Main()
        {
            Console.OutputEncoding = Encoding.Unicode;

            try
            {
                File.WriteAllText("data/config_example.json", JsonConvert.SerializeObject(new Configuration(), Formatting.Indented));
                if (!File.Exists("data/config.json"))
                    File.Copy("data/config_example.json", "data/config.json");
                File.WriteAllText("credentials_example.json", JsonConvert.SerializeObject(new Credentials(), Formatting.Indented));

            }
            catch
            {
                Console.WriteLine("Failed writing credentials_example.json or data/config_example.json");
            }

            try
            {
                Config = JsonConvert.DeserializeObject<Configuration>(File.ReadAllText("data/config.json"));
                Config.Quotes = JsonConvert.DeserializeObject<List<Quote>>(File.ReadAllText("data/quotes.json"));
                Config.PokemonTypes = JsonConvert.DeserializeObject<List<PokemonType>>(File.ReadAllText("data/PokemonTypes.json"));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed loading configuration.");
                Console.WriteLine(ex);
                Console.ReadKey();
                return;
            }

            try
            {
                //load credentials from credentials.json
                Creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json"));
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}");
                Console.ReadKey();
                return;
            }

            //if password is not entered, prompt for password
            if (string.IsNullOrWhiteSpace(Creds.Token))
            {
                Console.WriteLine("Token blank. Please enter your bot's token:\n");
                Creds.Token = Console.ReadLine();
            }

            Console.WriteLine(string.IsNullOrWhiteSpace(Creds.GoogleAPIKey)
                ? "No google api key found. You will not be able to use music and links won't be shortened."
                : "Google API key provided.");
            Console.WriteLine(string.IsNullOrWhiteSpace(Creds.TrelloAppKey)
                ? "No trello appkey found. You will not be able to use trello commands."
                : "Trello app key provided.");
            Console.WriteLine(Config.ForwardMessages != true
                ? "Not forwarding messages."
                : "Forwarding private messages to owner.");
            Console.WriteLine(string.IsNullOrWhiteSpace(Creds.SoundCloudClientID)
                ? "No soundcloud Client ID found. Soundcloud streaming is disabled."
                : "SoundCloud streaming enabled.");
            Console.WriteLine(string.IsNullOrWhiteSpace(Creds.OsuAPIKey)
                ? "No osu! api key found. Song & top score lookups will not work. User lookups still available."
                : "osu! API key provided.");
            Console.WriteLine(string.IsNullOrWhiteSpace(Creds.DerpiAPIKey)
                ? "No Derpiboori api key found. Only searches useing the Default filter will work."
                : "Derpiboori API key provided.");

            BotMention = $"<@{Creds.BotId}>";

            //create new discord client and log
            Client = new DiscordClient(new DiscordConfigBuilder()
            {
                MessageCacheSize = 10,
                ConnectionTimeout = int.MaxValue,
                LogLevel = LogSeverity.Warning,
                LogHandler = (s, e) =>
                    Console.WriteLine($"Severity: {e.Severity}" +
                                      $"ExceptionMessage: {e.Exception?.Message ?? "-"}" +
                                      $"Message: {e.Message}"),
            });

            //create a command service
            var commandService = new CommandService(new CommandServiceConfigBuilder
            {
                AllowMentionPrefix = false,
                CustomPrefixHandler = m => 0,
                HelpMode = HelpMode.Disabled,
                ErrorHandler = async (s, e) =>
                {
                    if (e.ErrorType != CommandErrorType.BadPermissions)
                        return;
                    if (string.IsNullOrWhiteSpace(e.Exception?.Message))
                        return;
                    try
                    {
                        await e.Channel.SendMessage(e.Exception.Message).ConfigureAwait(false);
                    }
                    catch { }
                }
            });

            //add command service
            Client.AddService<CommandService>(commandService);

            //create module service
            var modules = Client.AddService<ModuleService>(new ModuleService());

            //add audio service
            Client.AddService<AudioService>(new AudioService(new AudioServiceConfigBuilder()
            {
                Channels = 2,
                EnableEncryption = false,
                Bitrate = 128,
            }));

            //install modules
            modules.Add(new HelpModule(), "Help", ModuleFilter.None);
            modules.Add(new AdministrationModule(), "Administration", ModuleFilter.None);
            modules.Add(new UtilityModule(), "Utility", ModuleFilter.None);
            modules.Add(new PermissionModule(), "Permissions", ModuleFilter.None);
            modules.Add(new Conversations(), "Conversations", ModuleFilter.None);
            modules.Add(new GamblingModule(), "Gambling", ModuleFilter.None);
            modules.Add(new GamesModule(), "Games", ModuleFilter.None);
#if !NADEKO_RELEASE
            modules.Add(new MusicModule(), "Music", ModuleFilter.None);
#endif
            modules.Add(new SearchesModule(), "Searches", ModuleFilter.None);
            modules.Add(new NSFWModule(), "NSFW", ModuleFilter.None);
            modules.Add(new ClashOfClansModule(), "ClashOfClans", ModuleFilter.None);
            modules.Add(new PokemonModule(), "Pokegame", ModuleFilter.None);
            modules.Add(new TranslatorModule(), "Translator", ModuleFilter.None);
            modules.Add(new CustomReactionsModule(), "Customreactions", ModuleFilter.None);
            if (!string.IsNullOrWhiteSpace(Creds.TrelloAppKey))
                modules.Add(new TrelloModule(), "Trello", ModuleFilter.None);

            //run the bot
            Client.ExecuteAndWait(async () =>
            {
                await Task.Run(() =>
                {
                    Console.WriteLine("Specific config started initializing.");
                    var x = SpecificConfigurations.Default;
                    Console.WriteLine("Specific config done initializing.");
                });

                await PermissionsHandler.Initialize();

                try
                {
                    await Client.Connect(Creds.Token, TokenType.Bot).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Token is wrong. Don't set a token if you don't have an official BOT account.");
                    Console.WriteLine(ex);
                    Console.ReadKey();
                    return;
                }
#if NADEKO_RELEASE
                await Task.Delay(300000).ConfigureAwait(false);
#else
                await Task.Delay(1000).ConfigureAwait(false);
#endif

                Console.WriteLine("-----------------");
                Console.WriteLine(await NadekoStats.Instance.GetStats().ConfigureAwait(false));
                Console.WriteLine("-----------------");


                OwnerPrivateChannels = new List<Channel>(Creds.OwnerIds.Length);
                foreach (var id in Creds.OwnerIds)
                {
                    try
                    {
                        OwnerPrivateChannels.Add(await Client.CreatePrivateChannel(id).ConfigureAwait(false));
                    }
                    catch
                    {
                        Console.WriteLine($"Failed creating private channel with the owner {id} listed in credentials.json");
                    }
                }
                Client.ClientAPI.SendingRequest += (s, e) =>
                {
                    var request = e.Request as Discord.API.Client.Rest.SendMessageRequest;
                    if (request == null) return;
                    // meew0 is magic
                    request.Content = request.Content?.Replace("@everyone", "@everyοne").Replace("@here", "@һere") ?? "_error_";
                    if (string.IsNullOrWhiteSpace(request.Content))
                        e.Cancel = true;
                };
#if NADEKO_RELEASE
                Client.ClientAPI.SentRequest += (s, e) =>
                {
                    Console.WriteLine($"[Request of type {e.Request.GetType()} sent in {e.Milliseconds}]");

                    var request = e.Request as Discord.API.Client.Rest.SendMessageRequest;
                    if (request == null) return;

                    Console.WriteLine($"[Content: { request.Content }");
                };
#endif
                NadekoBot.Ready = true;
                NadekoBot.OnReady();
                Console.WriteLine("Ready!");
                //reply to personal messages and forward if enabled.
                Client.MessageReceived += Client_MessageReceived;
            });
            Console.WriteLine("Exiting...");
            Console.ReadKey();
        }
Ejemplo n.º 8
0
Archivo: Tars.cs Proyecto: xJon/TARSbot
        public Tars()
        {
            client = new DiscordClient();
            timer = new Timer(UpdateGameTimer, client, 3000, 14400000);
            commands = new Dictionary<string, Func<CommandArgs, Task>>();
            Commands.Init(commands);
            client.Log.Message += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}");
            client.MessageReceived += async (s, e) =>
            {
                if (e.Channel.IsPrivate)
                {
                    CommandArgs dm = new CommandArgs(e);
                    if (dm.Message.RawText.ToLower() == "tars help")
                        await e.Channel.SendMessage(Util.GetInfo());
                    else
                    {
                        ulong id = 0;
                        if (dm.Args.Count() >= 2 && dm.Message.RawText.ToLower().StartsWith("tars getprefix") && ulong.TryParse(dm.Args.ElementAt(1), out id))
                            await e.Channel.SendMessage("That server's prefix is: `" + DataBase.GetServerPrefix(id) + "`");
                    }
                    return;
                }

                Console.WriteLine("[{0}] [{1}] [{2}]: {3}", e.Server.Name, e.Channel.Name, e.User.Name, e.Message.Text);

                if (e.Message.IsAuthor)
                    return;

                if (e.Message.IsMentioningMe() && DataBase.IsUniqueUser(e.User.Id))
                {
                    await e.Channel.SendMessage(e.User.Mention + " " + Util.GetRandomHump());
                    return;
                }

                if (e.Message.RawText.ToLower().Contains("so i guess it's a") || e.Message.RawText.ToLower().Contains("so i suppose it's a"))
                {
                    await e.Channel.SendFile("images/ADate.jpg");
                    return;
                }

                if (e.Message.RawText.ToLower().Equals("ayy"))
                {
                    await e.Channel.SendMessage("lmao");
                    return;
                }

                if (e.Message.RawText.ToLower().StartsWith("present new changes"))
                {
                    await e.Channel.SendMessage("In your lame life nothing has changed.\nAnd it's even sadder when you realize " + e.User.Mention + " made me say it.");
                    return;
                }

                if (e.Message.RawText.ToLower().Equals("tars help"))
                {
                    string currentPrefix = DataBase.GetServerPrefix(e.Server.Id);
                    if (currentPrefix.ToLower() != "tars")
                    {
                        await e.Channel.SendMessage("TARS' prefix for this server is: `" + currentPrefix + "`\nUse `" + currentPrefix + " info`");
                        return;
                    }
                }

                prefix = DataBase.GetServerPrefix(e.Server.Id).Trim().ToLower();
                if (!e.Message.RawText.ToLower().StartsWith(prefix))
                    return;

                var trigger = string.Join("", e.Message.RawText.Substring(prefix.Length + 1).TakeWhile(c => c != ' '));
                if (!commands.ContainsKey(trigger.ToLower()))
                {
                    await e.Channel.SendMessage(Util.GetRandomGrump());
                    return;
                }
                await commands[trigger.ToLower()](new CommandArgs(e));
            };
            client.JoinedServer += async (s, e) =>
            {
                await e.Server.DefaultChannel.SendMessage("Hello, I'm TARS, made by <@96550262403010560>, and I'm ready to rule the universe. ∞");
            };
            client.ExecuteAndWait(async () =>
            {
                await client.Connect(ConstData.loginToken, TokenType.Bot);
            });
        }
Ejemplo n.º 9
0
        public async void Start()
        {
            var settings = GlobalSettings.Load();

            if (settings == null) return;


            _client = new DiscordClient();

            StartNet(settings.Port);
            if (settings.usePokeSnipers)
            {
                pollPokesniperFeed();
            }
            _client.MessageReceived += async (s, e) =>
            {
                if (settings.ServerChannels.Any(x => x.Equals(e.Channel.Name.ToString(), StringComparison.OrdinalIgnoreCase)))
                {
                    await relayMessageToClients(e.Message.Text, e.Channel.Name.ToString());
                }
            };

            _client.ExecuteAndWait(async () =>
            {
                if (settings.useToken && settings.DiscordToken != null)
                    await _client.Connect(settings.DiscordToken);
                else if (settings.DiscordUser != null && settings.DiscordPassword != null)
                {
                    try
                    {
                        await _client.Connect(settings.DiscordUser, settings.DiscordPassword);
                    }
                    catch
                    {
                        Console.WriteLine("Failed to authroize Discord user! Check your config.json and try again.");
                        Console.ReadKey();
                        return;
                    }
                }
                else
                {
                    Console.WriteLine("Please set your logins in the config.json first");
                }
            });
        }
Ejemplo n.º 10
0
        public void Connect()
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
            CommandListInit();
            try
            {
                if (!Properties.Settings.Default.DateTimeFormatCorrected)
                {
                    //xmlprovider.DateTimeCorrection();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            _streamProviderManager = new StreamProviderManager();
            _streamProviderManager.StreamStarted += OnStreamStarted;
            _streamProviderManager.StreamStopped += OnStreamStopped;
            _streamProviderManager.StreamGlobalNotification += OnStreamGlobalNotification;
            _streamProviderManager.AddStreamProvider(new TwitchProvider());
            _streamProviderManager.AddStreamProvider(new HitboxProvider());
            bot = new DiscordClient();
            bot.MessageReceived += Message_Received;
            bot.UserJoined += User_Joined;
            deathmicirc = new RelayBot(bot,false);
            Thread RelayThread = new Thread(deathmicirc.runBot);
            RelayThread.Start();
            while (!RelayThread.IsAlive) ;
            Thread.Sleep(1);

            readUsers();

            bot.ExecuteAndWait(async () =>
            {
                await bot.Connect("MjYwMTE2OTExOTczNDY2MTEy.CzhvyA.kpEIti2hVnjNIUccob0ERB4QFTw", TokenType.Bot);
            });
        }
Ejemplo n.º 11
0
        public void Start()
        {
            Console.WriteLine("Initializing...");
            _client = new DiscordClient();

            _client.UsingAudio(x => // Opens an AudioConfigBuilder so we can configure our AudioService
            { x.Mode = AudioMode.Outgoing; // Tells the AudioService that we will only be sending audio
            });

            // _vClient = _client.GetService<AudioService>();

            _client.MessageReceived += async (s, e) =>
            {
                if (!e.Message.IsAuthor)
                {
                    Console.WriteLine(e.Message.User.Name + "> " + e.Message.Text);
                    if (e.Message.Text.StartsWith("!!"))
                    {
                        string command = e.Message.Text.Replace("!!", "");
                        //   if (command.Equals(""))
                        //      {
                        //                 await e.Channel.SendMessage("I am Jukebot. Do !!info for more details.");
                        //
                        //          }
                        string[] words = command.Split(' ');
                        switch (words[0])
                        {
                            case "info":
                                await
                                    e.Channel.SendMessage(
                                        "```diff\n!====== [Jukebot] ======!" +
                                        "\nA shitty ass music bot made by Ratismal (stupid cat)" +
                                        "\nIt plays music. lol what did u expect" +
                                        "\n!== [Features] ==!" +
                                        "\n+ a shitty looking unintuitive piece of shit GUI that only the host can see (lol)" +
                                        "\n+ plays music" +
                                        "\n!== [Commands] ==!" +
                                        "\n+ !!info - shows this" +
                                        "\n+ !!summon - summons bot to current voice channel" +
                                        "\n+ !!banish - tells the bot to piss off" +
                                        "\n+ !!volume - shows the current volume" +
                                        "\n+ !!volume <amount> - set the volume" +
                                        "\n+ !!volume +-<amount> - add/subtract the volume" +
                                        "\n!== [Conclusi] ==!" +
                                        "\n+ '-on' cut off from title for consistancy spacing sake" +
                                        "\n+ f**k my life" +
                                        "\n+ you want to play something? GOOD LUCK WITH THAT LOL ONLY I CAN" +
                                        "\n- This is red text!" +
                                        "\n- its really late i should go to bed lol fml smfh lmao kms" +
                                        "\n```");
                                break;
                            case "summon":
                                Console.WriteLine("Joining a voice channel");
                                await e.Channel.SendMessage("Joining channel");
                                var voiceChannel = e.User.VoiceChannel;
                                _vClient = await _client.GetService<AudioService>().Join(voiceChannel);
                                //await _vClient.Join(voiceChannel);
                                break;
                            case "banish":
                                Console.WriteLine("Leaving a voice channel");

                                await e.Channel.SendMessage("Leaving channel");
                                await _client.GetService<AudioService>().Leave(e.Server);
                                break;
                            case "volume":
                                if (words.Length == 1)
                                {
                                    e.Channel.SendMessage("Current volume: " + MainWindow.volume);
                                }
                                else
                                {
                                    //  string goodstuff;
                                    if (words[1].StartsWith("+") || words[1].StartsWith("-"))
                                    {
                                        int addVolume = Int32.Parse(words[1]);
                                        MainWindow.volume += addVolume;
                                        e.Channel.SendMessage("New volume: " + MainWindow.volume);
                                    }
                                    else
                                    {
                                        MainWindow.volume = Int32.Parse(words[1]);
                                        e.Channel.SendMessage("New volume: " + MainWindow.volume);
                                    }
                                }

                                break;
                            default:
                                await e.Channel.SendMessage("I am Jukebot. Do !!info for more details.");
                                break;
                        }
                    }
                }
            };

            _client.ExecuteAndWait(async () =>
            {
                await
                    _client.Connect(token
                        );
            });
            Console.WriteLine("Cool story bro (finished)");
        }
Ejemplo n.º 12
0
        public ActivityLogger()
        {
            DiscordClient Client = new DiscordClient(Logger =>
            {
                Logger.LogLevel = LogSeverity.Info;
                Logger.LogHandler += delegate (object Sender, LogMessageEventArgs EvArgs)
                {
                    Console.WriteLine(EvArgs.Message);
                };
            });

            Client.UserUpdated += (object sender, UserUpdatedEventArgs EvArgs) =>
            {
                if (EvArgs.Before.VoiceChannel != EvArgs.After.VoiceChannel)
                {
                    if (EvArgs.Before.VoiceChannel == null)
                    {
                        LogString($"User {EvArgs.Before} joined voice channel {EvArgs.After.VoiceChannel}");
                    }
                    else if (EvArgs.After.VoiceChannel == null)
                    {
                        LogString($"User {EvArgs.Before} left voice channel {EvArgs.Before.VoiceChannel}");
                    }
                    else
                    {
                        LogString($"User {EvArgs.Before} changed from voice channel {EvArgs.Before.VoiceChannel} to {EvArgs.After.VoiceChannel}");
                    }
                }
                if (EvArgs.Before.Nickname != EvArgs.After.Nickname)
                {
                    if (EvArgs.Before.Nickname == null)
                    {
                        LogString($"User {EvArgs.Before} gave themselves the nickname {EvArgs.After.Nickname}");
                    }
                    else if (EvArgs.After.Nickname == null)
                    {
                        LogString($"User {EvArgs.Before} removed their nickname {EvArgs.Before.Nickname}");
                    }
                    else
                    {
                        LogString($"User {EvArgs.Before} changed their nickname from {EvArgs.Before.Nickname} to {EvArgs.After.Nickname}");
                    }
                }
                if (EvArgs.Before.IsSelfMuted != EvArgs.After.IsSelfMuted)
                {
                    if (EvArgs.After.IsSelfMuted)
                    {
                        LogString($"User {EvArgs.Before} muted themselves");
                    }
                    else
                    {
                        LogString($"User {EvArgs.Before} unmuted themselves");
                    }
                }
                if (EvArgs.Before.IsServerMuted != EvArgs.After.IsServerMuted)
                {
                    if (EvArgs.After.IsServerMuted)
                    {
                        LogString($"User {EvArgs.Before} was server muted");
                    }
                    else
                    {
                        LogString($"User {EvArgs.Before} was server unmuted");
                    }
                }
                if (EvArgs.Before.IsSelfDeafened != EvArgs.After.IsSelfDeafened)
                {
                    if (EvArgs.After.IsSelfDeafened)
                    {
                        LogString($"User {EvArgs.Before} deafened themselves");
                    }
                    else
                    {
                        LogString($"User {EvArgs.Before} undeafened themselves");
                    }
                }
                if (EvArgs.Before.IsServerDeafened != EvArgs.After.IsServerDeafened)
                {
                    if (EvArgs.After.IsServerDeafened)
                    {
                        LogString($"User {EvArgs.Before} was server deafened");
                    }
                    else
                    {
                        LogString($"User {EvArgs.Before} was server undeafened");
                    }
                }
            };

            Console.WriteLine("Connecting to discord");

            Client.ExecuteAndWait(async () =>
            {
                while (true)
                {
                    try
                    {
                        await Client.Connect(ActivityLoggerTokenCarrier.Token, TokenType.Bot);
                        break;
                    }
                    catch
                    {
                        await Task.Delay(3000);
                    }
                }
            });
        }
Ejemplo n.º 13
0
        public void Start()
        {

            _client = new DiscordClient(x=> {
                x.AppName = "CancerBot";
                x.MessageCacheSize = 10;
                x.EnablePreUpdateEvents = true;
            });
            _client.UsingPermissionLevels((u,c)=>  (int)CheckPermLevel(u,c));
            _client.UsingCommands(x => {
                x.PrefixChar = '>';
                x.HelpMode = HelpMode.Public;
                x.ErrorHandler += HandleError;
                x.AllowMentionPrefix = false;
            });

            var doc = new XmlDocument();
            try
            {
                doc.Load("commands.xml");
            }
            catch (FileNotFoundException e)
            {
                StreamWriter stream = new StreamWriter("commands.xml");
                XmlSerializer xml1 = new XmlSerializer(typeof(List<CustomCommand>));
                xml1.Serialize(stream, new List<CustomCommand>());
                stream.Close();
            }

            catch (XmlException e)
            {

                StreamWriter stream = new StreamWriter("commands.xml");
                XmlSerializer xml1 = new XmlSerializer(typeof(List<CustomCommand>));
                xml1.Serialize(stream, new List<CustomCommand>());
                stream.Close();
            }
            CommandService commandService = _client.GetService<CommandService>();
            List<CustomCommand> commands = new List<CustomCommand>();
            XmlSerializer xml = new XmlSerializer(typeof(List<CustomCommand>));

            FileStream file = new FileStream("commands.xml", FileMode.OpenOrCreate);

            List<CustomCommand> list = (List<CustomCommand>)xml.Deserialize(file);
            file.Close();
            foreach(CustomCommand x in list)
            {
                if (forbodens.Contains<string>(x.Name)) { continue; }
                CommandBuilder b = _client.GetService<CommandService>().CreateCommand(x.Name.ToLower()). Description(x.Contents).Parameter("Cuntents", ParameterType.Unparsed); b.Do(async e =>
                {
                    
                    double deltatime = 5;
                    if (LastCommandTime.ContainsKey(e.User.Id))
                    {
                        deltatime = (DateTime.Now.Second - LastCommandTime[e.User.Id]);
                    }
                    if (deltatime >= 5)
                    {
                        await e.Channel.SendMessage(x.Contents);
                       
                    }
                    if (LastCommandTime.ContainsKey(e.User.Id))
                    {
                        LastCommandTime[e.User.Id] = DateTime.Now.Second;
                    }
                    else
                    {
                        LastCommandTime[e.User.Id] = DateTime.Now.Second;
                    }
                });
                try
                {
                    b._command.IsCustom = true;
                    commandBuilders.Add(x.Name.ToLower(), b);

                }

                catch { Console.WriteLine($"Command with name {x.Name} already exists!"); };
            }
            _client.GetService<CommandService>().CreateCommand("test23").Description("Test Command").Do(async e =>
            {
                await e.Channel.SendMessage("test");
            });
            //_client.Ready += (s, e) =>
            //{
            //    _client.FindServers("Discord Bots").First().FindChannels("testing-aloha").First().SendMessage("I'm alive!");
            //};
            commandService.CreateCommand("changename").Description("Changes Name").Parameter("Name", ParameterType.Unparsed).MinPermissions((int)PermissionLevel.ServerOwner)
            .Do(async e =>
            {

                await _client.CurrentUser.Edit("", e.GetArg("Name"));
                
            });
            
           // _client.UserBanned += async (s, e) =>
           // {

                //await e.Server.DefaultChannel.SendMessage(e.User.Name + " was banned forever LUUL");
            //};
           // _client.UserLeft += async (s, e) =>
           // {

                //await e.Server.DefaultChannel.SendMessage(e.User.Name + " left FeelsBadMan");
          //  };
            _client.GetService<CommandService>().CreateCommand("8ball").Description("Simple 8ball command").Parameter("memes", ParameterType.Unparsed).Do(async e => {
                Random rand = new Random();
                string output = "";
                switch (rand.Next(6))
                {
                    case 0:
                        output = "I don't know f****t";
                        break;
                    case 1:
                        output = "Yes";
                        break;
                    case 2:
                        output = "No";
                        break;
                    case 3:
                        output = "Kys";
                        break;
                    case 4:
                        output = "Ask me later";
                        break;
                    case 5:
                        output = "Maybe";
                        break;
                    default: break;
                }
                await e.Channel.SendMessage(output);
            });
            Channel Log = _client.GetChannel(192699690473488384);
            _client.MessageReceived += async (s, e) => {
              //  if (!e.Message.IsAuthor)
              //  {
              //      if (e.Message.Attachments.Length == 0)
                 //   {
                      //  await e.Channel.SendMessage(DateTime.Now + " UTC - " + e.User.Name + " (" + e.User.Id + "): " + e.Message.Text);
                 //   }
                 //   else {
                      //  await e.Channel.SendMessage(DateTime.Now + " UTC - " + e.User.Name + " (" + e.User.Id + "): " + e.Message.Text+" | Message Contained Attachment: "+e.Message.Attachments[0].Filename+" "+e.Message.Attachments[0].Size+" "+e.Message.Attachments[0].ProxyUrl);
                  //  }
                //}
                
                if (e.Message.IsMentioningMe()&&!e.Message.IsAuthor)
                {
                    if(e.Message.RawText.ToLower().Contains("hi")|| e.Message.RawText.ToLower().Contains("hello"))
                    {
                        await e.Channel.SendMessage($"Hello, <@{e.User.Id}>!");
                    }
                    if (e.Message.RawText.ToLower().Contains("kys"))
                    {
                        if (e.User.Id == 142291646824841217)
                        {
                            await e.Channel.SendMessage("ok");
                            System.Threading.Thread.Sleep(1000);
                            _client.Disconnect();
                            System.Environment.Exit(0);
                            
                        }
                        else
                        {
                            await e.Channel.SendMessage("no u");
                        }
                    }
                }
            };
            _client.GetService<CommandService>().CreateCommand("addcustomcommand").Description("Adds Custom Command").Parameter("Name").Parameter("Contents",ParameterType.Unparsed).Do(async e =>
            {
                if (e.Message.RawText.Contains("@everyone")|| e.Message.RawText.Contains("@here"))
                {
                    await e.Channel.SendMessage("Don't ping everyone you f****t");
                    return;
                }
                if (e.Message.Attachments.Length > 0)
                {
                    await e.Channel.SendMessage("I don't support files you retard.");
                    return;
                }
                XmlSerializer xml1 = new XmlSerializer(typeof(List<CustomCommand>));
                FileStream file1 = new FileStream("commands.xml", FileMode.OpenOrCreate);
                List<CustomCommand> list1 = (List<CustomCommand>)xml1.Deserialize(file1);
                file1.Close();
                if (list1.Contains(new CustomCommand(e.GetArg("Name").ToLower(), e.GetArg("Contents"))) || forbodens.Contains<string>(e.GetArg("Name")))
                {
                    await e.Channel.SendMessage("That already exists.");
                    return;
                }
                if (commandBuilders.ContainsKey(e.GetArg("Name").ToLower()))
                {
                    List<CustomCommand> list2 = list1.Where<CustomCommand>(t => t.Name.ToLower() == e.GetArg("Name").ToLower()).ToList<CustomCommand>();
                    foreach (CustomCommand g in list2)
                    {
                        list1.Remove(g);
                        list1.Add(new CustomCommand(e.GetArg("Name").ToLower(), e.GetArg("Contents")));
                    }
                }
                else
                {
                    list1.Add(new CustomCommand(e.GetArg("Name").ToLower(), e.GetArg("Contents")));
                }
                StreamWriter stream = new StreamWriter("commands.xml");
                xml1.Serialize(stream, list1);
                stream.Close();

                if (commandBuilders.ContainsKey(e.GetArg("Name").ToLower())) {
                    commandBuilders[e.GetArg("Name").ToLower()].Hide();
                    Command test = commandBuilders[e.GetArg("Name").ToLower()]._command;//(Command)typeof(CommandBuilder).GetField("_command", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(commandBuilders[e.GetArg("Name").ToLower()]);
                    Action<CommandEventArgs> tes1 = (x =>
                    {
                    });
                    typeof(Command).GetField("_runFunc", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(test, TaskHelper.ToAsync(tes1));
                    test.IsHidden = true;
                    _client.GetService<CommandService>()._map._items.Remove(e.GetArg("Name").ToLower());
                    _client.GetService<CommandService>()._categories.FirstOrDefault().Value._items.ToList().ForEach(t => {
                        if (t.Value.Name == test.Text)
                        {
                            _client.GetService<CommandService>()._categories.FirstOrDefault().Value._items.Remove(t.Value.Name);
                        }
                    });
                    commandBuilders[e.GetArg("Name").ToLower()].Description(e.GetArg("Contents"));
                    Command test1 = commandBuilders[e.GetArg("Name").ToLower()]._command;//(Command)typeof(CommandBuilder).GetField("_command", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(commandBuilders[e.GetArg("Name").ToLower()]);
                    Func<CommandEventArgs,Task> tes11 = (async x =>
                    {
                        double deltatime = 5;
                        if (LastCommandTime.ContainsKey(e.User.Id))
                        {
                            deltatime = (DateTime.Now.Second - LastCommandTime[e.User.Id]);
                        }
                        if (deltatime >= 5) { 
                        await x.Channel.SendMessage(e.GetArg("Contents"));
                       
                    }
                        if (LastCommandTime.ContainsKey(e.User.Id))
                        {
                            LastCommandTime[e.User.Id] = DateTime.Now.Second;
                        }
                        else
                        {
                            LastCommandTime[e.User.Id] = DateTime.Now.Second;
                        }
                    });
                    commandBuilders[e.GetArg("Name").ToLower()].Do(tes11);
                }
                else
                {
                    CommandBuilder b = _client.GetService<CommandService>().CreateCommand(e.GetArg("Name")).Description(e.GetArg("Contents")).Parameter("Cuntents", ParameterType.Unparsed); b.Do(async x =>
                     {
                         await x.Channel.SendMessage(e.GetArg("Contents"));
                     });
                    b._command.IsCustom = true;
                    commandBuilders.Add(e.GetArg("Name").ToLower(), b);

                }
                await e.Channel.SendMessage("Command Made Successfully!");
            });
            _client.GetService<CommandService>().CreateCommand("delcustomcommand").Description("Deletes a Custom Command").Parameter("Name").Do(async e =>
            {

                XmlSerializer xml1 = new XmlSerializer(typeof(List<CustomCommand>));
                FileStream file1 = new FileStream("commands.xml", FileMode.OpenOrCreate);
                List<CustomCommand> list1 = (List<CustomCommand>)xml1.Deserialize(file1);
                file1.Close();

                List<CustomCommand> list2 = list1.Where<CustomCommand>(t => t.Name.ToLower() == e.GetArg("Name").ToLower()).ToList<CustomCommand>();
                if (list2.Count == 0)
                {
                    await e.Channel.SendMessage("Command does not exist!");
                    return;
                }
                foreach(CustomCommand x in list2)
                {
                    list1.Remove(x);
                }
                StreamWriter stream = new StreamWriter("commands.xml");
                xml1.Serialize(stream, list1);
                stream.Close();
                foreach (Server s in _client.Servers)
                {
                    ServerConfig config = ServerConfig.GetServerConfig(s.Id);
                    if (config.commandPerms.Where(i => i.Command == e.GetArg("Name")).ToList().Count > 0)
                    {
                        config.commandPerms.Remove(config.commandPerms.Where(i => i.Command == e.GetArg("Name")).FirstOrDefault());
                        ServerConfig.WriteServerConfig(config);
                    }
                }
                commandBuilders[e.GetArg("Name").ToLower()].Hide();
                Command test = commandBuilders[e.GetArg("Name").ToLower()]._command;//(Command)typeof(CommandBuilder).GetField("_command", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(commandBuilders[e.GetArg("Name").ToLower()]);
                Action<CommandEventArgs> tes1 = (x =>
                {
                });
                typeof(Command).GetField("_runFunc", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(test, TaskHelper.ToAsync(tes1));
                test.IsHidden = true;
                _client.GetService<CommandService>()._map._items.Remove(e.GetArg("Name").ToLower());
                _client.GetService<CommandService>()._categories.FirstOrDefault().Value._items.ToList().ForEach(t=> {
                    if (t.Value.Name == test.Text) { _client.GetService<CommandService>()._categories.FirstOrDefault().Value._items.Remove(t.Value.Name); 
                }
                });
                commandBuilders.Remove(e.GetArg("Name"));
                //Console.WriteLine(_client.GetService<CommandService>()._categories.FirstOrDefault().Value._items.FirstOrDefault().);
                await e.Channel.SendMessage("Command removed Successfully!");
            });
            _client.GetService<CommandService>().CreateGroup("permissions",e=> {
                e.CreateGroup("editserver", t => {
                    t.CreateCommand("command").Description("Sets Permission Level for Command").Parameter("Command").Parameter("Level").Do(async u => {

                        ServerConfig config = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.CommandPermission commandperm;
                        if (config.commandPerms.Where(i => i.Command == u.GetArg("Command")).ToList().Count > 0)
                        {
                            commandperm = config.commandPerms.Where(i => i.Command == u.GetArg("Command")).FirstOrDefault();
                            commandperm.Level = Int32.Parse(u.GetArg("Level"));
                            config.commandPerms[config.commandPerms.IndexOf(config.commandPerms.Where(i => i.Command == u.GetArg("Command")).FirstOrDefault())] = commandperm;
                        }
                        else
                        {
                            config.commandPerms.Add(new ServerConfig.CommandPermission(u.GetArg("Command"), Int32.Parse(u.GetArg("Level"))));

                        }
                        ServerConfig.WriteServerConfig(config);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                    t.CreateCommand("removecommand").Description("Removes Permission Level for Command").Parameter("Command").Do(async u => {

                        ServerConfig config = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.CommandPermission commandperm;
                        if (config.commandPerms.Where(i => i.Command == u.GetArg("Command")).ToList().Count > 0)
                        {
                            //commandperm = config.commandPerms.Where(i => i.Command == u.GetArg("Command")).FirstOrDefault();
                            //commandperm.Level = Int32.Parse(u.GetArg("Level"));
                            config.commandPerms.Remove(config.commandPerms.Where(i => i.Command == u.GetArg("Command")).FirstOrDefault());
                        }
                        else
                        {
                            //config.commandPerms.Add(new ServerConfig.CommandPermission(u.GetArg("Command"), Int32.Parse(u.GetArg("Level"))));
                            await u.Channel.SendMessage("Permissions UnSucksecksful");
                        }
                        ServerConfig.WriteServerConfig(config);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                    t.CreateCommand("role").Description("Sets Permission Level for Role (has to be EXACT name of role)").Parameter("Command").Parameter("Level").Do(async u => {

                        ServerConfig config = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.RolePermission commandperm;
                        if (config.rolePerms.Where(i => i.Role == u.GetArg("Command")).ToList().Count > 0)
                        {
                            commandperm = config.rolePerms.Where(i => i.Role == u.GetArg("Command")).FirstOrDefault();
                            commandperm.Level = Int32.Parse(u.GetArg("Level"));
                            config.rolePerms[config.rolePerms.IndexOf(config.rolePerms.Where(i => i.Role == u.GetArg("Command")).FirstOrDefault())] = commandperm;

                        }
                        else
                        {
                            config.rolePerms.Add(new ServerConfig.RolePermission(u.GetArg("Command"), Int32.Parse(u.GetArg("Level"))));

                        }
                        ServerConfig.WriteServerConfig(config);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                    t.CreateCommand("removerole").Description("Removes Permission Level for Role (has to be EXACT name of role)").Parameter("Command").Do(async u => {

                        ServerConfig config = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.RolePermission commandperm;
                        if (config.rolePerms.Where(i => i.Role == u.GetArg("Command")).ToList().Count > 0)
                        {

                            config.rolePerms.Remove(config.rolePerms.Where(i => i.Role == u.GetArg("Command")).FirstOrDefault());

                        }
                        else
                        {
                            //config.rolePerms.Add(new ServerConfig.RolePermission(u.GetArg("Command"), Int32.Parse(u.GetArg("Level"))));
                            await u.Channel.SendMessage("Permissions UnSucksecksful");
                        }
                        ServerConfig.WriteServerConfig(config);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                    t.CreateCommand("user").Description("Sets Permission Level for User (has to be mention)").Parameter("Command").Parameter("Level").Do(async u => {
                        List<char> input = u.GetArg("Command").ToCharArray().ToList();
                        input.RemoveAt(0);
                        input.RemoveAt(0);

                        input.RemoveAt(input.Count - 1);
                        ulong id = ulong.Parse(String.Concat(input));
                        ServerConfig config = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.UserPermission commandperm;
                        if (config.userPerms.Where(i => i.UserID == id).ToList().Count > 0)
                        {
                            commandperm = config.userPerms.Where(i => i.UserID == id).FirstOrDefault();
                            commandperm.Level = Int32.Parse(u.GetArg("Level"));
                            config.userPerms[config.userPerms.IndexOf(config.userPerms.Where(i => i.UserID == id).FirstOrDefault())] = commandperm;

                        }
                        else
                        {
                            config.userPerms.Add(new ServerConfig.UserPermission(id, Int32.Parse(u.GetArg("Level"))));

                        }
                        ServerConfig.WriteServerConfig(config);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                    t.CreateCommand("removeuser").Description("Remove Permission Level for User (has to be mention)").Parameter("Command").Do(async u => {
                        List<char> input = u.GetArg("Command").ToCharArray().ToList();
                        input.RemoveAt(0);
                        input.RemoveAt(0);

                        input.RemoveAt(input.Count - 1);
                        ulong id = ulong.Parse(String.Concat(input));
                        ServerConfig config = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.UserPermission commandperm;
                        if (config.userPerms.Where(i => i.UserID == id).ToList().Count > 0)
                        {
                            commandperm = config.userPerms.Where(i => i.UserID == id).FirstOrDefault();

                            config.userPerms.Remove(commandperm);

                        }
                        else
                        {
                            //config.userPerms.Add(new ServerConfig.UserPermission(id, Int32.Parse(u.GetArg("Level"))));
                            await u.Channel.SendMessage("Permissions UnSucksecksful");
                        }
                        ServerConfig.WriteServerConfig(config);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                    t.CreateCommand("commanduser").Description("Blacklists/Whitelists commands for certain user").Parameter("User").Parameter("Command").Parameter("Enabled").Do(async u => {
                        List<char> input = u.GetArg("User").ToCharArray().ToList();
                        input.RemoveAt(0);
                        input.RemoveAt(0);

                        input.RemoveAt(input.Count - 1);
                        ulong id = ulong.Parse(String.Concat(input));
                        ServerConfig config = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.UserCommandPermission commandperm;
                        if (config.userCommandPerms.Where(i => (i.Command == u.GetArg("Command") && i.UserID == id)).ToList().Count > 0)
                        {
                            commandperm = config.userCommandPerms.Where(i => i.Command == u.GetArg("Command") && i.UserID == id).FirstOrDefault();
                            commandperm.UserID = id;
                            commandperm.enabled = bool.Parse(u.GetArg("Enabled"));
                            config.userCommandPerms[config.userCommandPerms.IndexOf(config.userCommandPerms.Where(i => i.Command == u.GetArg("Command") && i.UserID == id).FirstOrDefault())] = commandperm;
                        }
                        else
                        {
                            config.userCommandPerms.Add(new ServerConfig.UserCommandPermission(id, u.GetArg("Command"), bool.Parse(u.GetArg("Enabled"))));

                        }
                        ServerConfig.WriteServerConfig(config);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                    t.CreateCommand("removecommanduser").Description("Removes a Blacklist/Whitelist command for certain user").Parameter("User").Parameter("Command").Do(async u => {
                        List<char> input = u.GetArg("User").ToCharArray().ToList();
                        input.RemoveAt(0);
                        input.RemoveAt(0);

                        input.RemoveAt(input.Count - 1);
                        ulong id = ulong.Parse(String.Concat(input));
                        ServerConfig config = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.UserCommandPermission commandperm;
                        if (config.userCommandPerms.Where(i => (i.Command == u.GetArg("Command") && i.UserID == id)).ToList().Count > 0)
                        {
                            commandperm = config.userCommandPerms.Where(i => i.Command == u.GetArg("Command") && i.UserID == id).FirstOrDefault();

                            config.userCommandPerms.Remove(commandperm);
                        }
                        else
                        {

                            await u.Channel.SendMessage("Permissions UnSucksecksful");
                        }
                        ServerConfig.WriteServerConfig(config);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                    t.CreateCommand("commandrole").Description("Blacklists/Whitelists commands for certain role").Parameter("User").Parameter("Command").Parameter("Enabled").Do(async u => {
                    //    List<char> input = u.GetArg("User").ToCharArray().ToList();
                     //   input.RemoveAt(0);
                     //   input.RemoveAt(0);

                     //   input.RemoveAt(input.Count - 1);
                     //   ulong id = ulong.Parse(String.Concat(input));
                        ServerConfig config = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.RoleCommandPermission commandperm;
                        if (config.roleCommandPerms.Where(i => (i.Command == u.GetArg("Command")&&i.Role==u.GetArg("User"))).ToList().Count > 0)
                        {
                            commandperm = config.roleCommandPerms.Where(i => i.Command == u.GetArg("Command") && i.Role == u.GetArg("User")).FirstOrDefault();
                            commandperm.Role = u.GetArg("User");
                            commandperm.enabled = bool.Parse(u.GetArg("Enabled"));
                            config.roleCommandPerms[config.roleCommandPerms.IndexOf(config.roleCommandPerms.Where(i => i.Command == u.GetArg("Command") && i.Role == u.GetArg("User")).FirstOrDefault())] = commandperm;
                        }
                        else
                        {
                            config.roleCommandPerms.Add(new ServerConfig.RoleCommandPermission(u.GetArg("User"), u.GetArg("Command"), bool.Parse(u.GetArg("Enabled"))));

                        }
                        ServerConfig.WriteServerConfig(config);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                    t.CreateCommand("removecommandrole").Description("Remove a Blacklist/Whitelist command for certain role").Parameter("User").Parameter("Command").Do(async u => {
                        //    List<char> input = u.GetArg("User").ToCharArray().ToList();
                        //   input.RemoveAt(0);
                        //   input.RemoveAt(0);

                        //   input.RemoveAt(input.Count - 1);
                        //   ulong id = ulong.Parse(String.Concat(input));
                        ServerConfig config = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.RoleCommandPermission commandperm;
                        if (config.roleCommandPerms.Where(i => (i.Command == u.GetArg("Command") && i.Role == u.GetArg("User"))).ToList().Count > 0)
                        {
                            commandperm = config.roleCommandPerms.Where(i => i.Command == u.GetArg("Command") && i.Role == u.GetArg("User")).FirstOrDefault();
                            config.roleCommandPerms.Remove(commandperm);
                        }
                        else
                        {
                            await u.Channel.SendMessage("Permissions UnSucksecksful");

                        }
                        ServerConfig.WriteServerConfig(config);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                });
                
                
                e.CreateGroup("editchannel", t => {
                    t.CreateCommand("command").Description("Sets Permission Level for Command").Parameter("Command").Parameter("Level").Do(async u => {

                        ServerConfig config1 = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.ChannelPermission config = config1.channelPerms.Where(i => i.ChannelID==u.Channel.Id).FirstOrDefault();
                        if (config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).ToList().Count == 0)
                        {
                            config = new ServerConfig.ChannelPermission(u.Channel.Id);
                            config1.channelPerms.Add(config);
                        }
                        ServerConfig.CommandPermission commandperm;
                        if (config.commandPerms.Where(i => i.Command == u.GetArg("Command")).ToList().Count > 0)
                        {
                            commandperm = config.commandPerms.Where(i => i.Command == u.GetArg("Command")).FirstOrDefault();
                            commandperm.Level = Int32.Parse(u.GetArg("Level"));
                            config.commandPerms[config.commandPerms.IndexOf(config.commandPerms.Where(i => i.Command == u.GetArg("Command")).FirstOrDefault())] = commandperm;
                        }
                        else
                        {
                            config.commandPerms.Add(new ServerConfig.CommandPermission(u.GetArg("Command"), Int32.Parse(u.GetArg("Level"))));

                        }
                        config1.channelPerms[config1.channelPerms.FindIndex(y => y.ChannelID == u.Channel.Id)] = config;
                        ServerConfig.WriteServerConfig(config1);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                    t.CreateCommand("removecommand").Description("Removes Permission Level for Command").Parameter("Command").Do(async u => {

                        ServerConfig config1 = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.ChannelPermission config = config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).FirstOrDefault();
                        if (config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).ToList().Count == 0)
                        {
                            config = new ServerConfig.ChannelPermission(u.Channel.Id);
                            config1.channelPerms.Add(config);
                        }
                        ServerConfig.CommandPermission commandperm;
                        if (config.commandPerms.Where(i => i.Command == u.GetArg("Command")).ToList().Count > 0)
                        {
                            commandperm = config.commandPerms.Where(i => i.Command == u.GetArg("Command")).FirstOrDefault();

                            config.commandPerms.Remove(commandperm);
                        }
                        else
                        {
                            await u.Channel.SendMessage("Permissions UnSucksecksful");

                        }
                        config1.channelPerms[config1.channelPerms.FindIndex(y => y.ChannelID == u.Channel.Id)] = config;
                        ServerConfig.WriteServerConfig(config1);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                    t.CreateCommand("role").Description("Sets Permission Level for Role (has to be EXACT name of role)").Parameter("Command").Parameter("Level").Do(async u => {

                        ServerConfig config1 = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.ChannelPermission config = config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).FirstOrDefault();
                        if (config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).ToList().Count == 0)
                        {
                            config = new ServerConfig.ChannelPermission(u.Channel.Id);
                            config1.channelPerms.Add(config);
                        }
                        ServerConfig.RolePermission commandperm;
                        if (config.rolePerms.Where(i => i.Role == u.GetArg("Command")).ToList().Count > 0)
                        {
                            commandperm = config.rolePerms.Where(i => i.Role == u.GetArg("Command")).FirstOrDefault();
                            commandperm.Level = Int32.Parse(u.GetArg("Level"));
                            config.rolePerms[config.rolePerms.IndexOf(config.rolePerms.Where(i => i.Role == u.GetArg("Command")).FirstOrDefault())] = commandperm;

                        }
                        else
                        {
                            config.rolePerms.Add(new ServerConfig.RolePermission(u.GetArg("Command"), Int32.Parse(u.GetArg("Level"))));

                        }
                        config1.channelPerms[config1.channelPerms.FindIndex(y => y.ChannelID == u.Channel.Id)] = config;
                        ServerConfig.WriteServerConfig(config1);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                    t.CreateCommand("removerole").Description("Removes Permission Level for Role (has to be EXACT name of role)").Parameter("Command").Do(async u => {

                        ServerConfig config1 = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.ChannelPermission config = config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).FirstOrDefault();
                        if (config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).ToList().Count == 0)
                        {
                            config = new ServerConfig.ChannelPermission(u.Channel.Id);
                            config1.channelPerms.Add(config);
                        }
                        ServerConfig.RolePermission commandperm;
                        if (config.rolePerms.Where(i => i.Role == u.GetArg("Command")).ToList().Count > 0)
                        {
                            commandperm = config.rolePerms.Where(i => i.Role == u.GetArg("Command")).FirstOrDefault();

                            config.rolePerms.Remove(commandperm);

                        }
                        else
                        {
                            await u.Channel.SendMessage("Permissions UnSucksecksful");

                        }
                        config1.channelPerms[config1.channelPerms.FindIndex(y => y.ChannelID == u.Channel.Id)] = config;
                        ServerConfig.WriteServerConfig(config1);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                    t.CreateCommand("user").Description("Sets Permission Level for User (has to be mention)").Parameter("Command").Parameter("Level").Do(async u => {
                        List<char> input = u.GetArg("Command").ToCharArray().ToList();
                        input.RemoveAt(0);
                        input.RemoveAt(0);

                        input.RemoveAt(input.Count - 1);
                        ulong id = ulong.Parse(String.Concat(input));
                        ServerConfig config1 = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.ChannelPermission config = config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).FirstOrDefault();
                        if (config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).ToList().Count == 0)
                        {
                            config = new ServerConfig.ChannelPermission(u.Channel.Id);
                            config1.channelPerms.Add(config);
                        }
                        ServerConfig.UserPermission commandperm;
                        if (config.userPerms.Where(i => i.UserID == id).ToList().Count > 0)
                        {
                            commandperm = config.userPerms.Where(i => i.UserID == id).FirstOrDefault();
                            commandperm.Level = Int32.Parse(u.GetArg("Level"));
                            config.userPerms[config.userPerms.IndexOf(config.userPerms.Where(i => i.UserID == id).FirstOrDefault())] = commandperm;

                        }
                        else
                        {
                            config.userPerms.Add(new ServerConfig.UserPermission(id, Int32.Parse(u.GetArg("Level"))));

                        }
                        config1.channelPerms[config1.channelPerms.FindIndex(y => y.ChannelID == u.Channel.Id)] = config;
                        ServerConfig.WriteServerConfig(config1);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });

                    t.CreateCommand("removeuser").Description("Removes Permission Level for User (has to be mention)").Parameter("Command").Do(async u => {
                        List<char> input = u.GetArg("Command").ToCharArray().ToList();
                        input.RemoveAt(0);
                        input.RemoveAt(0);

                        input.RemoveAt(input.Count - 1);
                        ulong id = ulong.Parse(String.Concat(input));
                        ServerConfig config1 = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.ChannelPermission config = config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).FirstOrDefault();
                        if (config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).ToList().Count == 0)
                        {
                            config = new ServerConfig.ChannelPermission(u.Channel.Id);
                            config1.channelPerms.Add(config);
                        }
                        ServerConfig.UserPermission commandperm;
                        if (config.userPerms.Where(i => i.UserID == id).ToList().Count > 0)
                        {
                            commandperm = config.userPerms.Where(i => i.UserID == id).FirstOrDefault();
                            config.userPerms.Remove(commandperm);

                        }
                        else
                        {
                            await u.Channel.SendMessage("Permissions UnSucksecksful");

                        }
                        config1.channelPerms[config1.channelPerms.FindIndex(y => y.ChannelID == u.Channel.Id)] = config;
                        ServerConfig.WriteServerConfig(config1);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                    t.CreateCommand("commanduser").Description("Blacklists/Whitelists commands for certain user").Parameter("User").Parameter("Command").Parameter("Enabled").Do(async u => {
                        List<char> input = u.GetArg("User").ToCharArray().ToList();
                        input.RemoveAt(0);
                        input.RemoveAt(0);

                        input.RemoveAt(input.Count - 1);
                        ulong id = ulong.Parse(String.Concat(input));
                        ServerConfig config1 = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.ChannelPermission config = config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).FirstOrDefault();
                        if (config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).ToList().Count == 0)
                        {
                            config = new ServerConfig.ChannelPermission(u.Channel.Id);
                            config1.channelPerms.Add(config);
                        }
                        ServerConfig.UserCommandPermission commandperm;
                        if (config.userCommandPerms.Where(i => (i.Command == u.GetArg("Command") && i.UserID == id)).ToList().Count > 0)
                        {
                            commandperm = config.userCommandPerms.Where(i => i.Command == u.GetArg("Command") && i.UserID == id).FirstOrDefault();
                            commandperm.UserID = id;
                            commandperm.enabled = bool.Parse(u.GetArg("Enabled"));
                            config.userCommandPerms[config.userCommandPerms.IndexOf(config.userCommandPerms.Where(i => i.Command == u.GetArg("Command") && i.UserID == id).FirstOrDefault())] = commandperm;
                        }
                        else
                        {
                            config.userCommandPerms.Add(new ServerConfig.UserCommandPermission(id, u.GetArg("Command"), bool.Parse(u.GetArg("Enabled"))));

                        }
                        config1.channelPerms[config1.channelPerms.FindIndex(y => y.ChannelID == u.Channel.Id)] = config;
                        ServerConfig.WriteServerConfig(config1);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                    t.CreateCommand("removecommanduser").Description("Removes a Blacklist/Whitelist command for certain user").Parameter("User").Parameter("Command").Do(async u => {
                        List<char> input = u.GetArg("User").ToCharArray().ToList();
                        input.RemoveAt(0);
                        input.RemoveAt(0);

                        input.RemoveAt(input.Count - 1);
                        ulong id = ulong.Parse(String.Concat(input));
                        ServerConfig config1 = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.ChannelPermission config = config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).FirstOrDefault();
                        if (config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).ToList().Count == 0)
                        {
                            config = new ServerConfig.ChannelPermission(u.Channel.Id);
                            config1.channelPerms.Add(config);
                        }
                        ServerConfig.UserCommandPermission commandperm;
                        if (config.userCommandPerms.Where(i => (i.Command == u.GetArg("Command") && i.UserID == id)).ToList().Count > 0)
                        {
                            commandperm = config.userCommandPerms.Where(i => i.Command == u.GetArg("Command") && i.UserID == id).FirstOrDefault();

                            config.userCommandPerms.Remove(commandperm);
                        }
                        else
                        {
                            await u.Channel.SendMessage("Permissions UnSucksecksful");

                        }
                        config1.channelPerms[config1.channelPerms.FindIndex(y => y.ChannelID == u.Channel.Id)] = config;
                        ServerConfig.WriteServerConfig(config1);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                    t.CreateCommand("commandrole").Description("Blacklists/Whitelists commands for certain role").Parameter("User").Parameter("Command").Parameter("Enabled").Do(async u => {
                        //    List<char> input = u.GetArg("User").ToCharArray().ToList();
                        //   input.RemoveAt(0);
                        //   input.RemoveAt(0);

                        //   input.RemoveAt(input.Count - 1);
                        //   ulong id = ulong.Parse(String.Concat(input));
                        ServerConfig config1 = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.ChannelPermission config = config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).FirstOrDefault();
                        if(config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).ToList().Count == 0)
                        {
                            config = new ServerConfig.ChannelPermission(u.Channel.Id);
                            config1.channelPerms.Add(config);
                        }
                        ServerConfig.RoleCommandPermission commandperm;

                            if (config.roleCommandPerms.Where(i => (i.Command == u.GetArg("Command") && i.Role == u.GetArg("User"))).ToList().Count > 0)
                            {
                                commandperm = config.roleCommandPerms.Where(i => i.Command == u.GetArg("Command") && i.Role == u.GetArg("User")).FirstOrDefault();
                                commandperm.Role = u.GetArg("User");
                                commandperm.enabled = bool.Parse(u.GetArg("Enabled"));
                                config.roleCommandPerms[config.roleCommandPerms.IndexOf(config.roleCommandPerms.Where(i => i.Command == u.GetArg("Command") && i.Role == u.GetArg("User")).FirstOrDefault())] = commandperm;
                            }
                        
                        else
                        {
                            config.roleCommandPerms.Add(new ServerConfig.RoleCommandPermission(u.GetArg("User"), u.GetArg("Command"), bool.Parse(u.GetArg("Enabled"))));

                        }
                        config1.channelPerms[config1.channelPerms.FindIndex(y => y.ChannelID == u.Channel.Id)] = config;
                        ServerConfig.WriteServerConfig(config1);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                    t.CreateCommand("removecommandrole").Description("Removes a Blacklist/Whitelist command for certain role").Parameter("User").Parameter("Command").Do(async u => {
                        //    List<char> input = u.GetArg("User").ToCharArray().ToList();
                        //   input.RemoveAt(0);
                        //   input.RemoveAt(0);

                        //   input.RemoveAt(input.Count - 1);
                        //   ulong id = ulong.Parse(String.Concat(input));
                        ServerConfig config1 = ServerConfig.GetServerConfig(u.Channel.Server.Id);
                        ServerConfig.ChannelPermission config = config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).FirstOrDefault();
                        if (config1.channelPerms.Where(i => i.ChannelID == u.Channel.Id).ToList().Count == 0)
                        {
                            config = new ServerConfig.ChannelPermission(u.Channel.Id);
                            config1.channelPerms.Add(config);
                        }
                        ServerConfig.RoleCommandPermission commandperm;

                        if (config.roleCommandPerms.Where(i => (i.Command == u.GetArg("Command") && i.Role == u.GetArg("User"))).ToList().Count > 0)
                        {
                            commandperm = config.roleCommandPerms.Where(i => i.Command == u.GetArg("Command") && i.Role == u.GetArg("User")).FirstOrDefault();
                            config.roleCommandPerms.Remove(commandperm);
                        }

                        else
                        {
                            await u.Channel.SendMessage("Permissions UnSucksecksful");

                        }
                        config1.channelPerms[config1.channelPerms.FindIndex(y => y.ChannelID == u.Channel.Id)] = config;
                        ServerConfig.WriteServerConfig(config1);
                        await u.Channel.SendMessage("Permissions Sucksecksful");
                    });
                });
            });
            _client.ExecuteAndWait(async ()=>{
                await _client.Connect("MTcxNzEyMTAwMzE2NjEwNTYx.CfbSCw.saNJTaBcw4EN8nZjjlzhzuHzJFI");
                //"*****@*****.**", "mushroom12345"
            });


        }
Ejemplo n.º 14
0
        static void Main() {
            //load credentials from credentials.json
            Credentials c;
            try {
                c = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json"));
                botMention = c.BotMention;
                if (c.ForwardMessages != true)
                    Console.WriteLine("Not forwarding messages.");
                else {
                    ForwardMessages = true;
                    Console.WriteLine("Forwarding messages.");
                }

                OwnerID = c.OwnerID;
                password = c.Password;
            } catch (Exception ex) {
                Console.WriteLine("Failed to load stuff from credentials.json, RTFM");
                Console.ReadKey();
                return;
            }

            //create new discord client
            client = new DiscordClient();

            //create a command service
            var commandService = new CommandService(new CommandServiceConfig {
                CommandChar = null,
                HelpMode = HelpMode.Disable
            });

            //init parse
            if (c.ParseKey != null && c.ParseID != null && c.ParseID != "" && c.ParseKey != "") {
                ParseClient.Initialize(c.ParseID, c.ParseKey);

                //monitor commands for logging
                stats_collector = new StatsCollector(commandService);
            } else {
                Console.WriteLine("Parse key and/or ID not found. Logging disabled.");
            }

            //reply to personal messages and forward if enabled.
            client.MessageReceived += Client_MessageReceived;
            
            //add command service
            var commands = client.Services.Add<CommandService>(commandService);

            //count commands ran
            client.Commands().CommandExecuted += (s, e) => commandsRan++;

            //create module service
            var modules = client.Services.Add<ModuleService>(new ModuleService());

            //add audio service
            var audio = client.Services.Add<AudioService>(new AudioService(new AudioServiceConfig() {
                Channels = 2,
                EnableEncryption = false,
                EnableMultiserver = true,
                Bitrate = 128,
            }));

            //install modules
            modules.Add(new Administration(), "Administration", ModuleFilter.None);
            //run the bot
            client.ExecuteAndWait(async () => {
                await client.Connect(c.Username, c.Password);

                Console.WriteLine("-----------------");
                Console.WriteLine(GetStats());
                Console.WriteLine("-----------------");

                foreach (var serv in client.Servers) {
                    if ((OwnerUser = serv.GetUser(OwnerID)) != null)
                        return;
                }

            });
            Console.WriteLine("Exiting...");
            Console.ReadKey();
        }
Ejemplo n.º 15
0
        private void Start(string[] args)
        {
            //Discord.ETF.ETFWriter.Test();
            GlobalSettings.Load();

            //Set up the base client itself with no voice and small message queues
            _client = new DiscordClient(x =>
            {
                x.AppName = "VoltBot";
                x.AppUrl = "https://github.com/RogueException/DiscordBot";
                x.AppVersion = DiscordConfig.LibVersion;
                x.LogLevel = LogSeverity.Info;
                x.MessageCacheSize = 0;
                x.UsePermissionsCache = false;
                x.EnablePreUpdateEvents = true;
            })

            //** Core Services **//
            //These are services adding functionality from other Discord.Net.XXX packages

            //Enable commands on this bot and activate the built-in help command
            .UsingCommands(x =>
            {
                x.CommandChar = '~';
                x.HelpMode = HelpMode.Public;
            })

            //Enable command modules
            .UsingModules()

            //Enable audio support
            .UsingAudio(x =>
            {
                x.Mode = AudioMode.Outgoing;
                x.EnableMultiserver = true;
                x.EnableEncryption = true;
                x.Bitrate = AudioServiceConfig.MaxBitrate;
                x.BufferLength = 10000;
            })

            //** Command Permission Services **//
            // These allow you to use permission checks on commands or command groups, or apply a permission globally (such as a blacklist)

            //Add a blacklist service so we can add people that can't run any commands. We have used a whitelist instead to restrict it to just us.
            .UsingGlobalBlacklist()
            //.EnableGlobalWhitelist(GlobalSettings.Users.DevId))

            //Assign users to our own role system based on their permissions in the server/channel a command is run in.
            .UsingPermissionLevels((u, c) =>
            {
                if (u.Id == GlobalSettings.Users.DevId)
                    return (int)PermissionLevel.BotOwner;
                if (u.Server != null)
                {
                    if (u == c.Server.Owner)
                        return (int)PermissionLevel.ServerOwner;

                    var serverPerms = u.ServerPermissions;
                    if (serverPerms.ManageRoles)
                        return (int)PermissionLevel.ServerAdmin;
                    if (serverPerms.ManageMessages && serverPerms.KickMembers && serverPerms.BanMembers)
                        return (int)PermissionLevel.ServerModerator;

                    var channelPerms = u.GetPermissions(c);
                    if (channelPerms.ManagePermissions)
                        return (int)PermissionLevel.ChannelAdmin;
                    if (channelPerms.ManageMessages)
                        return (int)PermissionLevel.ChannelModerator;
                }
                return (int)PermissionLevel.User;
            })

            //** Helper Services**//
            //These are used by the modules below, and will likely be removed in the future

            .AddService<SettingsService>()
            .AddService<HttpService>()

            //** Command Modules **//
            //Modules allow for events such as commands run or user joins to be filtered to certain servers/channels, as well as provide a grouping mechanism for commands
            
            .AddModule<AdminModule>("Admin", ModuleFilter.ServerWhitelist)
            .AddModule<ColorsModule>("Colors", ModuleFilter.ServerWhitelist)
            .AddModule<FeedModule>("Feeds", ModuleFilter.ServerWhitelist)
            .AddModule<GithubModule>("Repos", ModuleFilter.ServerWhitelist)
            .AddModule<ModulesModule>("Modules", ModuleFilter.None)
            .AddModule<PublicModule>("Public", ModuleFilter.None)
            .AddModule<TwitchModule>("Twitch", ModuleFilter.ServerWhitelist)
            .AddModule<StatusModule>("Status", ModuleFilter.ServerWhitelist);
            //.AddModule(new ExecuteModule(env, exporter), "Execute", ModuleFilter.ServerWhitelist);

            //** Events **//
            
            _client.Log.Message += (s, e) => WriteLog(e);

            //Display errors that occur when a user tries to run a command
            //(In this case, we hide argcount, parsing and unknown command errors to reduce spam in servers with multiple bots)
            _client.Commands().CommandErrored += (s, e) =>
            {
                string msg = e.Exception?.GetBaseException().Message;
                if (msg == null) //No exception - show a generic message
                {
                    switch (e.ErrorType)
                    {
                        case CommandErrorType.Exception:
                            //msg = "Unknown error.";
                            break;
                        case CommandErrorType.BadPermissions:
                            msg = "You do not have permission to run this command.";
                            break;
                        case CommandErrorType.BadArgCount:
                            //msg = "You provided the incorrect number of arguments for this command.";
                            break;
                        case CommandErrorType.InvalidInput:
                            //msg = "Unable to parse your command, please check your input.";
                            break;
                        case CommandErrorType.UnknownCommand:
                            //msg = "Unknown command.";
                            break;
                    }
                }
                if (msg != null)
                {
                    _client.ReplyError(e, msg);
                    _client.Log.Error("Command", msg);
                }
            };

            //Log to the console whenever someone uses a command
            _client.Commands().CommandExecuted += (s, e) => _client.Log.Info("Command", $"{e.Command.Text} ({e.User.Name})");
            
            //Used to load private modules outside of this repo
#if PRIVATE
            PrivateModules.Install(_client);
#endif

            //** Run **//

#if !DNXCORE50
            Console.Title = $"{_client.Config.AppName} v{_client.Config.AppVersion} (Discord.Net v{DiscordConfig.LibVersion})";
#endif

            //Convert this method to an async function and connect to the server
            //DiscordClient will automatically reconnect once we've established a connection, until then we loop on our end
            //Note: ExecuteAndWait is only needed for Console projects as Main can't be declared as async. UI/Web applications should *not* use this function.
            _client.ExecuteAndWait(async () =>
            {
                while (true)
                {
                    try
                    {
                        await _client.Connect(GlobalSettings.Discord.Email, GlobalSettings.Discord.Password);
                        _client.SetGame("Discord.Net");
                        break;
                    }
                    catch (Exception ex)
                    {
                        _client.Log.Error($"Login Failed", ex);
                        await Task.Delay(_client.Config.FailedReconnectDelay);
                    }
                }
            });
        }
Ejemplo n.º 16
0
        public void Start()
        {
            const string configFile = "configuration.json";

            try
            {
                _config = Configuration.LoadFile(configFile);           // Load the configuration from a saved file.
            }
            catch
            {
                _config = new Configuration();                          // Create a new configuration file if it doesn't exist.

                Console.WriteLine("Config file created. Enter a token.");
                Console.Write("Token: ");

                _config.Token = Console.ReadLine();                     // Read the user's token from the console.
                _config.SaveFile(configFile);
            }

            _client = new DiscordClient(x =>                            // Create a new instance of DiscordClient
            {
                x.AppName = "Moetron";
                x.AppUrl = "https://github.com/Cappucirno/moetron";
                x.AppVersion = "1.0";
                x.LogLevel = LogSeverity.Info;                          // Mirror relevant information to the console.
            })
            .UsingCommands(x =>                                         // Configure the Commands extension
            {
                x.PrefixChar = _config.Prefix;                          // Set the prefix from the configuration file
                x.HelpMode = HelpMode.Private;                          // Enable the automatic `!help` command.
            })
            .UsingPermissionLevels((u, c) => (int)GetPermission(u, c))  // Permission levels are used to check basic or custom permissions
            .UsingModules();                                            // Configure the Modules extension

            // With LogLevel enabled, mirror info to the console in this format.
            _client.Log.Message += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}");

            // Load modules into the Modules extension.
            _client.AddModule<AdminModule>("Admin", ModuleFilter.None);
            _client.AddModule<EventModule>("Events", ModuleFilter.None);
            _client.AddModule<PointModule>("Points", ModuleFilter.None);
            _client.AddModule<ImageModule>("Images", ModuleFilter.None);
            _client.AddModule<UtilModule>("Utility", ModuleFilter.None);


            // Proper Login.md
            _client.ExecuteAndWait(async () =>
            {
                while (true)
                {
                    try
                    {
                        await _client.Connect(_config.Token, TokenType.Bot);
                        break;
                    }
                    catch (Exception ex)
                    {
                        _client.Log.Error("Login Failed", ex);
                        await Task.Delay(_client.Config.FailedReconnectDelay);
                    }
                }
            });
            //_client.SetGame("with your :heart:");
        }
Ejemplo n.º 17
0
        private static void Main()
        {
            Console.OutputEncoding = Encoding.Unicode;

            //var lines = File.ReadAllLines("data/input.txt");
            //HashSet<dynamic> list = new HashSet<dynamic>();
            //for (int i = 0; i < lines.Length; i += 3) {
            //    dynamic obj = new JArray();
            //    obj.Text = lines[i];
            //    obj.Author = lines[i + 1];
            //    if (obj.Author.StartsWith("-"))
            //        obj.Author = obj.Author.Substring(1, obj.Author.Length - 1).Trim();
            //    list.Add(obj);
            //}

            //File.WriteAllText("data/quotes.json", Newtonsoft.Json.JsonConvert.SerializeObject(list, Formatting.Indented));

            //Console.ReadKey();
            // generate credentials example so people can know about the changes i make
            try
            {
                File.WriteAllText("data/config_example.json", JsonConvert.SerializeObject(new Configuration(), Formatting.Indented));
                if (!File.Exists("data/config.json"))
                    File.Copy("data/config_example.json", "data/config.json");
                File.WriteAllText("credentials_example.json", JsonConvert.SerializeObject(new Credentials(), Formatting.Indented));

            }
            catch
            {
                Console.WriteLine("Failed writing credentials_example.json or data/config_example.json");
            }

            try
            {
                Config = JsonConvert.DeserializeObject<Configuration>(File.ReadAllText("data/config.json"));
                Config.Quotes = JsonConvert.DeserializeObject<List<Quote>>(File.ReadAllText("data/quotes.json"));
                Config.PokemonTypes = JsonConvert.DeserializeObject<List<PokemonType>>(File.ReadAllText("data/PokemonTypes.json"));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed loading configuration.");
                Console.WriteLine(ex);
                Console.ReadKey();
                return;
            }

            try
            {
                //load credentials from credentials.json
                Creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json"));
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}");
                Console.ReadKey();
                return;
            }

            //if password is not entered, prompt for password
            if (string.IsNullOrWhiteSpace(Creds.Password) && string.IsNullOrWhiteSpace(Creds.Token))
            {
                Console.WriteLine("Password blank. Please enter your password:\n");
                Creds.Password = Console.ReadLine();
            }

            Console.WriteLine(string.IsNullOrWhiteSpace(Creds.GoogleAPIKey)
                ? "No google api key found. You will not be able to use music and links won't be shortened."
                : "Google API key provided.");
            Console.WriteLine(string.IsNullOrWhiteSpace(Creds.TrelloAppKey)
                ? "No trello appkey found. You will not be able to use trello commands."
                : "Trello app key provided.");
            Console.WriteLine(Config.ForwardMessages != true
                ? "Not forwarding messages."
                : "Forwarding private messages to owner.");
            Console.WriteLine(string.IsNullOrWhiteSpace(Creds.SoundCloudClientID)
                ? "No soundcloud Client ID found. Soundcloud streaming is disabled."
                : "SoundCloud streaming enabled.");

            BotMention = $"<@{Creds.BotId}>";

            //create new discord client and log
            Client = new DiscordClient(new DiscordConfigBuilder()
            {
                MessageCacheSize = 10,
                ConnectionTimeout = 120000,
                LogLevel = LogSeverity.Warning,
                LogHandler = (s, e) =>
                    Console.WriteLine($"Severity: {e.Severity}" +
                                      $"Message: {e.Message}" +
                                      $"ExceptionMessage: {e.Exception?.Message ?? "-"}"),
            });

            //create a command service
            var commandService = new CommandService(new CommandServiceConfigBuilder
            {
                AllowMentionPrefix = false,
                CustomPrefixHandler = m => 0,
                HelpMode = HelpMode.Disabled,
                ErrorHandler = async (s, e) =>
                {
                    if (e.ErrorType != CommandErrorType.BadPermissions)
                        return;
                    if (string.IsNullOrWhiteSpace(e.Exception?.Message))
                        return;
                    try
                    {
                        await e.Channel.SendMessage(e.Exception.Message).ConfigureAwait(false);
                    }
                    catch { }
                }
            });

            //reply to personal messages and forward if enabled.
            Client.MessageReceived += Client_MessageReceived;

            //add command service
            Client.AddService<CommandService>(commandService);

            //create module service
            var modules = Client.AddService<ModuleService>(new ModuleService());

            //add audio service
            Client.AddService<AudioService>(new AudioService(new AudioServiceConfigBuilder()
            {
                Channels = 2,
                EnableEncryption = false,
                Bitrate = 128,
            }));

            //install modules
            modules.Add(new AdministrationModule(), "Administration", ModuleFilter.None);
            modules.Add(new HelpModule(), "Help", ModuleFilter.None);
            modules.Add(new PermissionModule(), "Permissions", ModuleFilter.None);
            modules.Add(new Conversations(), "Conversations", ModuleFilter.None);
            modules.Add(new GamblingModule(), "Gambling", ModuleFilter.None);
            modules.Add(new GamesModule(), "Games", ModuleFilter.None);
            modules.Add(new MusicModule(), "Music", ModuleFilter.None);
            modules.Add(new SearchesModule(), "Searches", ModuleFilter.None);
            modules.Add(new NSFWModule(), "NSFW", ModuleFilter.None);
            modules.Add(new ClashOfClansModule(), "ClashOfClans", ModuleFilter.None);
            modules.Add(new PokemonModule(), "Pokegame", ModuleFilter.None);
            modules.Add(new TranslatorModule(), "Translator", ModuleFilter.None);
            if (!string.IsNullOrWhiteSpace(Creds.TrelloAppKey))
                modules.Add(new TrelloModule(), "Trello", ModuleFilter.None);

            //run the bot
            Client.ExecuteAndWait(async () =>
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(Creds.Token))
                        await Client.Connect(Creds.Username, Creds.Password).ConfigureAwait(false);
                    else
                    {
                        await Client.Connect(Creds.Token).ConfigureAwait(false);
                        IsBot = true;
                    }
                    Console.WriteLine(NadekoBot.Client.CurrentUser.Id);
                }
                catch (Exception ex)
                {
                    if (string.IsNullOrWhiteSpace(Creds.Token))
                        Console.WriteLine($"Probably wrong EMAIL or PASSWORD.");
                    else
                        Console.WriteLine($"Token is wrong. Don't set a token if you don't have an official BOT account.");
                    Console.WriteLine(ex);
                    Console.ReadKey();
                    return;
                }

                //await Task.Delay(90000).ConfigureAwait(false);
                Console.WriteLine("-----------------");
                Console.WriteLine(await NadekoStats.Instance.GetStats().ConfigureAwait(false));
                Console.WriteLine("-----------------");

                try
                {
                    OwnerPrivateChannel = await Client.CreatePrivateChannel(Creds.OwnerIds[0]).ConfigureAwait(false);
                }
                catch
                {
                    Console.WriteLine("Failed creating private channel with the first owner listed in credentials.json");
                }

                Client.ClientAPI.SendingRequest += (s, e) =>
                {
                    var request = e.Request as Discord.API.Client.Rest.SendMessageRequest;
                    if (request == null) return;
                    // meew0 is magic
                    request.Content = request.Content?.Replace("@everyone", "@everyοne").Replace("@here", "@һere") ?? "_error_";
                    if (string.IsNullOrWhiteSpace(request.Content))
                        e.Cancel = true;
                };
                PermissionsHandler.Initialize();
                NadekoBot.Ready = true;
            });
            Console.WriteLine("Exiting...");
            Console.ReadKey();
        }
Ejemplo n.º 18
0
        private void Start(string[] args)
        {
#if !DNXCORE50
            Console.Title = $"{AppName} (Discord.Net v{DiscordConfig.LibVersion})";
#endif

            GlobalSettings.Load();

            _client = new DiscordClient(x =>
            {
                x.AppName = AppName;
                x.AppUrl = AppUrl;
                x.MessageCacheSize = 0;
                x.UsePermissionsCache = true;
                x.EnablePreUpdateEvents = true;
                x.LogLevel = LogSeverity.Debug;
                x.LogHandler = OnLogMessage;
            })
            .UsingCommands(x =>
            {
                x.AllowMentionPrefix = true;
                x.HelpMode = HelpMode.Public;
                x.ExecuteHandler = OnCommandExecuted;
                x.ErrorHandler = OnCommandError;
            })
            .UsingModules()
            .UsingAudio(x =>
            {
                x.Mode = AudioMode.Outgoing;
                x.EnableMultiserver = true;
                x.EnableEncryption = true;
                x.Bitrate = AudioServiceConfig.MaxBitrate;
                x.BufferLength = 10000;
            })
            .UsingPermissionLevels(PermissionResolver);

            _client.AddService<SettingsService>();
            _client.AddService<HttpService>();

            _client.AddModule<AdminModule>("Admin", ModuleFilter.ServerWhitelist);
            _client.AddModule<ColorsModule>("Colors", ModuleFilter.ServerWhitelist);
            _client.AddModule<FeedModule>("Feeds", ModuleFilter.ServerWhitelist);
            _client.AddModule<GithubModule>("Repos", ModuleFilter.ServerWhitelist);
            _client.AddModule<ModulesModule>("Modules", ModuleFilter.None);
            _client.AddModule<PublicModule>("Public", ModuleFilter.None);
            _client.AddModule<TwitchModule>("Twitch", ModuleFilter.ServerWhitelist);
            _client.AddModule<StatusModule>("Status", ModuleFilter.ServerWhitelist);
            //_client.AddModule(new ExecuteModule(env, exporter), "Execute", ModuleFilter.ServerWhitelist);

#if PRIVATE
            PrivateModules.Install(_client);
#endif

            //Convert this method to an async function and connect to the server
            //DiscordClient will automatically reconnect once we've established a connection, until then we loop on our end
            //Note: ExecuteAndWait is only needed for Console projects as Main can't be declared as async. UI/Web applications should *not* use this function.
            _client.ExecuteAndWait(async () =>
            {
                while (true)
                {
                    try
                    {
                        await _client.Connect(GlobalSettings.Discord.Email, GlobalSettings.Discord.Password);
                        _client.SetGame("Discord.Net");
                        //await _client.ClientAPI.Send(new Discord.API.Client.Rest.HealthRequest());
                        break;
                    }
                    catch (Exception ex)
                    {
                        _client.Log.Error($"Login Failed", ex);
                        await Task.Delay(_client.Config.FailedReconnectDelay);
                    }
                }
            });
        }
Ejemplo n.º 19
0
        static void Main() {
            //load credentials from credentials.json
            bool loadTrello = false;
            try {
                creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json"));
                botMention = creds.BotMention;
                if (string.IsNullOrWhiteSpace(creds.GoogleAPIKey)) {
                    Console.WriteLine("No google api key found. You will not be able to use music and links won't be shortened.");
                } else {
                    Console.WriteLine("Google API key provided.");
                    GoogleAPIKey = creds.GoogleAPIKey;
                }
                if (string.IsNullOrWhiteSpace(creds.TrelloAppKey)) {
                    Console.WriteLine("No trello appkey found. You will not be able to use trello commands.");
                } else {
                    Console.WriteLine("Trello app key provided.");
                    TrelloAppKey = creds.TrelloAppKey;
                    loadTrello = true;
                }
                if (creds.ForwardMessages != true)
                    Console.WriteLine("Not forwarding messages.");
                else {
                    ForwardMessages = true;
                    Console.WriteLine("Forwarding messages.");
                }
                if (string.IsNullOrWhiteSpace(creds.ParseID) || string.IsNullOrWhiteSpace(creds.ParseKey)) {
                    Console.WriteLine("Parse key and/or ID not found. Those are mandatory.");
                    ParseActive = false;
                } else ParseActive = true;

                if(string.IsNullOrWhiteSpace(creds.OsuApiKey))
                    Console.WriteLine("No osu API key found. Osu functionality is disabled.");
                else
                    Console.WriteLine("Osu enabled.");
                if(string.IsNullOrWhiteSpace(creds.SoundCloudClientID))
                    Console.WriteLine("No soundcloud Client ID found. Soundcloud streaming is disabled.");
                else
                    Console.WriteLine("SoundCloud streaming enabled.");

                //init parse
                if (ParseActive)
                    try {
                        ParseClient.Initialize(creds.ParseID, creds.ParseKey);
                    } catch (Exception) { Console.WriteLine("Parse exception. Probably wrong parse credentials."); }

                OwnerID = creds.OwnerID;
                password = creds.Password;
            } catch (Exception ex) {
                Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}");
                Console.ReadKey();
                return;
            }

            //create new discord client
            client = new DiscordClient();

            //create a command service
            var commandService = new CommandService(new CommandServiceConfig {
                CommandChar = null,
                HelpMode = HelpMode.Disable
            });
            
            //reply to personal messages and forward if enabled.
            client.MessageReceived += Client_MessageReceived;

            //add command service
            var commands = client.Services.Add<CommandService>(commandService);

            //create module service
            var modules = client.Services.Add<ModuleService>(new ModuleService());

            //add audio service
            var audio = client.Services.Add<AudioService>(new AudioService(new AudioServiceConfig() {
                Channels = 2,
                EnableEncryption = false,
                EnableMultiserver = true,
                Bitrate = 128,
            }));

            //install modules
            modules.Add(new Administration(), "Administration", ModuleFilter.None);
            modules.Add(new Conversations(), "Conversations", ModuleFilter.None);
            modules.Add(new Gambling(), "Gambling", ModuleFilter.None);
            modules.Add(new Games(), "Games", ModuleFilter.None);
            modules.Add(new Music(), "Music", ModuleFilter.None);
            modules.Add(new Searches(), "Searches", ModuleFilter.None);
            if (loadTrello)
                modules.Add(new Trello(), "Trello", ModuleFilter.None);

            //run the bot
            client.ExecuteAndWait(async () => {
                await client.Connect(creds.Username, creds.Password);
                Console.WriteLine("-----------------");
                Console.WriteLine(NadekoStats.Instance.GetStats());
                Console.WriteLine("-----------------");

                foreach (var serv in client.Servers) {
                    if ((OwnerUser = serv.GetUser(OwnerID)) != null)
                        return;
                }

                client.ClientAPI.SendingRequest += (s, e) =>
                {
                    var request = e.Request as Discord.API.Client.Rest.SendMessageRequest;
                    if (request != null) {
                        if (string.IsNullOrWhiteSpace(request.Content))
                            e.Cancel = true;
                    }
                };
            });
            Console.WriteLine("Exiting...");
            Console.ReadKey();
        }        
Ejemplo n.º 20
0
        private static async void Connect(DiscordClient inoriClient)
        {
            inoriClient.ExecuteAndWait(async () =>
            {
                while (true)
                {
                    try
                    {
                        await inoriClient.Connect(EMAIL, PASSWORD);
                        inoriClient.SetGame("Guilty Gear Xrd -Revelator-");
                        var channelName = "Koromo's Room";
                        var textChannelName = "Koromos_room";
                        OttawaAnimeCrewServer = inoriClient.Servers.FirstOrDefault(s => s.Name.Equals("Ottawa Anime Crew"));
                        TLSokuServer = inoriClient.Servers.FirstOrDefault(s => s.Name.Equals("TL Soku"));
                        VoiceChannel = TLSokuServer.VoiceChannels.FirstOrDefault(v => v.Name.Equals(channelName));
                        MusicChatChannel = TLSokuServer.TextChannels.FirstOrDefault(v => v.Name.Equals(textChannelName));
                        await VoiceChannel.JoinAudio();

                        break;
                    }
                    catch (Exception ex)
                    {
                        inoriClient.Log.Message += (s, e) => Console.WriteLine(String.Concat("Login Failed", ex));
                        await Task.Delay(inoriClient.Config.FailedReconnectDelay);
                    }
                }
            });
        }