Example #1
0
        public static void LoadInfo()
        {
            string config = Path.Combine(Directory, "config.json");

            ConsoleHelper.Log($"Loading config from \"{config}\"", Discord.LogSeverity.Info);

            if (!File.Exists(config))
            {
                File.WriteAllText(config, JsonConvert.SerializeObject(new Config()));
                ConsoleHelper.Log($"No configuration set, please edit {config}!", Discord.LogSeverity.Critical);
                Console.ReadKey();
                Process.GetCurrentProcess().Kill();
            }
            else
            {
                try {
                    Config = JsonConvert.DeserializeObject <Config>(File.ReadAllText(config));
                } catch (Exception ex) {
                    ConsoleHelper.Log(ex.Message, Discord.LogSeverity.Critical);
                    ConsoleHelper.Log($"Could not load config.json!, please edit {config}!", Discord.LogSeverity.Critical);
                    Console.ReadKey();
                    Process.GetCurrentProcess().Kill();
                }
            }
        }
Example #2
0
        public Cirilla(LogSeverity logSeverity)
        {
            DiscordSocketConfig config = new DiscordSocketConfig {
                LogLevel = logSeverity
            };

            Client                  = new DiscordSocketClient(config);
            Client.Log             += Log;
            Client.MessageReceived += MessageReceived;
            Client.UserJoined      += EventHelper.UserJoined;
            Client.UserLeft        += EventHelper.UserLeft;

            CommandServiceConfig serviceConfig = new CommandServiceConfig {
                CaseSensitiveCommands = false,
                SeparatorChar         = '$',
                LogLevel = logSeverity
            };

            _service      = new CommandService(serviceConfig);
            _service.Log += Log;
            _service.AddModulesAsync(Assembly.GetEntryAssembly()).GetAwaiter().GetResult();

            try {
                Login().GetAwaiter().GetResult();
            } catch (Exception ex) {
                ConsoleHelper.Log($"Could not login as Discord Bot! {ex.Message}", LogSeverity.Critical);
            }
        }
Example #3
0
        public static async Task JoinedGuild(SocketGuild guild)
        {
            try
            {
                ConsoleHelper.Log($"Joined Guild \"{guild.Name}\"!", LogSeverity.Info);

                if (guild.CurrentUser.GuildPermissions.SendMessages)
                {
                    await guild.DefaultChannel.SendMessageAsync("Hi guys! I'm the new bot!! :wave: :smile:" +
                                                                $"{Environment.NewLine}Type `{Information.Prefix}help` for a list of all available commands!");

                    string dataPath = Path.Combine(Information.Directory, guild.Id.ToString());
                    if (!Directory.Exists(dataPath))
                    {
                        Directory.CreateDirectory(dataPath);
                    }
                }

                await Cirilla.Client.SetGameAsync($"{Information.Prefix}help | {Cirilla.Client.Guilds.Count} Guilds");
            } catch (Exception ex)
            {
                ConsoleHelper.Log($"An unknown error occured (JoinedGuild event) {ex.Message}",
                                  LogSeverity.Error);
            }
        }
Example #4
0
        public static async Task UserJoined(SocketGuildUser arg)
        {
            await ConsoleHelper.Log($"{Helper.GetName(arg)} joined the \"{arg.Guild.Name}\" server!", Discord.LogSeverity.Info);

            SocketTextChannel channel = (new List <SocketTextChannel>(arg.Guild.TextChannels)).FirstOrDefault(c => c.Name == Information.TextChannel);

            if (channel != null)
            {
                await channel.SendMessageAsync($"Hi {arg.Mention}!", true);
            }
        }
Example #5
0
        public static async Task UserJoined(SocketGuildUser user)
        {
            ConsoleHelper.Log($"{Helper.GetName(user)} joined the \"{user.Guild.Name}\" server!",
                              LogSeverity.Info);
            var channel = user.Guild.DefaultChannel;

            if (channel != null)
            {
                await channel.SendMessageAsync($"Hi {user.Mention}!", true);
            }
        }
Example #6
0
        public static async Task Ready()
        {
            await Cirilla.Client.SetGameAsync($"{Information.Prefix}help | {Cirilla.Client.Guilds.Count} Guilds");


            ConsoleHelper.Log("Connected Guilds:", LogSeverity.Info);
            foreach (IGuild guild in Cirilla.Client.Guilds)
            {
                ConsoleHelper.Log($"\t{guild.Name}", LogSeverity.Info);
            }
        }
Example #7
0
        public static Task GuildAvailable(SocketGuild guild)
        {
            try
            {
                ReminderService.Init(guild);
            } catch (Exception ex)
            {
                ConsoleHelper.Log($"Could not init Guild's reminders! ({ex.Message})", LogSeverity.Error);
            }

            return(Task.CompletedTask);
        }
Example #8
0
        public static async Task UserLeft(SocketGuildUser arg)
        {
            await ConsoleHelper.Log($"{arg.Username} left the \"{arg.Guild.Name}\" server!", Discord.LogSeverity.Info);

            SocketTextChannel channel = (new List <SocketTextChannel>(arg.Guild.TextChannels)).FirstOrDefault(c => c.Name == Information.TextChannel);

            if (channel != null)
            {
                await channel.SendMessageAsync($"{Helper.GetName(arg)} left the server!", true);
            }

            RestDMChannel dm = await arg.CreateDMChannelAsync();

            await dm.SendMessageAsync("Why did you leave man?", true);
        }
Example #9
0
        public static async Task UserLeft(SocketGuildUser user)
        {
            ConsoleHelper.Log($"{user} left the \"{user.Guild.Name}\" server!", LogSeverity.Info);
            var channel = user.Guild.DefaultChannel;

            if (channel != null)
            {
                await channel.SendMessageAsync($"{Helper.GetName(user)} left the server!", true);
            }

            XpManager.RemoveUser(user.Guild, user);

            var dm = await user.GetOrCreateDMChannelAsync();

            await dm.SendMessageAsync("Why did you leave man?", true);
        }
Example #10
0
        public static Task LeftGuild(SocketGuild guild)
        {
            try
            {
                string guildDir = Path.Combine(Information.Directory, guild.Id.ToString());
                //cleanup
                if (Directory.Exists(guildDir))
                {
                    Directory.Delete(guildDir, true);
                }
            } catch (Exception ex)
            {
                ConsoleHelper.Log($"Could not cleanup for \"{guild.Name}\" guild! ({ex.Message})",
                                  LogSeverity.Error);
            }

            ConsoleHelper.Log($"Left Guild \"{guild.Name}\"!", LogSeverity.Info);

            return(Task.CompletedTask);
        }
Example #11
0
        private async Task MessageReceived(SocketMessage messageArg)
        {
            // Don't process the command if it was a System Message
            SocketUserMessage message = messageArg as SocketUserMessage;

            if (message == null)
            {
                return;
            }

            if (message.Author.ToString() != Client.CurrentUser.ToString())
            {
                await ConsoleHelper.Log(new LogMessage(
                                            LogSeverity.Info,
                                            message.Author.ToString(),
                                            message.Content));

                IEmote emote = Modules.RandomEmote.GetRandomEmote((messageArg.Channel as IGuildChannel).Guild, message);
                if (emote != null)
                {
                    await message.AddReactionAsync(emote);
                }

                // Command Begin
                int argPos = 0;
                // Determine if the message is a command
                if (!(message.HasCharPrefix(Information.Prefix, ref argPos) ||
                      message.HasCharPrefix(Information.SecondaryPrefix, ref argPos) ||
                      message.HasMentionPrefix(Client.CurrentUser, ref argPos)))
                {
                    return;
                }
                CommandContext context = new CommandContext(Client, message);
                IResult        result  = await _service.ExecuteAsync(context, argPos);

                if (!result.IsSuccess)
                {
                    await context.Channel.SendMessageAsync(result.ErrorReason);
                }
            }
        }
Example #12
0
        public static void LoadInfo()
        {
            //lock object so config does not get written to file (endless loop of errors)
            lock (Helper.Lock)
            {
                string config = Path.Combine(Directory, "config.json");

                ConsoleHelper.Log("Loading config..", LogSeverity.Info);
                ConsoleHelper.Log($"pwd: {Directory}", LogSeverity.Info);

                if (!File.Exists(config))
                {
                    File.WriteAllText(config, JsonConvert.SerializeObject(new Configuration()));
                    ConsoleHelper.Log($"No configuration set, please edit {config}!", LogSeverity.Critical);
                    Console.ReadKey();
                    Process.GetCurrentProcess().Kill();
                }
                else
                {
                    try
                    {
                        Config = JsonConvert.DeserializeObject <Configuration>(File.ReadAllText(config));
                    } catch (Exception ex)
                    {
                        ConsoleHelper.Log(ex.Message, LogSeverity.Critical);
                        ConsoleHelper.Log($"Could not load config.json!, please edit {config}!", LogSeverity.Critical);
                        Console.ReadKey();
                        Process.GetCurrentProcess().Kill();
                    }
                }

                if (Config.Token == "DISCORD_API_TOKEN_GOES_HERE")
                {
                    ConsoleHelper.Log($"Discord API Token is invalid, please edit {config}!", LogSeverity.Critical);
                    Console.ReadKey();
                    Process.GetCurrentProcess().Kill();
                }
            }
        }
Example #13
0
        public static async Task RandomEmoji(SocketMessage messageArg)
        {
            if (!(messageArg is SocketUserMessage message))
            {
                return;
            }

            if (message.Channel is IGuildChannel guildchannel)
            {
                var emote = RandomEmote.GetRandomEmote(guildchannel.Guild);
                if (emote != null)
                {
                    try
                    {
                        await message.AddReactionAsync(emote);

                        ConsoleHelper.Log("Added random Emote to a message!", LogSeverity.Info);
                    } catch
                    {
                        // can't add reactions
                    }
                }
            }
        }
Example #14
0
        public static void Main(string[] args)
        {
            while (true)
            {
                try
                {
                    Random = new Random();
                    if (!Directory.Exists(Information.Directory))
                    {
                        Directory.CreateDirectory(Information.Directory);
                    }

                    Information.LoadInfo();
                    ConsoleHelper.Log(">> Starting Cirilla Discord Bot..", LogSeverity.Info);

#pragma warning disable 219
                    bool skipIntro = false;
#pragma warning restore 219

                    foreach (string arg in args)
                    {
                        string cleanArg = arg.ToLower().Replace("-", "");
                        switch (cleanArg)
                        {
                        case "skip":
                            // ReSharper disable once RedundantAssignment
                            skipIntro = true;
                            break;

                        case "legacy":
                            // Need legacy Sockets (WS4NET)
                            Information.NeedsWs4Net = true;
                            break;
                        }
                    }

                    bool windows = !IsLinux;

                    if (windows)
                    {
                        ConsoleHelper.Set();
                        Console.Title = "Cirilla Discord Bot";
                    }

#if !DEBUG
                    if (!skipIntro && windows)
                    {
                        ConsoleHelper.Intro();
                    }
#endif

                    GuildConfigManager.Init();

                    Cirilla   = new Cirilla(LogSeverity.Debug);
                    StartTime = DateTime.Now;

                    ConsoleHelper.Log("Initializing services..", LogSeverity.Info);
                    var sw = Stopwatch.StartNew();
                    XpManager.Init();
                    NewsService.Init();
                    ConsoleHelper.Log($"Finished initializing services! ({sw.ElapsedMilliseconds}ms)",
                                      LogSeverity.Info);

                    Thread.Sleep(-1);
                    return;
                } catch (Exception ex)
                {
                    string nl = Environment.NewLine;
                    File.WriteAllText(Path.Combine(Information.Directory, "error.txt"),
                                      $"[{DateTime.Now:dd.MM.yyyy hh:mm:ss}] {ex.Message}:{nl}{ex.Message}{nl}{ex.Source}{nl}{ex.StackTrace}");
                }

                Console.WriteLine("Retrying in 3..");
                Thread.Sleep(1000);
                Console.WriteLine("Retrying in 2..");
                Thread.Sleep(1000);
                Console.WriteLine("Retrying in 1..");
                Thread.Sleep(1000);
            }
        }
Example #15
0
        private async Task MessageReceived(SocketMessage messageArg)
        {
            // Don't process the command if it was a System Message
            if (!(messageArg is SocketUserMessage message))
            {
                return;
            }

            if (message.Author.ToString() != Client.CurrentUser.ToString())
            {
                string secondaryPrefix;
                bool   enablePrimary = true;
                string guildname     = "private";

                if (messageArg.Channel is IGuildChannel guildchannel)
                {
                    guildname = guildchannel.Guild.Name;

                    var config = GuildConfigManager.Get(guildchannel.Guild.Id);
                    secondaryPrefix = config.Prefix;
                    enablePrimary   = config.EnablePrimaryPrefix;
                }
                else
                {
                    secondaryPrefix = Information.SecondaryPrefix;
                }

                //Log to console but don't write log to file
                ConsoleHelper.Log(new LogMessage(LogSeverity.Info, $"{message.Author}@{guildname}", message.Content),
                                  false);

                // Command (after prefix) Begin
                int argPos = 0;

                // Determine if the message is a command by checking for all prefixes
                bool primaryMatch   = enablePrimary && message.HasCharPrefix(Information.Prefix, ref argPos);
                bool secondaryMatch = message.HasStringPrefix(secondaryPrefix, ref argPos);
                bool mentionMatch   = message.HasMentionPrefix(Client.CurrentUser, ref argPos);
                if (!(primaryMatch || secondaryMatch || mentionMatch))
                {
                    return;
                }

                CommandLogger.Log(message.Author.ToString(), guildname, message.Content);

                var context = new CommandContext(Client, message);
                var result  = await Service.ExecuteAsync(context, argPos);

                if (!result.IsSuccess)
                {
                    ConsoleHelper.Log($"Command did not execute correctly! {result.ErrorReason}",
                                      LogSeverity.Error);
                    //await context.Channel.SendMessageAsync(result.ErrorReason);

                    //Find out what the user probably meant
                    var embed = Helper.WrongCommand(message, Service, context);
                    if (embed != default(Embed))
                    {
                        await context.Channel.SendMessageAsync("", embed : embed);
                    }
                }
            }
        }
Example #16
0
 private static Task Log(LogMessage message)
 {
     ConsoleHelper.Log(message);
     return(Task.CompletedTask);
 }