Пример #1
0
        public async Task set_language(string newlang)
        {
            using (var database = new GuildDB())
            {
                // log execution
                CommandMethods.LogExecution(logger, "set language", Context);

                // indicate that the command is being worked on
                await Context.Channel.TriggerTypingAsync();

                // grab the guild language
                GuildTB gtb      = statecollection.GetGuildEntry(Context.Guild, database);
                var     language = statecollection.GetLanguage(Context.Guild, database, gtb);

                // make sure that the user has the right permissions
                if (!PermissionHelper.UserHasPermission(Context.User as SocketGuildUser, PermissionHelper.Admin, database))
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.nopermission"));

                    return;
                }

                // set the language
                if (!statecollection.SetLanguage(Context.Guild, newlang, database, gtb))
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.nolanguage"));

                    return;
                }

                // indicate success
                language = statecollection.GetLanguage(Context.Guild, database, gtb);
                await Context.Channel.SendMessageAsync(language.GetString("command.set.language"));
            }
        }
Пример #2
0
        private bool SaveApplicationToDatabase(GuildTB dbentry, DateTime deadline, ITextChannel channel, IInviteMetadata invite, GuildDB database)
        {
            // create entry
            ApplicationTB appdbentry = new ApplicationTB
            {
                Deadline = deadline,
                InviteID = invite.Id,
                Channel  = channel.Id,
                Guild    = dbentry,
            };

            database.Applications.Add(appdbentry);

            try
            {
                // try to save to database
                database.SaveChanges();
                return(true);
            }
            catch (Exception e)
            {
                // log failure
                logger.Log(new LogMessage(LogSeverity.Error, "State", $"Attempted to save application to database, but failed: {e.Message}\n{e.StackTrace}"));
                return(false);
            }
        }
Пример #3
0
        public async Task unset_notification([Remainder] string input = null)
        {
            using (var database = new GuildDB())
            {
                // log command execution
                CommandMethods.LogExecution(logger, "unset notification", Context);

                // indicate that the bot is working on the command
                await Context.Channel.TriggerTypingAsync();

                // apply change and report to user
                GuildTB gtb      = statecollection.GetGuildEntry(Context.Guild, database);
                var     language = statecollection.GetLanguage(Context.Guild, database, gtb);

                // make sure that the user has the right permissions
                if (!PermissionHelper.UserHasPermission(Context.User as SocketGuildUser, PermissionHelper.Owner, database))
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.nopermission"));

                    return;
                }

                gtb.Notification = null;
                statecollection.SetGuildEntry(gtb, database);
                await Context.Channel.SendMessageAsync(language.GetString("command.unset.notification"));
            }
        }
Пример #4
0
        public async Task set_permission(SocketRole role, string permissionstr, [Remainder] string rest = null)
        {
            using (var database = new GuildDB())
            {
                // log command execution
                CommandMethods.LogExecution(logger, "set permission", Context);

                // indicate that the bot is working on the command
                await Context.Channel.TriggerTypingAsync();

                GuildTB         gtb      = statecollection.GetGuildEntry(Context.Guild, database);
                StringConverter language = statecollection.GetLanguage(Context.Guild, database, gtb);

                byte permission        = PermissionHelper.StringToPermission(permissionstr);
                byte target_permission = PermissionHelper.GetRolePermission(role, database);

                // make sure that the calling user has the right permission to perform this command
                if (!PermissionHelper.UserHasPermission(Context.User as SocketGuildUser, Math.Max(permission, target_permission), database))
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.nopermission"));

                    return;
                }

                // execute the command
                PermissionHelper.SetRolePermission(role, permission, database, gtb);

                // return success
                await Context.Channel.SendMessageAsync(language.GetString("command.set.permission"));
            }
        }
Пример #5
0
        public async Task Events(EventSpecifier eventSpecifier, [Remainder] string rest = null)
        {
            using (var database = new GuildDB())
            {
                // log execution
                CommandMethods.LogExecution(logger, "get event", Context);

                // indicate that the command is being worked on
                await Context.Channel.TriggerTypingAsync();

                GuildTB         gtb      = statecollection.GetGuildEntry(Context.Guild, database);
                StringConverter language = statecollection.GetLanguage(Context.Guild, database, gtb);

                // make sure that the user has the right permissions
                if (!PermissionHelper.UserHasPermission(Context.User as SocketGuildUser, PermissionHelper.Member, database))
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.nopermission"));

                    return;
                }

                var events = agenda.GetEvents(Context.Guild, database);

                // make sure that the agenda is not empty
                if (events.Count() == 0)
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.event.empty"));

                    return;
                }

                // create an embed
                EmbedBuilder eb = new EmbedBuilder()
                                  .WithColor(Color.DarkRed);

                switch (eventSpecifier)
                {
                case EventSpecifier.All:
                    eb.Title = $":calendar_spiral: All events for '{Context.Guild.Name}'";
                    foreach (EventTB e in events)
                    {
                        eb.AddField(e.Name, e.Date.ToString(@"dd MMMM \a\t hh:mm tt UTC"));
                    }
                    break;

                case EventSpecifier.First:
                    eb.Title = $":calendar_spiral: First event for '{Context.Guild.Name}'";
                    EventTB ev = events.First();
                    eb.AddField(ev.Name, ev.Date.ToString(@"dd MMMM \a\t hh:mm tt UTC"));
                    break;
                }

                Embed embed = eb.Build();
                await Context.Channel.SendMessageAsync(language.GetString("present"), embed : embed);
            }
        }
Пример #6
0
        private GuildState CreateDefaultState(SocketGuild guild, GuildTB dbentry)
        {
            StringConverter language = StringConverter.LoadFromFile(constants.PathToLanguage(dbentry.Language), logger);
            GuildState      state    = new GuildState
            {
                Language = language,
            };

            if (!guildCollection.TryAdd(guild.Id, state))
            {
                logger.Log(new LogMessage(LogSeverity.Error, "State", $"Attempted to add new state to state collection, but failed."));
            }

            return(state);
        }
Пример #7
0
        private GuildTB CreateDefaultGuild(SocketGuild guild, GuildDB database)
        {
            GuildTB result = new GuildTB
            {
                GuildId  = guild.Id,
                Name     = guild.Name,
                Language = "Assistant",
            };

            // add default entry to database
            database.Guilds.Add(result);
            database.SaveChanges();

            return(result);
        }
Пример #8
0
        public GuildTB GetGuildEntry(SocketGuild guild, GuildDB database)
        {
            // try to read the database for a guild entry
            GuildTB dbresult = (from g in database.Guilds
                                where g.GuildId == guild.Id
                                select g).FirstOrDefault();

            // if there was no entry, create a default entry
            if (dbresult == null)
            {
                // push to log and create new entry
                logger.Log(new LogMessage(LogSeverity.Info, "State", $"No database entry was found for '{guild.Name}'. Creating a new one"));
                dbresult = CreateDefaultGuild(guild, database);
            }

            return(dbresult);
        }
Пример #9
0
        public StringConverter GetLanguage(SocketGuild guild, GuildDB database, GuildTB dbentry = null)
        {
            // make sure that the dbentry is not null
            if (dbentry == null)
            {
                dbentry = GetGuildEntry(guild, database);
            }

            // make sure that there is a state for this guild
            if (!guildCollection.ContainsKey(guild.Id))
            {
                logger.Log(new LogMessage(LogSeverity.Info, "State", $"No state was found for '{guild.Name}'. Creating a new one with the database"));
                return(CreateDefaultState(guild, dbentry).Language);
            }

            // return the language
            return(guildCollection[guild.Id].Language);
        }
Пример #10
0
        private EventAndNotifications StoreEventInDatabase(SocketGuild guild, GuildDB database, string name, DateTime date, SocketTextChannel channel = null, bool doNotifications = true, IEnumerable <TimeSpan> notifications = null)
        {
            // Get the data for this guild
            GuildTB g = statecollection.GetGuildEntry(guild, database);

            // first plan the event
            EventTB ev = new EventTB
            {
                Guild = g,
                Name  = name,
                Date  = date,
                NotificationChannel = channel != null ? (ulong?)channel.Id : null,
            };

            IEnumerable <EventNotificationTB> ens = null;

            if (doNotifications)
            {
                ens = CreateNotificationEntries(ev, notifications);
            }

            ev.Notifications = ens.ToArray();

            database.Events.Add(ev);
            try
            {
                // try to save addition to database
                database.SaveChanges();
            }
            catch (Exception e)
            {
                // log failure
                logger.Log(new LogMessage(LogSeverity.Error, "Agenda", $"Attempted to write event to database, but failed: {e.Message}\n{e.StackTrace}"));
            }

            // return the event and the notifications
            return(new EventAndNotifications
            {
                Event = ev,
                Notifications = ens,
            });
        }
Пример #11
0
        public void SetGuildEntry(GuildTB dbentry, GuildDB database)
        {
            // check if the language is still up to date
            if (guildCollection.ContainsKey(dbentry.GuildId) && guildCollection[dbentry.GuildId].Language.Name != dbentry.Language)
            {
                guildCollection[dbentry.GuildId].Language = StringConverter.LoadFromFile(constants.PathToLanguage(dbentry.Language), logger);
            }

            // send changes to database
            database.Guilds.Update(dbentry);

            try
            {
                database.SaveChanges();
            }
            catch (Exception e)
            {
                // log failure
                logger.Log(new LogMessage(LogSeverity.Error, "State", $"Attempted to save guild changes to database, but failed: {e.Message}\n{e.StackTrace}"));
            }
        }
Пример #12
0
        public async Task Status([Remainder] string input = null)
        {
            using (var database = new GuildDB())
            {
                // log execution
                CommandMethods.LogExecution(logger, "get status", Context);

                // indicate that the command is being worked on
                await Context.Channel.TriggerTypingAsync();

                GuildTB         gtb      = statecollection.GetGuildEntry(Context.Guild, database);
                StringConverter language = statecollection.GetLanguage(Context.Guild, database, gtb);

                // make sure that the user has the right permissions
                if (!PermissionHelper.UserHasPermission(Context.User as SocketGuildUser, PermissionHelper.Admin, database))
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.nopermission"));

                    return;
                }

                // get all the data from the database
                ApplicationTB     apptb = statecollection.GetApplicationEntry(Context.Guild, database);
                SocketTextChannel pc    = statecollection.GetPublicChannel(Context.Guild, database, gtb);
                SocketTextChannel nc    = statecollection.GetNotificationChannel(Context.Guild, database, gtb);

                EmbedBuilder eb = new EmbedBuilder()
                                  .WithColor(Color.Gold)
                                  .WithTitle($":clipboard: Status information for '{gtb.Name}'");

                eb.AddField("Language", gtb.Language);
                eb.AddField("Public channel", (pc != null ? pc.Mention : "Undefined"));
                eb.AddField("Notification channel", (nc != null ? nc.Mention : "Undefined"));
                eb.AddField("Application", (apptb != null ? $"ends on: {apptb.Deadline.ToString("dd MMMM a\\t hh:mm tt UTC")}" : "No active application"));

                await Context.Channel.SendMessageAsync(statecollection.GetLanguage(Context.Guild, database, gtb).GetString("present"), embed : eb.Build());
            }
        }
Пример #13
0
        public async Task Languages()
        {
            using (var database = new GuildDB())
            {
                // log execution
                CommandMethods.LogExecution(logger, "get languages", Context);

                // indicate that the bot is working on the answer
                await Context.Channel.TriggerTypingAsync();

                GuildTB gtb      = statecollection.GetGuildEntry(Context.Guild, database);
                var     language = statecollection.GetLanguage(Context.Guild, database, gtb);

                // make sure that caller has the right permissions
                if (!PermissionHelper.UserHasPermission(Context.User as SocketGuildUser, PermissionHelper.Admin, database))
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.nopermission"));

                    return;
                }

                EmbedBuilder eb = new EmbedBuilder()
                                  .WithTitle(":speech_balloon: Languages")
                                  .WithColor(Color.DarkBlue);

                // get the current language
                eb.AddField("Current Language", gtb.Language);

                // find all available languages
                IEnumerable <string> languages = Directory.GetFiles(constants.PathToLanguages(), "*.lang").Select(x => Path.GetFileNameWithoutExtension(x)).OrderBy(x => x);
                eb.AddField("Available Languages", languages.Aggregate((x, y) => $"{x}\n{y}"));

                // send feedback to caller
                await Context.Channel.SendMessageAsync(language.GetString("present"), embed : eb.Build());
            }
        }
Пример #14
0
        public bool SetLanguage(SocketGuild guild, string language, GuildDB database, GuildTB dbentry = null)
        {
            // make sure that given language exists
            if (!Directory.GetFiles(constants.PathToLanguages(), "*.lang").Select(x => Path.GetFileNameWithoutExtension(x)).Any(x => x == language))
            {
                logger.Log(new LogMessage(LogSeverity.Warning, "State", $"Attempted to set language for '{guild.Name}', but failed: Language does not exist"));
                return(false);
            }

            // make sure that dbentry is not null
            if (dbentry == null)
            {
                dbentry = GetGuildEntry(guild, database);
            }

            // make sure that there is a guild state
            if (!guildCollection.ContainsKey(guild.Id))
            {
                CreateDefaultState(guild, dbentry);
            }

            // set the language
            dbentry.Language = language;
            database.Guilds.Update(dbentry);

            try
            {
                // save the changes to the database
                database.SaveChanges();
            }
            catch (Exception e)
            {
                // log failure
                logger.Log(new LogMessage(LogSeverity.Error, "State", $"Attempted to set language in database for '{guild.Name}', but failed: {e.Message}\n{e.StackTrace}"));
                return(false);
            }

            guildCollection[guild.Id].Language = StringConverter.LoadFromFile(constants.PathToLanguage(language), logger);
            return(true);
        }
Пример #15
0
        public async Task StartApplications([Remainder] string input = null)
        {
            using (var database = new GuildDB())
            {
                // log command execution
                CommandMethods.LogExecution(logger, "application start", Context);

                // indicate that the bot is working on the command
                await Context.Channel.TriggerTypingAsync();

                GuildTB dbentry = statecollection.GetGuildEntry(Context.Guild, database);

                var language = statecollection.GetLanguage(Context.Guild, database, dbentry);

                // make sure that the user has the right permissions
                if (!PermissionHelper.UserHasPermission(Context.User as SocketGuildUser, PermissionHelper.Admin, database))
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.nopermission"));

                    return;
                }

                // allow only 1 application per guild
                if (statecollection.GetApplicationEntry(Context.Guild, database) != null)
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.appstart.isactive"));

                    return;
                }

                // command must have input
                if (input == null)
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.appstart.empty"));

                    return;
                }

                // user must have a timezone
                TimeZoneInfo usertimezone = DateTimeMethods.UserToTimezone(Context.User);
                if (usertimezone == null)
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.appstart.notimezone"));

                    return;
                }

                // given deadline must be in proper format
                DateTime?localdeadline = DateTimeMethods.StringToDatetime(input);
                if (!localdeadline.HasValue)
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.appstart.error"));

                    return;
                }
                DateTime utcdeadline = TimeZoneInfo.ConvertTimeToUtc(localdeadline.Value, usertimezone);

                // deadline must be in the future
                if (utcdeadline < DateTime.UtcNow)
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.appstart.past"));

                    return;
                }

                // creation must succeed
                IInviteMetadata invite = await statecollection.StartApplication(Context.Guild, database, utcdeadline, dbentry);

                if (invite == null)
                {
                    await Context.Channel.SendMessageAsync(language.GetString("command.appstart.error"));

                    return;
                }

                // return success to the user
                await Context.Channel.SendMessageAsync(language.GetString("command.appstart.success", new SentenceContext()
                                                                          .Add("url", invite.Url)));
            }
        }
Пример #16
0
 public SocketTextChannel GetNotificationElsePublicChannel(SocketGuild guild, GuildDB database, GuildTB dbentry = null)
 {
     if (dbentry == null)
     {
         dbentry = GetGuildEntry(guild, database);
     }
     return(GetNotificationChannel(guild, database, dbentry) ?? GetPublicChannel(guild, database, dbentry));
 }
Пример #17
0
        public static bool SetUserPermission(SocketGuildUser user, byte permission, GuildDB database, GuildTB guildentry)
        {
            // First check if there is already a permission for this user
            PermissionTB p = (from perm in database.Permissions
                              where perm.Guild.GuildId == user.Guild.Id && perm.PermissionType == PermissionType.User && perm.PermissionTarget == user.Id
                              select perm).FirstOrDefault();

            if (p != null)
            {
                // if there is already a permission for given user, update it
                p.Permission = permission;
                database.Permissions.Update(p);
            }
            else
            {
                // if no permission is specified, create a new one
                p = new PermissionTB
                {
                    Guild            = guildentry,
                    PermissionType   = PermissionType.User,
                    PermissionTarget = user.Id,
                    Permission       = permission,
                };
                database.Permissions.Add(p);
            }

            try
            {
                database.SaveChanges();
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Пример #18
0
        public SocketTextChannel GetPublicChannel(SocketGuild guild, GuildDB database, GuildTB dbentry = null)
        {
            // try to use the database entry if present
            if (dbentry == null)
            {
                dbentry = GetGuildEntry(guild, database);
            }

            // get the channel
            return(GetChannel(guild, dbentry.Public));
        }
Пример #19
0
        public void SetApplicationToken(SocketGuild guild, GuildDB database, CancellationTokenSource token, GuildTB dbentry = null)
        {
            // make sure that dbentry is not null
            if (dbentry == null)
            {
                dbentry = GetGuildEntry(guild, database);
            }

            // make sure that there is a guild state
            if (!guildCollection.ContainsKey(guild.Id))
            {
                CreateDefaultState(guild, dbentry);
            }

            // set the token
            guildCollection[guild.Id].ApplicationToken = token;
        }
Пример #20
0
        public async Task <IInviteMetadata> StartApplication(SocketGuild guild, GuildDB database, DateTime deadline, GuildTB dbentry = null)
        {
            if (dbentry == null)
            {
                dbentry = GetGuildEntry(guild, database);
            }

            // create a channel
            var channel = await CreateApplicationChannel(guild, dbentry);

            if (channel == null)
            {
                return(null);
            }

            // create an invite
            var invite = await CreateApplicationInvite(guild, channel, dbentry);

            if (invite == null)
            {
                return(null);
            }

            // save to database
            if (!SaveApplicationToDatabase(dbentry, deadline, channel, invite, database))
            {
                return(null);
            }

            // set a notifier
            var token = notifier.CreateWaiterTask(guild, GetApplicationChannel(guild, database), messages: DateTimeMethods.BuildMessageList(constants.ApplicationNotifications, deadline, "Application selection"), action: async(db) =>
            {
                await ExpireAppLink(invite);
            });

            SetApplicationToken(guild, database, token, dbentry);

            return(invite);
        }
Пример #21
0
 private async Task <IInviteMetadata> CreateApplicationInvite(SocketGuild guild, ITextChannel channel, GuildTB dbentry)
 {
     logger.Log(new LogMessage(LogSeverity.Info, "State", $"Creating an invite for {guild.Name}"));
     try
     {
         return(await channel.CreateInviteAsync(null, null, false, false));
     }
     catch (Exception e)
     {
         logger.Log(new LogMessage(LogSeverity.Error, "State", $"Attempted to create invite for '{guild.Name}', but failed: {e.Message}\n{e.StackTrace}"));
         return(null);
     }
 }
Пример #22
0
        private async Task <ITextChannel> CreateApplicationChannel(SocketGuild guild, GuildTB dbentry)
        {
            logger.Log(new LogMessage(LogSeverity.Info, "State", $"Creating an application channel for {guild.Name}."));

            // find the correct category
            SocketCategoryChannel category = null;

            if (dbentry.Public != null)
            {
                foreach (var c in guild.CategoryChannels)
                {
                    if (c.Channels.Any(x => x.Id == dbentry.Public))
                    {
                        category = c;
                        break;
                    }
                }
            }

            try
            {
                // try to create a text channel
                return(await guild.CreateTextChannelAsync("Applications", (x) =>
                {
                    x.Topic = "Are you interested in our community? Write your application here!";
                    x.CategoryId = category?.Id;
                }));
            }
            catch (Exception e)
            {
                // report failure
                logger.Log(new LogMessage(LogSeverity.Error, "State", $"Attempted to create a channel for '{guild.Name}', but failed: {e.Message}\n{e.StackTrace}"));
                return(null);
            }
        }