SocketGuildChannel LoadSuggestionSettings() { var guild = Program.clientCopy.GetGuild(201877884313403392); var gset = GuildSettings.Load(guild); return(guild.GetChannel(gset.suggestionChannel.id)); }
private Task Ready() { _ = Task.Run(async() => { var contextFactory = _services.GetRequiredService <BotContextFactory>(); using var botContext = contextFactory.CreateContext(); foreach (var guild in _client.Guilds) { GuildSettings settings = new GuildSettings() { GuildId = guild.Id, Prefix = Environment.GetEnvironmentVariable("PREFIX") }; var found = await botContext.Settings.FindAsync(guild.Id); if (found is null) { botContext.Add(settings); await botContext.SaveChangesAsync(); } } _logger.Info("Preloaded guild settings."); }); return(Task.CompletedTask); }
/// <summary> /// Gets the guild settings for a guild. /// </summary> /// <param name="guildId">The guild id of the guild requested</param> /// <returns>The guild settings for this guild</returns> public GuildSettings GetSettings(ulong guildId) { GuildSettings settings = null; using (var conn = new NpgsqlConnection(ConnectionString)) { conn.Open(); using (var cmd = new NpgsqlCommand(GET_GUILD_SETTINGS, conn)) { cmd.Parameters.AddWithValue("id", (long)guildId); var reader = cmd.ExecuteReader(); if (reader.Read()) { settings = new GuildSettings { Prefix = reader.GetChar(1), AuditChannelId = (ulong?)reader.GetFieldValue <long?>(2), RoleAssignment = new RoleAssignmentSettings { ChannelId = (ulong?)reader.GetFieldValue <long?>(3), MessageId = (ulong?)reader.GetFieldValue <long?>(4), Roles = GetRoleAssignmentRoles(guildId) } }; } } conn.Close(); } return(settings); }
public ReactionHandler(IUserMessage message, SocketReaction reaction, GuildSettings gset) { botUser = BotUser.Load(reaction.UserId); this.reaction = reaction; this.message = message; guildSettings = gset; }
public async Task SetMusicChannelForGuild(ulong musicChannelId) { //check channel of message if (Context.Message.Channel is SocketGuildChannel guildChannel) { SocketGuild guild = guildChannel.Guild; //check if channel is on server if (guild.GetTextChannel(musicChannelId) == null) { await Context.Message.Channel.SendMessageAsync("Cannot find channel on the server."); return; } //add or update channel to guildsettings from server GuildSettings guildSetting = DatabaseAccess.Instance.guildSettings.Find(g => g.GuildId == guild.Id); guildSetting.MusicChannelId = musicChannelId; DatabaseAccess.Instance.UpdateGuildSettings(guildSetting); await Context.Message.Channel.SendMessageAsync($"{guildChannel.Name} was set as music channel."); } else { //message wasn't send from a server await Context.Message.Channel.SendMessageAsync("Try this command on a server."); } }
public async Task ServerInfo(ulong?id = null) { if (id == null || Context.Guild?.Id == id) { if (Context.Guild != null) { await ReplyAsync(embed : Context.guildSettings.GetInfo(Context.Guild).Build()); } else { await ReplyAsync("Current channel is not in a guild."); } } else { var gs = GuildSettings.Load(id ?? 0); if (gs?.Guild == null) { //Bot is not in that server, delete from database. await Program.data.database.database.GetCollection <GuildSettings>("Guilds").DeleteOneAsync($"{{_id:{id}}}"); await ReplyAsync("Guild not found"); } else { await ReplyAsync(embed : gs.GetInfo().Build()); } } }
public async Task SetupIodem() { foreach (SocketGuildUser user in Context.Guild.Users) { var account = UserAccounts.GetAccount(user); account.Name = user.DisplayName(); account.ServerStats.LegacyStreak = new EndlessStreak() { Solo = account.ServerStats.ColossoHighestRoundEndlessSolo, Duo = account.ServerStats.ColossoHighestRoundEndlessDuo, DuoNames = account.ServerStats.ColossoHighestRoundEndlessDuoNames, Trio = account.ServerStats.ColossoHighestRoundEndlessTrio, TrioNames = account.ServerStats.ColossoHighestRoundEndlessTrioNames, Quad = account.ServerStats.ColossoHighestRoundEndlessQuad, QuadNames = account.ServerStats.ColossoHighestRoundEndlessQuadNames }; } foreach (SocketGuild guild in Global.Client.Guilds) { var gs = GuildSettings.GetGuildSettings(guild); gs.Name = guild.Name; } Console.WriteLine(Global.Client.Guilds.Sum(g => g.Emotes.Count)); UserAccounts.SaveAccounts(); GuildSettings.SaveGuilds(); await Task.CompletedTask; }
public async Task ProcessReaction(MessageReactionAddEventArgs e, GuildSettings guildSettings, SavedMiss savedMiss, int index) { var analyzer = savedMiss.MissAnalyzer; Logger.Log(Logging.ReactionCalls); if (savedMiss.MissUrls[index] == null) { savedMiss.MissUrls[index] = await SendMissMessage(analyzer, index); } var message = e.Message; if (!message.Author.IsCurrent) { message = savedMiss.Response; if (message == null) { var response = await e.Message.RespondAsync(savedMiss.MissUrls[index]); Logger.Log(Logging.MessageCreated); savedMiss.Response = response; if (!guildSettings.Compact) { CachedMisses[response] = savedMiss; await SendReactions(response, analyzer.MissCount); } } } if (message != null) { Logger.Log(Logging.MessageEdited); await message.ModifyAsync(savedMiss.MissUrls[index]); } }
public async Task ServerLookup(ulong id) { // Get the GuildSettings GuildSettings guildSettings = Configuration.LoadedConfiguration.DiscordConfig.GuildSettings.Where(settings => settings.GuildId == id).FirstOrDefault(); // Get the SocketGuild and SocketGuildChannel SocketGuild guild = DiscordBot.GetGuild(id); // Build an embed EmbedBuilder embedBuilder = new EmbedBuilder() .WithTitle("Lookup") .AddField("Guild", $"{guild.Name} ({guild.Id}, {(guildSettings != null ? "registered" : "unregistered")})"); // Check if this guild is registered if (guildSettings != null) { // Get the registered channel SocketGuildChannel channel = guild.GetChannel(guildSettings.TargetChannelId); // Add additional lookup details embedBuilder .AddField("Channel", $"#{channel.Name} ({channel.Id})") .AddField("Language", guildSettings.DefaultLanguage.ToString()); } // Complete the embed embedBuilder .AddField("Owner", $"{guild.Owner.Username}#{guild.Owner.Discriminator} ({guild.Owner.Id})") .AddField("User Count", guild.MemberCount) .WithColor(Color.Blue); await Context.Channel.SendMessageAsync(embed : embedBuilder.Build()); }
public static bool NewGuildSetting(GuildSettings Arg, ulong GuildId, bool SetTo, object ExtraSaveData = null) { string SettingsDir = $@"{Base}\{GuildId}\{Arg}"; if (!Directory.Exists($@"{Base}\{GuildId}")) { Directory.CreateDirectory($@"{Base}\{GuildId}"); } if (!Directory.Exists(SettingsDir)) { Directory.CreateDirectory(SettingsDir); } string ToRead = $@"{SettingsDir}\ret.txt"; string ToSaveExt = $@"{SettingsDir}\strsave.txt"; while (!CanReadWrite(ToRead)) { } if (ExtraSaveData != null) { using (StreamWriter SW = new StreamWriter(ToSaveExt)) { SW.WriteLine(ExtraSaveData.ToString()); SW.Close(); } } using (StreamWriter SW = new StreamWriter(ToRead)) { SW.Write(SetTo); SW.Close(); return(SetTo); } }
public static async Task ReactionClear(ModCoreShard bot, MessageReactionsClearEventArgs e) { GuildSettings cfg = null; using (var db = bot.Database.CreateContext()) { cfg = e.Channel.Guild.GetGuildSettings(db); if (cfg == null) { return; } var emoji = cfg.Starboard.Emoji; DiscordEmoji em = null; if (emoji.EmojiId != 0) { em = DiscordEmoji.FromGuildEmote(e.Client, (ulong)emoji.EmojiId); } else { em = DiscordEmoji.FromUnicode(e.Client, emoji.EmojiName); } if (cfg.Starboard.Enable) { var c = e.Channel.Guild.Channels.First(x => x.Key == (ulong)cfg.Starboard.ChannelId).Value; if (db.StarDatas.Any(x => (ulong)x.MessageId == e.Message.Id)) { await(await c.GetMessageAsync((ulong)db.StarDatas.First(x => (ulong)x.MessageId == e.Message.Id).StarboardMessageId)).DeleteAsync(); db.StarDatas.RemoveRange(db.StarDatas.Where(x => (ulong)x.MessageId == e.Message.Id)); await db.SaveChangesAsync(); } } } }
public static string ReturnExtraSaved(GuildSettings Arg, ulong GuildId) { string SettingsDir = $@"{Base}\{GuildId}\{Arg}"; if (!Directory.Exists($@"{Base}\{GuildId}")) { Directory.CreateDirectory($@"{Base}\{GuildId}"); } if (!Directory.Exists(SettingsDir)) { Directory.CreateDirectory(SettingsDir); } string ToSaveExt = $@"{SettingsDir}\strsave.txt"; while (!CanReadWrite(ToSaveExt)) { } if (File.Exists(ToSaveExt)) { return(File.ReadAllText(ToSaveExt)); } else { return(" "); } }
private async Task Update() { foreach (SocketGuild guild in Program.DiscordClient.Guilds) { GuildSettings settings = await SettingsService.GetSettings <GuildSettings>(guild.Id); string?name = null; if (!string.IsNullOrEmpty(settings.NickName)) { name = settings.NickName; } SocketGuildUser guildUser = guild.GetUser(Program.DiscordClient.CurrentUser.Id); if (guildUser != null) { await guildUser.ModifyAsync(x => { x.Nickname = name; }); await Task.Delay(500); // don't flood } } await Program.DiscordClient.SetActivityAsync(new BotActivity()); }
public static bool ReadSetting(GuildSettings Arg, ulong GuildId) { string SettingsDir = $@"{Base}\{GuildId}\{Arg}"; if (!Directory.Exists($@"{Base}\{GuildId}")) { Directory.CreateDirectory($@"{Base}\{GuildId}"); } if (!Directory.Exists(SettingsDir)) { Directory.CreateDirectory(SettingsDir); } string ToRead = $@"{SettingsDir}\ret.txt"; while (!CanReadWrite(ToRead)) { } if (File.Exists(ToRead)) { return(bool.Parse(File.ReadAllText(ToRead))); } else { return(false); } }
private async Task Client_GuildMemberUpdated(SocketGuildUser user_before, SocketGuildUser user) { var guild = GuildSettings.GetGuildSettings(user.Guild); if (user_before.DisplayName() != user.DisplayName()) { EntityConverter.ConvertUser(user).Name = user.DisplayName(); _ = guild.TestCommandChannel .SendMessageAsync($"{user.Mention} changed Nickname from {user_before.DisplayName()} to {user.DisplayName()}"); } if (user_before.IsPending == true && user.IsPending == false) { if (GuildSettings.GetGuildSettings(user.Guild).sendWelcomeMessage) { _ = guild.MainChannel.SendMessageAsync(embed: new EmbedBuilder() .WithColor(Colors.Get("Iodem")) .WithDescription(string.Format(welcomeMsg.Random(), user.DisplayName())) .Build()); } } if (user_before.PremiumSince.HasValue != user.PremiumSince.HasValue) { var isBoosting = user.PremiumSince.HasValue; _ = guild.TestCommandChannel .SendMessageAsync($"{"<:Exclamatory:549529360604856323>"} {user.Mention} is {(isBoosting ? "now" : "no longer")} boosting the server."); } await Task.CompletedTask; }
public bool IsHelpRequest(MessageCreateEventArgs e, GuildSettings guildSettings) { return(!e.Author.IsCurrent && (e.Message.Content.StartsWith(guildSettings.GetCommand("help")) || ((e.Message.Channel.IsPrivate || (e.MentionedUsers?.Any(u => u?.IsCurrent ?? false) ?? false)) && e.Message.Content.IndexOf("help", StringComparison.InvariantCultureIgnoreCase) >= 0) || e.Message.Content == guildSettings.Prefix)); }
internal static async void LevelUp(UserAccount userAccount, SocketGuildUser user, IMessageChannel channel = null) { if (userAccount.LevelNumber < 10 && (userAccount.LevelNumber % 5) > 0) { channel = GuildSettings.GetGuildSettings(user.Guild).CommandChannel; } if (channel == null) { return; } // the user leveled up var embed = new EmbedBuilder(); embed.WithColor(Colors.Get(userAccount.Element.ToString())); embed.WithTitle("LEVEL UP!"); embed.WithDescription("<:Up_Arrow:571309108289077258> " + userAccount.GsClass + " " + user.Mention + " just leveled up!"); embed.AddField("LEVEL", userAccount.LevelNumber, true); embed.AddField("XP", userAccount.XP, true); if (userAccount.LevelNumber == 10) { embed.AddField("Congratulations!", "You have unlocked Easy mode in the Weyard battle channels!"); } else if (userAccount.LevelNumber == 30) { embed.AddField("Congratulations!", "You have unlocked Medium mode in the Weyard battle channels!"); } else if (userAccount.LevelNumber == 50) { embed.AddField("Congratulations!", "You have unlocked Hard mode in the Weyard battle channels, as well as the Endless mode!"); } await channel.SendMessageAsync("", embed : embed.Build()); }
public override async Task RunAsync() { var gs = GuildSettings.GetGuildSettings(Context.Guild); try { if (Context is RequestInteractionContext r) { await r.OriginalInteraction.DeferAsync(); } } catch (HttpException) { } var acc = EntityConverter.ConvertUser(Context.User); var openBattle = new EndlessBattleEnvironment(_battleService, $"{Context.User.Username}", gs.ColossoChannel, false, await _battleService.PrepareBattleChannel($"Endless-{Context.User.Username}", Context.Guild, persistent: false)); if (FastTrack && acc.Inv.RemoveBalance(Cost)) { UserAccountProvider.StoreUser(acc); openBattle.SetStreak(12); } _battleService.AddBattleEnvironment(openBattle); await Context.Channel.SendMessageAsync( $"{Context.User.Username}, {openBattle.BattleChannel.Mention} has been prepared for an endless adventure"); }
private async Task HandleCommandAsync(SocketMessage s) { if (Program.CurrentState == Program.State.Booting || Program.CurrentState == Program.State.Exiting || s.Author.IsBot) { return; } GuildSettings guildSet = GuildSettings.Load(s); if (!(s is SocketUserMessage msg) || (guildSet != null && guildSet.Ignore)) { return; } CustomCommandContext context = new CustomCommandContext(_client, msg) { guildSettings = guildSet }; string prefix = guildSet == null ? "" : guildSet.prefix == null || guildSet.prefix.Length < 1 ? defaultPrefix : guildSet.prefix; if (MessageIsApproved(msg, prefix, out int argPosition) && await GameMaster.VerifyChannel(context, guildSet)) { switch (Program.CurrentState) { case Program.State.Paused: if (s.Author.Id != 201875246091993088) { DUtils.DeleteMessage(await context.Channel.SendMessageAsync( "Server under maintenance, please refer to the support server for more information.")); return; } break; case Program.State.Ready: break; case Program.State.Updating: DUtils.DeleteMessage(await context.Channel.SendMessageAsync("Leaving for tea break soon. [Incoming Update]")); break; } if (!RunUser(s.Author.Id)) { return; } _ = context.BotUser; _ = Task.Run(async() => { try { await _command.ExecuteAsync(context, argPosition, null); } catch (Exception e) { Log.LogS(e); } }); } }
public async Task ConfigAsync() { ulong id = Context.Guild.Id; GuildSettings guild = await GuildSettings.GetSettings(id); string?prefix = guild.CommandPrefix; string p = prefix ?? ""; // --------------------------------------------------------------------------------------------------------- StringBuilder dsb = new StringBuilder() .AppendLine("Additional, server-specific commands for configuring the bot. Anyone with `Administrator` or `Manage Server` perms can invoke these.") .AppendLine() .AppendLine($"{B}`{p}set prefix [prefix]`: Set the command prefix the bot listens for on this server. `>` by default.") .AppendLine() .AppendLine($"{B}`{p}set locale [locale]`: Set the locale (language-country) the bot uses on this server for printing cards etc. `en-US` by default.") .AppendLine() .AppendLine($"{B}`{p}locales`: List all available locale strings."); // --------------------------------------------------------------------------------------------------------- Embed embed = new EmbedBuilder() .WithDescription(dsb.ToString()) .Build(); await ReplyAsync(embed : embed); }
public async Task UpdateGuildSettingsAsync(GuildSettings settings) { using var scope = _services.CreateScope(); var dbContext = scope.ServiceProvider.GetRequiredService <CheeseBotDbContext>(); dbContext.Update(settings); await dbContext.SaveChangesAsync(); }
private async Task Client_UserLeft(SocketGuildUser user) { if (GuildSettings.GetGuildSettings(user.Guild).sendLeaveMessage) { _ = GuildSettings.GetGuildSettings(user.Guild).TestCommandChannel.SendMessageAsync($"{user.DisplayName()} left the party :(."); } await Task.CompletedTask; }
public void AutoJoinAsync(SocketMessage message, [Summary("Catagory For Annyoamus Channel")] bool enable) { if (!(message.Author is SocketGuildUser user)) { return; } GuildSettings.SetAutoJoin(user.Guild.Id, enable); }
public async Task StreamMessage(GuildSettings settings, IUserMessage message) { if (message is TwitchMessage) { return; } await SendMessage(settings.TwitchSettings.ChannelName, $"{message.Author}: {message.Content}"); }
// Override the CheckPermissions method public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context, CommandInfo command, IServiceProvider services) { if (context.Guild != null && GuildSettings.GetGuildSettings(context.Guild).IsUserServer) { return(Task.FromResult(PreconditionResult.FromSuccess())); } return(Task.FromResult(PreconditionResult.FromError("You must be in an approved server to run this."))); }
private void AddNotifyTask(GuildSettings guild, Notify notify) { var notifyHashCode = guild.Notifys[guild.Notifys.IndexOf(notify)].GetHashCode(); var task = new NotifyTask(() => { if (_client.ConnectionState != ConnectionState.Connected) { RaiseLog(LogSeverity.Warning, $"No connection to perform notify task."); return; } var newNotifyEntry = guild.Notifys.Find(n => n.GetHashCode() == notifyHashCode); if (newNotifyEntry.Info.SourceId == null) { var obj = _vk.ResolveScreeName(newNotifyEntry.Info.SourceDomain); newNotifyEntry.Info.SourceId = obj.Id; if (obj.Type == VkNet.Enums.VkObjectType.Group) { newNotifyEntry.Info.SourceId *= -1; } } var posts = CheckWallPosts(newNotifyEntry); if (posts.Count != 0) { var typingState = ((SocketTextChannel)_client.GetChannel(notify.Info.ChannelId)).EnterTypingState(); DateTime?newLastSent = newNotifyEntry.LastSent; posts.ForEach((post) => newLastSent = newLastSent < post.Date ? post.Date : newLastSent); newNotifyEntry.LastCheck = DateTime.Now; newNotifyEntry.LastSent = (DateTime)newLastSent; guild.Notifys.Remove(guild.Notifys.Find(n => n.GetHashCode() == notifyHashCode)); guild.Notifys.Add(newNotifyEntry); notifyHashCode = newNotifyEntry.GetHashCode(); _data.UpdateGuildSettings(guild.GuildId, guild); SentNotify(posts, newNotifyEntry.Info); typingState.Dispose(); } }, notify.Info, DataManager.BotSettings.NotifyDueTime, notify.Info.UpdatePeriod * MILLISECONDS_PER_MINUTE); task.TaskStarted += (t) => { RaiseLog(LogSeverity.Debug, $"Notify task started. TaskId={t.Id}"); }; task.TaskEnded += (t, result) => { var severety = LogSeverity.Debug; if (result == TaskStatus.Canceled || result == TaskStatus.Faulted) { severety = LogSeverity.Warning; } RaiseLog(severety, $"Notify task ended. TaskId={t.Id} Result={result.ToString()}"); }; if (!_notifys.ContainsKey(guild.GuildId)) { _notifys.Add(guild.GuildId, new List <NotifyTask>()); } _notifys[guild.GuildId].Add(task); RaiseLog(LogSeverity.Debug, $"Added notify task. GuildId={guild.GuildId}"); }
private async Task OnUserJoinAsync(SocketGuildUser user) { if (GuildSettings.GetGuildSettings(user.Guild.Id).AutoJoin) { await new AnonChannelManagement(GuildSettings.GetGuildSettings(user.Guild.Id).CatagoryID).CreateAnonChannel(user); } return; }
public async Task SaveAsync(GuildSettings teamsettings) { var objectToSave = new CosmosObject <GuildSettings> { Id = $"{_objectType}::{teamsettings.GuildId}", Item = teamsettings }; await _cosmosContainer.UpsertItemAsync(objectToSave, new PartitionKey(_objectType)); }
private async Task Update() { prefixCache.Clear(); foreach (SocketGuild guild in Program.DiscordClient.Guilds) { GuildSettings settings = await SettingsService.GetSettings <GuildSettings>(guild.Id); prefixCache.Add(guild.Id, settings.Prefix); } }
/// <summary> /// update existing guild settings in database /// </summary> /// <param name="settings"></param> public void UpdateGuildSettings(GuildSettings settings) { MySqlCommand command = new MySqlCommand("UPDATE Guildsettings SET owner=@owner,levelbackground=@levelbackground WHERE id = @id", connection); command.Parameters.AddWithValue("@id", settings.GuildId); command.Parameters.AddWithValue("@owner", settings.Owner); command.Parameters.AddWithValue("@levelbackground", settings.LevelbackgroundImage); command.Prepare(); command.ExecuteNonQuery(); }