private async Task HandleCommandAsync(SocketMessage s) { if (!(s is SocketUserMessage msg)) { return; } var context = new SocketCommandContext(_client, msg); if (context.User.IsBot) { return; } Leveling.MessageReceived(context.User as SocketGuildUser, context.Channel as SocketTextChannel); int argPos = 0; // If the guild prefix hasn't been set, then get the default one if (msg.HasStringPrefix(Guilds.GetGuild(context.Guild).Prefix ?? Config.Bot.DefaultPrefix, ref argPos) || msg.HasMentionPrefix(_client.CurrentUser, ref argPos)) { var result = await _service.ExecuteAsync(context, argPos); if (!result.IsSuccess) { Console.WriteLine(result.ErrorReason); } } }
public static GuildsAttitude getGuildAttitude(Guilds g1, Guilds g2) { if (GuildAttitudes.ContainsKey(g1) && GuildAttitudes[g1].ContainsKey(g2)) { return(GuildAttitudes[g1][g2]); } else if (GuildAttitudes.ContainsKey(g2) && GuildAttitudes[g2].ContainsKey(g1)) { return(GuildAttitudes[g2][g1]); } if (g1 < Guilds.HUM_SPERATOR && g2 < Guilds.HUM_SPERATOR) { return(GuildsAttitude.FRIENDLY); } if (g1 < Guilds.HUM_SPERATOR && g2 > Guilds.HUM_SPERATOR) { return(GuildsAttitude.HOSTILE); } if (g2 < Guilds.HUM_SPERATOR && g1 > Guilds.HUM_SPERATOR) { return(GuildsAttitude.HOSTILE); } return(GuildsAttitude.NEUTRAL); }
/// <summary> /// Save all the current bot variables such as user accounts and guilds. /// </summary> /// <returns></returns> public static Task SaveAll() { UserAccounts.SaveAccounts(); Guilds.SaveGuilds(); return(Task.CompletedTask); }
public virtual bool OnGuildCreate(DiscordPacket Packet) { Guild Guild = null; if (long.TryParse(Packet.d["id"].GetString(), out long Id)) { if (Guilds.TryGet(Id, out Guild)) { Console.WriteLine($"Found guild obj for {Id}, patching"); try { Guild.Patch(Packet.d); }catch (Exception Ex) { Console.WriteLine($"Exception during patch: {Ex.Message}\n{Ex.StackTrace}"); } } else { Console.WriteLine($"Creating new guild for {Id}"); Guilds.CreateEntry(Packet.d); } } Console.WriteLine(Guild); GuildCreate?.Invoke(this, Guild); return(true); }
public Guild FindGuild(IGuild iguild) { Check.NotNull(iguild); return(Guilds.Include(g => g.Commands) .Include(g => g.Channels) .FirstOrDefault(g => g.Id == iguild.Id)); }
public static async Task AnnounceUserJoin(SocketGuildUser guildUser) { if (guildUser.IsBot) { return; } var guild = await Guilds.GetAsync(guildUser.Guild); var announce = guild.General.Announce; var embed = new EmbedBuilder(); var socketGuild = guildUser.Guild; var channel = socketGuild.GetTextChannel(announce.Welcomes.Channel) ?? socketGuild.SystemChannel ?? socketGuild.DefaultChannel; string imageURL = $"{Global.Config.DashboardURL}/api/servers/{guildUser.Guild.Id}/users/{guildUser.Id}/welcome"; var stream = await CommandUtils.DownloadData(imageURL); if (!announce.DMNewUsers) { await(channel as ISocketMessageChannel)?.SendFileAsync(stream, "welcome.png"); } else if (announce.DMNewUsers) { await guildUser.SendFileAsync(stream, "welcome.png"); } }
/// <summary> /// Deletes a specific guild from the Guilds database table /// </summary> /// <param name="id">Unique ID of the targeted guild</param> /// <returns>Task of completion</returns> public async Task Delete(int id) { Guilds guild = await _context.Guilds.FindAsync(id); _context.Entry(guild).State = EntityState.Deleted; await _context.SaveChangesAsync(); }
/// <summary> /// Gets a specific guild from the Guilds database table /// </summary> /// <param name="id">Unique ID of the targeted guild</param> /// <returns>Targeted guild object</returns> public async Task <GuildsDTO> GetGuild(int id) { Guilds guild = await _context.Guilds.FindAsync(id); List <GameGuilds> gameGuilds = await _context.GameGuilds.Where(x => x.GuildId == id).ToListAsync(); List <GamesDTO> games = new List <GamesDTO>(); foreach (var item in gameGuilds) { games.Add(await _games.GetGame(item.GameId)); } GuildsDTO dto = new GuildsDTO() { Name = guild.Name, Games = games, Id = guild.Id }; foreach (var item in games) { item.Guilds = null; } return(dto); }
/// <summary> /// Sprawdź i oceń odpowiedź użytkownika /// </summary> /// <param name="wasSeen"> /// Czy użytkownik widział to pytanie /// </param> /// <param name="goodAnswer"> /// Czy użytkownik odpowiedział poprawnie na pytanie /// </param> /// <param name="id"> /// Id pytania /// </param> /// <param name="categoryId"> /// Id kategorii /// </param> /// <param name="userAccount"> /// Konto użytkownika /// </param> /// <param name="channel"> /// Kanał na który należy poinformować użytkownika o wyniku /// </param> /// <returns></returns> private static async Task CheckScore(bool wasSeen, bool goodAnswer, int id, int categoryId, UserAccount userAccount, ISocketMessageChannel channel) { if (wasSeen && goodAnswer) { // check if user has this question in wrongly answered questions if (userAccount.WrongAnswersQuestionIds.Contains(id)) { // remove this question from wrongly answered questions userAccount.WrongAnswersQuestionIds.Remove(id); // Add points to category scores userAccount.CategoryComplition[categoryId]++; } } else if (goodAnswer) //if user haven't seen this question and answers correctly { // Add points to category scores userAccount.CategoryComplition[categoryId]++; } else if (!wasSeen) //if user haven't seen this question and answers wrongly { // Add question to wrongly answered questions userAccount.WrongAnswersQuestionIds.Add(id); } // check if user seen this question for the first time if (!wasSeen) { userAccount.SeenQuestionsIds.Add(id); } NotifyAboutResult(goodAnswer, channel); Guilds.Save(); }
private void HookClientEvents() { bot.Ready += async() => { try { await lavaClient.StartAsync(bot); lavaClient.OnTrackFinished += services.GetService <AudioService>().OnFinished; await bot.SetGameAsync(Global.Config.Bot.Status); await new DatabaseManager(Global.Config.MongoURI).UpdateCommands(new CommandHelp()); } catch (Exception ex) { await Debug.LogCriticalAsync(ex.Source, ex.Message); } }; bot.JoinedGuild += async(SocketGuild socketGuild) => { var newGuild = await Guilds.GetAsync(socketGuild); var channel = socketGuild.SystemChannel ?? socketGuild.DefaultChannel; var embed = new EmbedBuilder(); embed.WithTitle($"Hi, I'm {bot.CurrentUser.Username}!"); embed.AddField("⚙️ Config", $"Customize me to your server's needs at {Global.Config.DashboardURL}/servers/{socketGuild.Id}", inline: true); embed.AddField("📜 Commands", $"Type {newGuild.General.CommandPrefix}help for a list of commands.", inline: true); embed.AddField("❔ Support", $"Need help with {bot.CurrentUser.Username}? Join our Discord for more support: {Global.Config.DashboardURL}/support", inline: true); await channel.SendMessageAsync(embed : embed.Build()); }; }
public async Task MarkovUserChannel(CommandContext ctx, [Description("Which channel the bot should look at.")] DiscordChannel channel, [Description("Which user's messages the bot should look at.")] DiscordUser user, [Description("How many messages the bot should look at.")] int amount = 500, int order = 0) { if (amount >= 10000) { amount = 10000; } var messages = await channel.GetMessagesAsync(amount); messages = messages.Where(msg => msg.Author == user).ToList(); var lines = messages.Select(msg => msg.Content).ToList(); //Select content lines = lines.Where(s => !string.IsNullOrWhiteSpace(s)).ToList(); //Remove empty messages lines = lines.Where(s => !s.Contains($"{Guilds.GetGuild(ctx.Guild).Prefix}markov")).ToList(); if (lines.Count == 0) { await MarkovUser(ctx, user, amount + 10); return; } await ctx.RespondAsync(MarkovResponse(order, lines)); }
public void RemoveGuild(IGuild guild) { var guildConfig = GetGuildConfigurationInternal(guild); Guilds.Remove(guildConfig); Save(); }
public async Task LoadRemoteAsync() { ChangeTracker.AutoDetectChangesEnabled = false; await Guilds .LoadAsync() .ConfigureAwait(false); await Channels .LoadAsync() .ConfigureAwait(false); await Games .LoadAsync() .ConfigureAwait(false); await Trackers .Where(t => t.State != TrackerState.Dead) .LoadAsync() .ConfigureAwait(false); await Races .Include(r => r.Entrants) .Include(r => r.Announcements) .Where(r => r.IsActive) .LoadAsync() .ConfigureAwait(false); }
public IEnumerator GetGuildsRoutine(Action <Guilds> action) { string uri = NetworkSettings.instance.BaseUri() + "/api/guild/list"; var form = new WWWForm(); form.AddField("playerId", NetworkSettings.instance.username); form.AddField("authtoken", NetworkSettings.instance.authtoken); WWW www = new WWW(uri, form.data, form.headers); yield return(www); if (www.error != null) { Debug.Log(www.error); action(null); } else { MemoryStream stream = new MemoryStream(www.bytes); Guilds guilds = Serializer.Deserialize <Guilds>(stream); action(guilds); } }
private IResult TeachSpellSkill(Guilds guild, IMobileObject guildMaster, IMobileObject learner, string parameter) { GuildAbility skill = GlobalReference.GlobalValues.GuildAbilities.Skills[guild].FirstOrDefault(i => string.Equals(i.Abiltiy.AbilityName, parameter, StringComparison.CurrentCultureIgnoreCase)); if (skill != null) { if (skill.Level <= learner.Level) { return(TeachSkill((ISkill)skill.Abiltiy, guildMaster, learner)); } else { return(NotHighEnoughLevel(guildMaster, learner)); } } GuildAbility spell = GlobalReference.GlobalValues.GuildAbilities.Spells[guild].FirstOrDefault(i => string.Equals(i.Abiltiy.AbilityName, parameter, StringComparison.CurrentCultureIgnoreCase)); if (spell != null) { if (spell.Level <= learner.Level) { return(TeachSpell((ISpell)spell.Abiltiy, guildMaster, learner)); } else { return(NotHighEnoughLevel(guildMaster, learner)); } } guildMaster.EnqueueCommand(string.Format("Tell {0} I can not teach you that.", learner.KeyWords[0])); return(new Result("", true)); }
public async Task SetLeaveMsg(CommandContext ctx, [RemainingText, Description( "The new Leave message. You can use '[user]' for \"pinging\" the user. Pass 'disable' if you don't want one.")] string lm = "") { if (lm == "disable") { lm = "empty"; } if (lm == "") { await ctx.RespondAsync( $"The current LeaveMessage on this guild is: \"{Guilds.GetGuild(ctx.Guild).LeaveMsg}\""); return; } Utilities.Con.Open(); using (var cmd = new SqliteCommand("UPDATE Guilds SET leaveMsg = @message WHERE Guilds.id = @id", Utilities.Con)) { cmd.Parameters.AddWithValue("@message", lm); cmd.Parameters.AddWithValue("@id", ctx.Guild.Id); cmd.ExecuteReader(); } Utilities.Con.Close(); Guilds.UpdateGuild(ctx.Guild); await ctx.Message.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":white_check_mark:")); }
private async Task HandleCommandAsync(SocketMessage messageParam) { if (Settings.Default.InLockdown == false) { // Don't process the command if it was a System Message var message = messageParam as SocketUserMessage; var guildchannel = messageParam.Channel as SocketGuildChannel; var config = Guilds.getorcreateguild(guildchannel.Guild); if (message == null) { return; } // Create a number to track where the prefix ends and the command begins int argPos = 0; // Determine if the message is a command, based on if it starts with '!' or a mention prefix if (!(message.HasStringPrefix(config.prefix, ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos))) { return; } // Create a Command Context var context = new SocketCommandContext(_client, message); // Execute the command. (result does not indicate a return value, // rather an object stating if the command executed successfully) var result = await _commands.ExecuteAsync(context, argPos, _services); if (!result.IsSuccess) { await context.Channel.SendMessageAsync(result.ErrorReason); } } }
private void Update() { try { if (this.Players == null) { return; } if (this.DB == null) { return; } Players.SaveModified(DB); Guilds.SaveModified(DB.Guilds); Notifications.SaveModified(DB.Notifications); Chat.DumpToDatabase(DB.Chat); Stores.SaveChanges(); RaceCommands.Save(); Election.Update(); raceStats.Save(); friends.Update(); }catch (Exception ex) { log.Error(ex); log.Error(ex.StackTrace); } }
public async Task SetPrefix([Remainder] string prefix = "") { try { CurrentGuild ??= await Guilds.GetAsync(Context.Guild); if (string.IsNullOrEmpty(prefix)) { await ReplyAsync(EmbedHandler.CreateBasicEmbed(ModuleName, $"**Current Prefix**: `{CurrentGuild.General.CommandPrefix}`", ModuleColour)); return; } const int maxLength = 16; if (prefix.Length > maxLength) { throw new ArgumentException($"Prefix must be less than {maxLength + 1} characters long."); } CurrentGuild.General.CommandPrefix = prefix; await Guilds.Save(CurrentGuild); await ReplyAsync(EmbedHandler.CreateBasicEmbed(ModuleName, $"Prefix has been set to `{prefix}`", Color.Green)); } catch (ArgumentException ex) { await ReplyAsync(EmbedHandler.CreateErrorEmbed(ModuleName, ex.Message)); } }
public async Task Disconnect() { Guilds.Clear(); OverwriteNames.Clear(); Channels.Clear(); await DSharpPlusConnection.Disconnect(); }
public GuildQueryResult() { OnClientUpdated += (sender, e) => { Guilds.SetClientsInList(Client); }; }
public async Task LewdNeko() { if (!Guilds.GetGuild(Context.Guild).GetChannel(Context.Channel).IsNsfw) { await Context.Channel.SendMessageAsync("Th-That's for NSFW channels! You lewdie!!!"); return; } string json; using (var client = new WebClient()) { json = client.DownloadString("https://nekos.life/api/lewd/neko"); } string timestamp = System.DateTime.Now.ToString(CultureInfo.InvariantCulture); var searchResult = JsonConvert.DeserializeObject <dynamic>(json); var embed = new EmbedBuilder(); var url = searchResult.neko.ToString(); embed.WithImageUrl(url); embed.WithTitle($"Neko for {Global.GetNickname((IGuildUser)Context.User)}!"); embed.WithAuthor("Source : Nekos.life"); embed.WithFooter($"Timestamp : {timestamp} GMT-5 "); embed.WithColor(255, 0, 255); await Context.Channel.SendMessageAsync("", false, embed); }
public async Task YubooruStats(string stat, params string[] tags) { if (!Guilds.GetGuild(Context.Guild).GetChannel(Context.Channel).IsNsfw) { await Context.Channel.SendMessageAsync("Th-That's for NSFW channels! You lewdie!!!"); return; } // ToLower() is bad practice, but switches only use ordinal comparison switch (stat.ToLower()) { case "total": var imageInfoFilePath = Config.Bot.YubooruLocation + "\\ImageInfo.json"; var json = File.ReadAllText(imageInfoFilePath); var images = JsonConvert.DeserializeObject <List <ImageInfo> >(json); var matchingimages = new List <ImageInfo>(); Search(tags, images, matchingimages); var tagsString = string.Join(" + ", tags); await Context.Channel.SendMessageAsync($"Yubooru currently contains {matchingimages.Count} images of tags \"{tagsString}\"!"); break; default: await Context.Channel.SendMessageAsync("Unknown statistic!"); break; } }
public void RemoveGuild(Guild myguild) { lock (Guilds.SyncRoot) { myguild.alliance = null; myguild.AllianceId = ""; Guilds.Remove(myguild); if (myguild.GuildID == m_dballiance.DBguildleader.GuildID) { SendMessageToAllianceMembers(myguild.Name + " has disbanded the alliance of " + m_dballiance.AllianceName, PacketHandler.eChatType.CT_System, PacketHandler.eChatLoc.CL_SystemWindow); ArrayList mgl = new ArrayList(Guilds); foreach (Guild mg in mgl) { try { RemoveGuild(mg); } catch (Exception) { } } GameServer.Database.DeleteObject(m_dballiance); } else { m_dballiance.DBguilds = null; GameServer.Database.SaveObject(m_dballiance); GameServer.Database.FillObjectRelations(m_dballiance); } //sirru 23.12.06 save changes to db for each guild myguild.SaveIntoDatabase(); myguild.SendMessageToGuildMembers(myguild.Name + " has left the alliance of " + m_dballiance.AllianceName, PacketHandler.eChatType.CT_System, PacketHandler.eChatLoc.CL_SystemWindow); SendMessageToAllianceMembers(myguild.Name + " has left the alliance of " + m_dballiance.AllianceName, PacketHandler.eChatType.CT_System, PacketHandler.eChatLoc.CL_SystemWindow); } }
public async Task YubooruStats() { if (!Guilds.GetGuild(Context.Guild).GetChannel(Context.Channel).IsNsfw) { await Context.Channel.SendMessageAsync("Th-That's for NSFW channels! You lewdie!!!"); return; } var imageInfoFilePath = Config.Bot.YubooruLocation + "\\ImageInfo.json"; var json = File.ReadAllText(imageInfoFilePath); var images = JsonConvert.DeserializeObject <List <ImageInfo> >(json); var embed = new EmbedBuilder { Title = "Yubooru's stats", Color = Color.DarkMagenta }; embed.AddInlineField("images", images.Count); embed.AddInlineField("Tags", GetTotalTagCount()); embed.AddInlineField("Artists", GetTotalArtistCount()); embed.AddInlineField("Copyrights", GetTotalCopyrightCount()); embed.AddInlineField("Characters", GetTotalCharacterCount()); embed.AddInlineField("Contributors", 1); // Filler field because 5 fields looks really ugly on desktop await Context.Channel.SendMessageAsync("", embed : embed); }
public Task <KeyRedemptionObject> RedeemKeyAsync(ulong guildId, string key) { var keyObj = Keys.FirstOrDefault(x => x.Key == key); if (keyObj != null) { if (Guilds.TryGetValue(guildId, out Guild guild)) { guild.Upgrades.Add(new GuildKey { Key = keyObj.Key, ValidFor = keyObj.ValidFor }); Keys = Keys.Where(x => x.Key != key).ToList(); Save(); return(Task.FromResult(new KeyRedemptionObject { Success = true, ValidFor = keyObj.ValidFor })); } return(Task.FromResult(failKeyRedemption)); } return(Task.FromResult(failKeyRedemption)); }
public bool Contains(Guild myguild) { lock (Guilds.SyncRoot) { return(Guilds.Contains(myguild)); } }
public async Task RepeatMsg(CommandContext ctx, [Description("The amount of messages that need to have the same content. Set to 0 to disable.")] string amount = "") { if (amount == "") { await ctx.RespondAsync( $"If {Guilds.GetGuild(ctx.Guild).PrevMessageAmount} messages in a row have the same content, the bot will repeat it"); return; } Utilities.Con.Open(); using (var cmd = new SqliteCommand("UPDATE Guilds SET prevMessageAmount = @amount WHERE Guilds.id = @id", Utilities.Con)) { cmd.Parameters.AddWithValue("@amount", int.Parse(amount)); cmd.Parameters.AddWithValue("@id", ctx.Guild.Id); cmd.ExecuteReader(); } Utilities.Con.Close(); Guilds.UpdateGuild(ctx.Guild); await ctx.Message.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":white_check_mark:")); }
private Task <ResponseStatus> UpdateGuildAsync(ulong guildId, string message) { if (Guilds.TryGetValue(guildId, out var guild)) { int max = guild.MaxCharacters(); if (guild.TotalCharacters >= max) { return(Task.FromResult(ResponseStatus.GuildLimitExceeded)); } if (guild.TotalCharacters + message.Length > max) { return(Task.FromResult(ResponseStatus.GuildLimitExceededByMessage)); } guild.TotalCharacters += message.Length; return(Task.FromResult(ResponseStatus.GuildSucceded)); } else { Guilds.TryAdd(guildId, new Guild { GuildId = guildId }); } return(Task.FromResult(ResponseStatus.GuildLimitExceeded)); }
public async Task Yubooru(params string[] tags) { if (!Guilds.GetGuild(Context.Guild).GetChannel(Context.Channel).IsNsfw) { await Context.Channel.SendMessageAsync("Th-That's for NSFW channels! You lewdie!!!"); return; } var directory = new DirectoryInfo(Config.Bot.YubooruLocation); var imageInfoFilePath = Config.Bot.YubooruLocation + "\\ImageInfo.json"; var json = File.ReadAllText(imageInfoFilePath); var images = JsonConvert.DeserializeObject <List <ImageInfo> >(json); List <ImageInfo> matchingimages = new List <ImageInfo>(); Search(tags, images, matchingimages); var image = matchingimages[Global.Random.Next(matchingimages.Count)]; var imageFile = directory.GetFiles().FirstOrDefault(f => Path.GetFileNameWithoutExtension(f.Name) == image.Id); UserAccounts.GetAccount(Context.User).LastYubooruImageInfo = image; await Context.Channel.SendFileAsync(imageFile?.FullName); }
public TSAlchemistDeed(Guilds.Guild guild) : base(guild) { SetName("an alchemist"); }
public TSTownCrierDeed(Guilds.Guild guild) : base(guild) { SetName("the town crier"); }
public TSInnkeeperDeed(Guilds.Guild guild) : base(guild) { SetName("an innkeeper"); }
public TSEvocatorDeed(Guilds.Guild guild) : base(guild) { SetName("an evocator"); }
public TSEmissaryDeed(Guilds.Guild guild) : base(guild) { SetName("an emissary"); }
public TSRogueTrainerDeed(Guilds.Guild guild) : base(guild) { SetName("a rogue trainer"); }
public TSMageTrainerDeed(Guilds.Guild guild) : base(guild) { SetName("a mage trainer"); }
public TSAnimalTrainerDeed(Guilds.Guild guild) : base(guild) { SetName("an animal trainer"); }
public TSProvisionerDeed(Guilds.Guild guild) : base(guild) { SetName("a provisioner"); }
public TSLookoutDeed(Guilds.Guild guild) : base(guild) { SetName("a lookout"); }
public TSMageDeed(Guilds.Guild guild) : base(guild) { SetName("a mage"); }
public TSArmsTrainerDeed(Guilds.Guild guild) : base(guild) { SetName("an arms trainer"); }
public TSBankerDeed(Guilds.Guild guild) : base(guild) { SetName("a banker"); }