public async Task Select(string shortName)
        {
            //The requested language was not found.
            if (Client.Languages.All(l => l.ShortName != shortName))
            {
                await Context.Channel.SendMessageAsync(null, false,
                                                       EmbedHelper.BuildError(Locale, string.Format(Locale.InvalidLanguage, shortName)));
            }
            else
            {
                //The loading GIF :D
                RestUserMessage?loading = null;
                if (!string.IsNullOrEmpty(Client.Config.LoadingGif))
                {
                    loading = await Context.Channel.SendFileAsync(Client.Config.LoadingGif);
                }

                var guild = Client.Guilds.First(g => g.Id == Context.Guild.Id);
                guild.Language = shortName;
                var path =
                    $"{Client.Config.RootDirectory}{Path.DirectorySeparatorChar}{Client.Config.GuildsDirectoryName}{(Client.Config.GuildsDirectoryName == "" ? "" : Path.DirectorySeparatorChar.ToString())}{guild.Id}.json";
                //Write the new guild to a file.
                guild.OverwriteTo(path);
                if (loading != null)
                {
                    await loading.DeleteAsync();
                }
                //Send an embed with the new language.
                var newLocale = ILocale.Find(shortName);
                await Context.Channel.SendMessageAsync(null, false,
                                                       EmbedHelper.BuildSuccess(newLocale, newLocale.LanguageChanged));
            }
        }
Example #2
0
        /// <summary>
        ///     Run the bot.
        ///     <remarks>It will start an infinite loop: <c>await Task.Delay(-1)</c></remarks>
        /// </summary>
        public async Task RunAsync()
        {
            if (StaticGuilds == null || StaticLanguages == null)
            {
                StaticGuilds    = new List <JsonGuild>();
                StaticLanguages = new List <JsonLanguage>();
                await LoadResources();
            }

            Client    = new DiscordSocketClient();
            _commands = new CommandService();
            _services = new ServiceCollection()
                        .AddSingleton(Client)
                        .AddSingleton(_commands)
                        .BuildServiceProvider();
            Client.Log += message =>
            {
                Console.WriteLine($"Diswords: {message.Message}");
                return(Task.CompletedTask);
            };
            Client.JoinedGuild += async guild =>
            {
                var language = _findGuildLanguage(guild);
                var locale   = ILocale.Find(language);
                guild.SystemChannel?.SendMessageAsync(locale.JoinedGuild);
                await JoinedGuild(guild, language);

                guild.SystemChannel?.SendMessageAsync(locale.SetupDone);
            };
            Client.LeftGuild += async guild =>
            {
                var path =
                    $"{Config.RootDirectory}{Path.DirectorySeparatorChar}{Config.GuildsDirectoryName}{(Config.GuildsDirectoryName == "" ? "" : Path.DirectorySeparatorChar.ToString())}{Client.CurrentUser.Id}";
                if (!Directory.Exists(path))
                {
                    return;
                }
                var jsonGuild = GetGuild(guild.Id);
                if (jsonGuild != null)
                {
                    Directory.Delete(path, true);
                }
            };
            Client.MessageReceived += HandleCommandAsync;
            Client.Ready           += LoadPrivateResources;
            await _commands.AddModulesAsync(Assembly.GetExecutingAssembly(), _services);

            Console.WriteLine("Diswords: Logging in..");
            await Client.LoginAsync(TokenType.Bot, Config.Token);

            await Client.StartAsync();

            await Task.Delay(-1);
        }
Example #3
0
 public Diswords(DiswordsClient client, IGuildUser creator, JsonGuild guild, ITextChannel channel,
                 bool createdNewChannel, int previousSlowModeInterval, JsonLanguage language)
 {
     Creator                   = creator ?? throw new ArgumentNullException(nameof(creator));
     Channel                   = channel ?? throw new ArgumentNullException(nameof(channel));
     Language                  = language ?? throw new ArgumentNullException(nameof(language));
     Locale                    = ILocale.Find(Language.ShortName);
     Guild                     = guild;
     _newChannelCreated        = createdNewChannel;
     _previousSlowModeInterval = previousSlowModeInterval;
     _client                   = client;
     _lastSender               = null !;
 }
 /// <summary>
 ///     Method executed before the command.
 /// </summary>
 /// <param name="command">Discord.NET thing</param>
 /// <exception cref="Exception">Thrown if the client was not found.</exception>
 protected override void BeforeExecute(CommandInfo command)
 {
     //Find the client by it's ID
     //Diswords Client's ID is just Discord Bot's user ID.
     Client = DiswordsClient.Find(Context.Client.CurrentUser.Id);
     if (Client == default)
     {
         throw new Exception("Diswords: Something went wrong..\nDiswordsClient was not found.");
     }
     //Find the language of the server.
     Locale = ILocale.Find(Client.Guilds.FirstOrDefault(x => x.Id == Context.Guild.Id)?.Language);
     //Start "typing".
     _typing = Context.Channel.EnterTypingState();
     base.BeforeExecute(command);
 }
Example #5
0
        /// <summary>
        ///     A method that is called each time the client (bot) receives a command.
        /// </summary>
        private async Task HandleCommandAsync(SocketMessage arg)
        {
            var message = arg as SocketUserMessage;
            var context = new SocketCommandContext(Client, message);

            if (message == null)
            {
                return;
            }
            if (message.Author.IsBot)
            {
                return;
            }
            var guild = GetGuild(context.Guild.Id);

            if (guild == null)
            {
                await JoinedGuild(context.Guild, _findGuildLanguage(context.Guild));

                await message.Channel.SendMessageAsync(null, false, EmbedHelper.BuildError(ILocale.Find("en"), "```unexpected error: please run this command again.```"));
            }
            var argPos = 0;

            if (message.HasStringPrefix(guild.Prefix, ref argPos))
            {
                var searchResult = _commands.Search(context, argPos);
                if (searchResult.IsSuccess)
                {
                    var result = await _commands.ExecuteAsync(context, argPos, _services);

                    if (!result.IsSuccess)
                    {
                        if (result is ExecuteResult execResult)
                        {
                            await context.Channel.SendMessageAsync(null, false,
                                                                   EmbedHelper.BuildError(ILocale.Find(guild.Language),
                                                                                          $"```{execResult.Exception.StackTrace}```"));
                        }
                    }
                }
            }
            else
            {
                var game = Games.FirstOrDefault(g => g.Channel.Id == context.Channel.Id);
                game?.HandleInput(message);
            }
        }