public IEnumerable <EventTB> GetEvents(SocketGuild guild, GuildDB database) { return(from e in database.Events where e.Guild.GuildId == guild.Id orderby e.Date select e); }
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")); } }
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")); } }
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")); } }
public async Task <bool> StopApplication(SocketGuild guild, GuildDB database, ApplicationTB appentry) { // make sure that there is indeed a state with a token if (!guildCollection.ContainsKey(guild.Id)) { return(false); } // cancel notifier logger.Log(new LogMessage(LogSeverity.Info, "State", $"Cancelling application notifier for '{guild.Name}'")); if (!CancelApplicationNotifier(guild)) { return(false); } // delete the invite logger.Log(new LogMessage(LogSeverity.Info, "State", $"Deleting invite for '{guild.Name}'.")); await ExpireAppLink(await GetApplicationInvite(guild, database, appentry)); // delete the channel logger.Log(new LogMessage(LogSeverity.Info, "State", $"Deleting application channel for '{guild.Name}'")); await DeleteApplicationChannel(guild, appentry); // delete from the database RemoveApplicationFromDatabase(appentry, database); return(true); }
public async Task <IInviteMetadata> GetApplicationInvite(SocketGuild guild, GuildDB database, ApplicationTB application = null, SocketTextChannel channel = null) { // make sure that there are indeed applications if (!GetApplicationEntry(guild, database, ref application)) { return(null); } // get the channel where the invite comes from if (channel == null) { channel = GetChannel(guild, application.Channel); if (channel == null) { return(null); } } IEnumerable <IInviteMetadata> invites; try { // try to get the invites from discord invites = await channel.GetInvitesAsync(); } catch (Exception e) { // log failure and return logger.Log(new LogMessage(LogSeverity.Warning, "State", $"Attempted to read invites from '{guild.Name}', but failed: {e.Message}\n{e.StackTrace}")); return(null); } // return the invite return(invites.FirstOrDefault(x => x.Id == application.InviteID)); }
public async Task StopApplication([Remainder] string input = null) { using (var database = new GuildDB()) { // log command execution CommandMethods.LogExecution(logger, "application stop", Context); // indicate that the bot is working on the command await Context.Channel.TriggerTypingAsync(); StringConverter language = statecollection.GetLanguage(Context.Guild, database); // 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; } // make sure that applications are taking place ApplicationTB appentry = statecollection.GetApplicationEntry(Context.Guild, database); if (appentry == null) { await Context.Channel.SendMessageAsync(language.GetString("command.appstop.noapp")); return; } // stop the applications await statecollection.StopApplication(Context.Guild, database, appentry); await Context.Channel.SendMessageAsync(language.GetString("command.appstop.success")); } }
public async Task Ping([Remainder] string input = null) { using (var database = new GuildDB()) { // log command execution CommandMethods.LogExecution(logger, "ping", Context); // indicate that the bot is working on the command await Context.Channel.TriggerTypingAsync(); string response; if (Context.Guild != null) { var language = statecollection.GetLanguage(Context.Guild, database); // make sure that the user has the right permissions if (!PermissionHelper.UserHasPermission(Context.User as SocketGuildUser, PermissionHelper.Public, database)) { await Context.Channel.SendMessageAsync(language.GetString("command.nopermission")); return; } response = statecollection.GetLanguage(Context.Guild, database).GetString("command.ping"); } else { response = "pong"; } await Context.Channel.SendMessageAsync(response); } }
public IEnumerable <EventAndNotifications> GuildEvents(ulong id) { using (var database = new GuildDB()) { var dbresult = (from g in database.Guilds where g.GuildId == id select g.Events).FirstOrDefault(); if (dbresult == null) { return(null); } var output = dbresult.Select(x => { var notifications = (from n in database.EventNotifications where n.Event == x select new Notification { Date = n.Date, Response = n.ResponseKeyword }).ToArray(); return(new EventAndNotifications { Event = new Event { Id = x.EventId, Date = x.Date, Name = x.Name }, Notifications = notifications }); }).ToArray(); return(output); } }
public EventAndNotifications GetEventDetails(ulong gid, ulong evid) { using (var database = new GuildDB()) { var events = (from g in database.Guilds where g.GuildId == gid select g.Events).FirstOrDefault(); if (events == null) { return(null); } EventTB ev = events.FirstOrDefault(x => x.EventId == evid); if (ev == null) { return(null); } var notifications = (from n in database.EventNotifications where n.Event == ev select new Notification { Date = n.Date, Response = n.ResponseKeyword }).ToArray(); return(new EventAndNotifications { Event = new Event { Id = ev.EventId, Date = ev.Date, Name = ev.Name }, Notifications = notifications }); } }
public void RestoreGuildEvents(SocketGuild guild, GuildDB database) { // get all events and notifications for this guild // cast to array to prevent change to collection in foreach loop var evs = GetEvents(guild, database).ToArray(); foreach (var ev in evs) { // find corresponding notifications var ens = (from en in database.EventNotifications where en.Event == ev select en).ToArray(); // make sure that given event is still valid if (!CheckEventValidity(ev, ens, database)) { continue; } // check to see if there is currently a notification active for this guild already // (This is possible, because GuildAvailable gets called when connection to discord is interupted for a longer period) if (notifiercollection.ContainsKey(ev.EventId)) { // check to see if this event was cancelled or not if (!notifiercollection[ev.EventId].IsCancellationRequested) { logger.Log(new LogMessage(LogSeverity.Warning, "Agenda", $"Found an already active notifier for event '{ev.Name}', skipping this event.")); continue; } else { logger.Log(new LogMessage(LogSeverity.Warning, "Agenda", $"Found an event notifier for event '{ev.Name}', but it was cancelled.")); if (!notifiercollection.TryRemove(ev.EventId, out CancellationTokenSource t)) { logger.Log(new LogMessage(LogSeverity.Error, "Agenda", $"Attempted to removed cancelled event, but failed! This should never happen!!")); } } } // get event channel logger.Log(new LogMessage(LogSeverity.Info, "Agenda", $"Getting text channel for '{ev.Name}' from '{guild.Name}'")); SocketTextChannel channel = GetChannel(guild, ev); // create a waiter event logger.Log(new LogMessage(LogSeverity.Info, "Agenda", $"Creating waiter task for '{ev.Name}' from '{guild.Name}'")); var token = notifier.CreateWaiterTask(guild, channel, messages: TimedMessagesFromEvent(new EventAndNotifications { Event = ev, Notifications = ens.ToArray() }), action: (db) => { Cancel(ev, db); }); // store cancellation token if (!notifiercollection.TryAdd(ev.EventId, token)) { // log failure logger.Log(new LogMessage(LogSeverity.Error, "Agenda", "Attempted to store cancellation token for event, but failed")); } } }
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)); }
private async Task Client_GuildAvailable_RestoreApplication(SocketGuild guild) { // ask state collection to restore application and log start and finish logger.Log(new LogMessage(LogSeverity.Info, "Bot", $"Restoring application for '{guild.Name}'")); using (var database = new GuildDB()) await statecollection.RestoreApplication(guild, database); logger.Log(new LogMessage(LogSeverity.Info, "Bot", $"Successfully restored application for '{guild.Name}'")); }
public bool Cancel(EventTB Event, GuildDB database) { // cancel the notifications CancelNotifier(Event); // remove from the database return(RemoveEventFromDatabase(Event, database)); }
public async Task set_timezones([Remainder] string input = null) { using (var database = new GuildDB()) { // log command execution CommandMethods.LogExecution(logger, "set timezones", Context); // indicate that the bot is working on the command await Context.Channel.TriggerTypingAsync(); var language = statecollection.GetLanguage(Context.Guild, database); // 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; } await Context.Channel.SendMessageAsync(language.GetString("command.set.timezones.wait")); // find all the current roles in the guild IEnumerable <SocketRole> present = from role in Context.Guild.Roles where DateTimeMethods.IsTimezone(role.Name) select role; // add all the timezones that are not present already foreach (string t in DateTimeMethods.Timezones()) { if (!present.Any(x => x.Name == t)) { var role = await Context.Guild.CreateRoleAsync(t, isHoisted : false, permissions : constants.RolePermissions); await role.ModifyAsync(x => { x.Mentionable = false; }); } } // update the roles of the timezones that áre present foreach (SocketRole sr in present) { await sr.ModifyAsync((x) => { x.Permissions = constants.RolePermissions; x.Mentionable = false; }); } // return success to the user await Context.Channel.TriggerTypingAsync(); await Context.Channel.SendMessageAsync(statecollection.GetLanguage(Context.Guild, database).GetString("command.set.timezones.done")); } }
private Task Client_GuildAvailable_RestoreEvents(SocketGuild guild) { // ask agenda to restore events and log start and finish logger.Log(new LogMessage(LogSeverity.Info, "Bot", $"Restoring events for '{guild.Name}'")); using (var database = new GuildDB()) agenda.RestoreGuildEvents(guild, database); logger.Log(new LogMessage(LogSeverity.Info, "Bot", $"Successfully restored events for '{guild.Name}'")); return(Task.CompletedTask); }
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); } }
public IEnumerable <KeyValuePair <string, ulong> > Get() { using (var database = new GuildDB()) { var dbresult = from g in database.Guilds select new KeyValuePair <string, ulong>(g.Name, g.GuildId); return(dbresult.ToArray()); } }
public SocketTextChannel GetApplicationChannel(SocketGuild guild, GuildDB database, ApplicationTB application = null) { // make sure that there are indeed applications if (!GetApplicationEntry(guild, database, ref application)) { return(null); } // return the channel return(GetChannel(guild, application.Channel)); }
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)); }
public IEnumerable <Permission> Permissions(ulong gid) { using (var database = new GuildDB()) { var permissions = from p in database.Permissions where p.Guild.GuildId == gid select new Permission { Level = p.Permission, Target = p.PermissionTarget, Type = p.PermissionType }; return(permissions.ToArray()); } }
private bool GetApplicationEntry(SocketGuild guild, GuildDB database, ref ApplicationTB application) { // make sure that there are indeed applications going if (application == null) { application = GetApplicationEntry(guild, database); if (application == null) { return(false); } } return(true); }
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); }
public static byte GetRolePermission(SocketRole role, GuildDB database) { // find any permissions in the database PermissionTB dbresult = (from p in database.Permissions where p.PermissionType == PermissionType.Role && p.Guild.GuildId == role.Guild.Id && p.PermissionTarget == role.Id select p).FirstOrDefault(); // if no permission was found, this role has public permission if (dbresult == null) { return(Public); } // otherwise, return permission return(dbresult.Permission); }
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; }
private bool RemoveApplicationFromDatabase(ApplicationTB appentry, GuildDB database) { database.Applications.Remove(appentry); try { //try to apply removal to database database.SaveChanges(); return(true); } catch (Exception e) { //log failure logger.Log(new LogMessage(LogSeverity.Warning, "State", $"Attempted to remove application from database, but failed: {e.Message}\n{e.StackTrace}")); return(false); } }
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); }
public async Task AnalyseTime(SocketCommandContext Context) { using (var database = new GuildDB()) { // first make sure that the user has the correct permissions if (!PermissionHelper.UserHasPermission(Context.User as SocketGuildUser, PermissionHelper.Member, database)) { return; } DateTime now = DateTime.UtcNow; // check if the text contains a time indication TimeSpan?FoundTime = DateTimeMethods.StringToTime(Context.Message.Content); if (!FoundTime.HasValue) { return; } // check if the user has a timezone applied TimeZoneInfo tz = DateTimeMethods.UserToTimezone(Context.User); if (tz == null) { return; } // indicate that the bot is working on the answer await Context.Channel.TriggerTypingAsync(); var language = statecollection.GetLanguage(Context.Guild, database); // find the desired date time in the local time DateTime dt = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0) + FoundTime.Value; // print the table to the chat string result = DateTimeMethods.TimetableToString(DateTimeMethods.LocalTimeToTimetable(dt, tz, Context.Guild)); await Context.Channel.SendMessageAsync(language.GetString("scan.time.found")); await Context.Channel.TriggerTypingAsync(); await Context.Channel.SendMessageAsync(result); return; } }
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); }
public async Task <bool> Init() { // initiate logger process logger.Init(); // migrate the database to the latest version string dbpath = Path.Combine(constants.PathToData(), "databases"); if (!Directory.Exists(dbpath)) { Directory.CreateDirectory(dbpath); } using (var database = new GuildDB()) { database.Database.Migrate(); } // read settings from the file system if (!settings.Init()) { logger.Log(new LogMessage(LogSeverity.Error, "Bot", $"Initialisation of configurations failed")); return(false); } // create discord objects client = new DiscordSocketClient(new DiscordSocketConfig { LogLevel = settings.LogLevel, }); commands = new CommandService(new CommandServiceConfig { CaseSensitiveCommands = false, DefaultRunMode = RunMode.Async, LogLevel = settings.LogLevel, }); await commands.AddModulesAsync(Assembly.GetEntryAssembly(), services); // subscribe to all relevant events SetupEventSubscriptions(); return(true); }