public JSONContainer ToJSON() { JSONContainer result = JSONContainer.NewObject(); result.TryAddField(JSON_ACTIVE, Active); result.TryAddField(JSON_CHANNELIDS, ChannelId); result.TryAddField(JSON_ROLEID, RoleId); result.TryAddField(JSON_CAPTAINID, CaptainId); result.TryAddField(JSON_FOUNDINGTIMESTAMP, FoundingTimestamp.ToString("u")); JSONContainer memberIdList = JSONContainer.NewArray(); foreach (ulong id in MemberIds) { memberIdList.Add(id); } result.TryAddField(JSON_MEMBERIDS, memberIdList); JSONContainer mateIdList = JSONContainer.NewArray(); foreach (ulong id in MateIds) { mateIdList.Add(id); } result.TryAddField(JSON_MATEIDS, mateIdList); return(result); }
internal static void LoadSettings(ulong guildId, BotVar var) { if (var.IsGeneric) { JSONContainer json = var.Generic; if (json.TryGetField(JSON_ENABLEDEBUG, out JSONContainer debugSettings)) { if (debugSettings.IsArray) { for (int i = 0; i < debugSettings.Array.Count && i < debugLogging.Length; i++) { debugLogging[i] = debugSettings.Array[i].Boolean; } } } json.TryGetField(JSON_MODERATORROLE, out AdminRole); json.TryGetField(JSON_WELCOMINGMESSAGE, out welcomingMessage, welcomingMessage); json.TryGetField(JSON_MUTEROLE, out MuteRole); if (json.TryGetField(JSON_CHANNELINFOS, out JSONContainer guildChannelInfoContainer)) { GuildChannelHelper.FromJSON(guildChannelInfoContainer); } if (json.TryGetArrayField(JSON_AUTOASSIGNROLEIDS, out JSONContainer autoAssignRoles)) { foreach (JSONField idField in autoAssignRoles.Array) { if (idField.IsNumber && !idField.IsFloat && !idField.IsSigned) { EventLogger.AutoAssignRoleIds.Add(idField.Unsigned_Int64); } } } } }
/// <summary> /// Initiates the GuildChannelHelpers stored configs and ids from a json object /// </summary> /// <param name="json">json data</param> public static void FromJSON(JSONContainer json) { channelConfigs.Clear(); json.TryGetField(JSON_DEBUGCHANNELID, out DebugChannelId); json.TryGetField(JSON_WELCOMINGCHANNELID, out WelcomingChannelId); json.TryGetField(JSON_ADMINCOMMANDUSAGELOGCHANNELID, out AdminCommandUsageLogChannelId); json.TryGetField(JSON_ADMINNOTIFICATIONCHANNELID, out AdminNotificationChannelId); json.TryGetField(JSON_INTERACTIVEMESSAGECHANNELID, out InteractiveMessagesChannelId); json.TryGetField(JSON_GUILDCATEGORYID, out GuildCategoryId); if (json.TryGetField(JSON_CHANNELINFOS, out IReadOnlyList <JSONField> channelInfos)) { foreach (JSONField channelInfo in channelInfos) { if (channelInfo.IsObject) { GuildChannelConfiguration info = new GuildChannelConfiguration(); if (info.FromJSON(channelInfo.Container)) { channelConfigs.Add(info.Id, info); } } } } }
/// <summary> /// Saves all settings to appdata/locallow/Ciridium Wing Bot/Settings.json /// </summary> internal static void SaveSettings() { JSONContainer json = JSONContainer.NewObject(); JSONContainer debugSettings = JSONContainer.NewArray(); foreach (bool b in debugLogging) { debugSettings.Add(b); } json.TryAddField(JSON_MODERATORROLE, AdminRole); json.TryAddField(JSON_ENABLEDEBUG, debugSettings); json.TryAddField(JSON_WELCOMINGMESSAGE, welcomingMessage); json.TryAddField(JSON_MUTEROLE, MuteRole); json.TryAddField(JSON_CHANNELINFOS, GuildChannelHelper.ToJSON()); JSONContainer autoAssignRoleIds = JSONContainer.NewArray(); foreach (var roleId in EventLogger.AutoAssignRoleIds) { autoAssignRoleIds.Add(roleId); } json.TryAddField(JSON_AUTOASSIGNROLEIDS, autoAssignRoleIds); BotVarManager.GlobalBotVars.SetBotVar("YNBsettings", json); }
public static async Task <RequestJSONResult> GetWebJSONAsync(string url) { RequestJSONResult loadresult = new RequestJSONResult(); try { using (HttpRequestMessage requestmessage = new HttpRequestMessage(HttpMethod.Get, url)) { requestmessage.Version = new Version(1, 1); using (HttpResponseMessage responsemessage = await httpClient.SendAsync(requestmessage)) { loadresult.Status = responsemessage.StatusCode; loadresult.IsSuccess = responsemessage.IsSuccessStatusCode; if (responsemessage.IsSuccessStatusCode) { loadresult.rawData = await responsemessage.Content.ReadAsStringAsync(); JSONContainer.TryParse(loadresult.rawData, out loadresult.JSON, out loadresult.jsonParseError); } } } } catch (Exception e) { loadresult.IsException = true; loadresult.ThrownException = e; } return(loadresult); }
protected override Task <ArgumentParseResult> ParseArgumentsGuildAsync(IGuildCommandContext context) { ArgumentContainer argOut = new ArgumentContainer(); if (!ArgumentParsing.TryParseGuildTextChannel(context, context.Arguments.First, out argOut.channel)) { return(Task.FromResult(new ArgumentParseResult(Arguments[0], "Failed to parse to a guild text channel!"))); } if (context.Message.Content.Length > Identifier.Length + context.Arguments.First.Length + 2) { context.Arguments.Index++; string embedText = context.RemoveArgumentsFront(1).Replace("[3`]", "```"); if (JSONContainer.TryParse(embedText, out JSONContainer json, out string errormessage)) { if (EmbedHelper.TryGetMessageFromJSONObject(json, out argOut.embed, out argOut.messageContent, out string error)) { return(Task.FromResult(new ArgumentParseResult(argOut))); } else { return(Task.FromResult(new ArgumentParseResult(Arguments[1], error))); } } else { return(Task.FromResult(new ArgumentParseResult(Arguments[1], $"Unable to parse JSON text to a json data structure! Error: `{errormessage}`"))); } }
public static async Task <LoadFileOperation> LoadToJSONObject(string path) { LoadFileOperation operation = new LoadFileOperation() { Success = false, Result = null }; if (File.Exists(path)) { string fileContent = ""; try { fileContent = await File.ReadAllTextAsync(path, Encoding.UTF8); operation.Success = JSONContainer.TryParse(fileContent, out operation.Result, out string error); return(operation); } catch (Exception e) { await YNBBotCore.Logger(new Discord.LogMessage(Discord.LogSeverity.Critical, "Save/Load", "Failed to load " + path, e)); } } return(operation); }
public JSONContainer ToJSON() { JSONContainer result = JSONContainer.NewObject(); JSONContainer eventChannelsJSON = JSONContainer.NewObject(); foreach (var channel in EventLogChannels) { eventChannelsJSON.TryAddField(channel.Key.ToString(), channel.Value); } result.TryAddField("EventLogChannels", eventChannelsJSON); JSONContainer userModChannelsJSON = JSONContainer.NewObject(); foreach (var channel in UserModLogChannels) { userModChannelsJSON.TryAddField(channel.Key.ToString(), channel.Value); } result.TryAddField("UserModLogChannels", userModChannelsJSON); JSONContainer channelModChannelsJSON = JSONContainer.NewObject(); foreach (var channel in ChannelModLogChannels) { channelModChannelsJSON.TryAddField(channel.Key.ToString(), channel.Value); } result.TryAddField("ChannelModLogChannels", channelModChannelsJSON); return(result); }
internal async Task <bool> TryLoadBotVars() { string filepath = Resources.GetGuildBotVarSaveFileName(GuildID); if (File.Exists(filepath)) { JSONContainer json = await Resources.LoadJSONFile(filepath); if (json == null) { return(false); } else { lock (savelock) { FromJSON(json); } return(true); } } else { return(false); } }
public bool FromJSON(JSONContainer json) { if (json.TryGetField(JSON_MODTYPE, out uint type) && json.TryGetField(JSON_CHANNELID, out ulong channelId) && json.TryGetField(JSON_ACTORID, out ulong actorid)) { Type = (ChannelModerationType)type; ChannelId = channelId; ActorId = actorid; if (json.TryGetField(JSON_TIMESTAMP, out string timestamp_str)) { if (DateTimeOffset.TryParseExact(timestamp_str, "u", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTimeOffset timestamp)) { Timestamp = timestamp; } else { Timestamp = DateTimeOffset.MinValue; } } json.TryGetField(JSON_CHANNELNAME, out string channelname); ChannelName = channelname; json.TryGetField(JSON_ACTORNAME, out string actorname); ActorName = actorname; json.TryGetField(JSON_INFO, out string info); Info = info; return(true); } return(false); }
public JSONContainer ToJSON() { JSONContainer result = JSONContainer.NewObject(); result.TryAddField(JSON_USERID, UserId); if (BannedUntil.HasValue) { result.TryAddField(JSON_BANNEDUNTIL, BannedUntil.Value.ToString("u")); } if (MutedUntil.HasValue) { result.TryAddField(JSON_MUTEDUNTIL, MutedUntil.Value.ToString("u")); if ((rolesPreMute != null) && rolesPreMute.Count > 0) { JSONContainer rolespremute = JSONContainer.NewArray(); foreach (ulong roleId in rolesPreMute) { rolespremute.Add(roleId); } result.TryAddField(JSON_ROLEIDS, rolespremute); } } if (moderationEntries.Count > 0) { JSONContainer jsonModEntries = JSONContainer.NewArray(); foreach (UserModerationEntry entry in moderationEntries) { jsonModEntries.Add(entry.ToJSON()); } result.TryAddField(JSON_MODENTRIES, jsonModEntries); } return(result); }
internal async Task SafePages(int listLocation = -1) { JSONContainer idSettings = JSONContainer.NewObject(); idSettings.TryAddField(JSON_ID, nextId); await ResourcesModel.WriteJSONObjectToFile(StorageDirectory + ID_SAFEFILE, idSettings); if (listLocation == -1) { foreach (string file in Directory.GetFiles(StorageDirectory)) { if (file.Contains("page-") && file.EndsWith(".json")) { File.Delete(file); } } int pages = (pageStorables.Count - 1) / PAGESIZE; for (int i = 0; i <= pages; i++) { await SafePage(i); } } else { int page = listLocation / PAGESIZE; await SafePage(page); } }
public JSONContainer ToJSON() { JSONContainer result = JSONContainer.NewObject(); result.TryAddField(JSON_QUOTEID, QuoteId); JSONContainer macroList = JSONContainer.NewArray(); foreach (Macro macro in macros.Values) { macroList.Add(macro.ToJSON()); } result.TryAddField(JSON_MACROS, macroList); JSONContainer quoteList = JSONContainer.NewArray(); foreach (Quote quote in quotes.Values) { quoteList.Add(quote.ToJSON()); } result.TryAddField(JSON_QUOTES, quoteList); return(result); }
private EmbedBuilder GetDistanceEmbed(JSONContainer json) { EmbedFooterBuilder footer = new EmbedFooterBuilder() { Text = "EDSM" }; if (json.IsArray) { if (json.Array.Count == 2) { JSONContainer systemAJSON = json.Array[0].Container; JSONContainer systemBJSON = json.Array[1].Container; if (systemAJSON != null && systemBJSON != null) { if (GetSystemInfo(systemAJSON, out SystemA_name, SystemA_name, out uint systemA_id, out string systemA_url, out Vector3 systemA_pos) && GetSystemInfo(systemBJSON, out SystemB_name, SystemB_name, out uint systemB_id, out string systemB_url, out Vector3 systemB_pos)) { float distance = Vector3.Distance(systemA_pos, systemB_pos); return(DistanceEmbed(footer, $"{(systemA_url == null ? SystemA_name : $"[{SystemA_name}]({systemA_url})")} **`<-` `{distance.ToString("### ###.00", CultureInfo.InvariantCulture)} ly` ` ->`** " + $"{(systemB_url == null ? SystemB_name : $"[{SystemB_name}]({systemB_url})")}", false)); } return(DistanceEmbed(footer, "Error " + Macros.GetCodeLocation())); } return(DistanceEmbed(footer, "Error " + Macros.GetCodeLocation())); }
public bool ApplyJSON(JSONContainer json) { macros.Clear(); quotes.Clear(); if (json.TryGetField(JSON_QUOTEID, out QuoteId) && json.TryGetArrayField(JSON_MACROS, out JSONContainer macroList) && json.TryGetArrayField(JSON_QUOTES, out JSONContainer quoteList)) { foreach (JSONField macroField in macroList.Array) { if (macroField.IsObject) { Macro macro = new Macro(); if (macro.ApplyJSON(macroField.Container)) { macros[macro.Identifier] = macro; } } } foreach (JSONField quoteField in quoteList.Array) { if (quoteField.IsObject) { Quote quote = new Quote(); if (quote.ApplyJSON(quoteField.Container)) { quotes[quote.QuoteId] = quote; } } } return(true); } return(false); }
internal async Task <bool> TryLoadBotVars() { string filepath = getFilePath(); if (File.Exists(filepath)) { JSONContainer json = await Resources.LoadJSONFile(filepath); if (json == null) { return(false); } else { lock (savelock) { FromJSON(json); } BotVarManager.InvokeOnGuildBotVarCollectionLoaded(this); return(true); } } else { return(false); } }
internal JSONContainer ToJSON() { JSONContainer result = JSONContainer.NewObject(); result.TryAddField(JSON_ID, Identifier); result.TryAddField(JSON_TYPE, (int)Type); switch (Type) { case BotVarType.UInt64: result.TryAddField(JSON_VALUE, UInt64); break; case BotVarType.Int64: result.TryAddField(JSON_VALUE, Int64); break; case BotVarType.Float64: result.TryAddField(JSON_VALUE, Float64); break; case BotVarType.String: result.TryAddField(JSON_VALUE, String); break; case BotVarType.Bool: result.TryAddField(JSON_VALUE, Bool); break; case BotVarType.Generic: result.TryAddField(JSON_VALUE, Generic); break; } return(result); }
private static void checkAddStringField(string value, JSONContainer json, string identifier) { if (!string.IsNullOrEmpty(value)) { json.TryAddField(identifier, value); } }
private static EmbedFooterBuilder getFooter(JSONContainer footerJSON) { return(new EmbedFooterBuilder() { Text = getLengthCheckedStringField(footerJSON, TEXT, EMBEDFOOTERTEXT_MAX, "The embed footer text may not exceed {0} characters!"), IconUrl = getFormCheckedURLField(footerJSON, ICON_URL, "The url for the embed footer icon is not a well formed url!") }); }
private static string getFormCheckedImageField(JSONContainer json, string identifier, string errorstring) { if (json.TryGetObjectField(identifier, out JSONContainer imageJSON)) { return(getFormCheckedURLField(imageJSON, URL, errorstring)); } return(null); }
public JSONContainer ToJSON() { JSONContainer result = JSONContainer.NewObject(); result.TryAddField(JSON_GUILDID, GuildId); result.TryAddField(JSON_CHANNELID, ChannelId); return(result); }
public bool ApplyJSON(JSONContainer json) { if (json.TryGetField(JSON_RED, out uint red) && json.TryGetField(JSON_GREEN, out uint green) && json.TryGetField(JSON_BLUE, out uint blue)) { C = new Color((byte)red, (byte)green, (byte)blue); return(true); } return(false); }
private static EmbedAuthorBuilder getAuthor(JSONContainer authorJSON) { return(new EmbedAuthorBuilder { Name = getLengthCheckedStringField(authorJSON, NAME, EMBEDAUTHORNAME_MAX, "The embed author name may not exceed {0} characters!"), IconUrl = getFormCheckedURLField(authorJSON, ICON_URL, "The URL for the author icon is not a well formed URL"), Url = getFormCheckedURLField(authorJSON, URL, "The URL for the author link is not a well formed URL") }); }
public JSONContainer ToJSON() { JSONContainer result = JSONContainer.NewObject(); result.TryAddField(JSON_RED, C.R); result.TryAddField(JSON_GREEN, C.G); result.TryAddField(JSON_BLUE, C.B); return(result); }
public JSONContainer ToJSON() { JSONContainer result = JSONContainer.NewObject(); result.TryAddField(JSON_ID, Id); result.TryAddField(JSON_ALLOWCOMMANDS, AllowCommands); result.TryAddField(JSON_ALLOWSHITPOSTING, AllowShitposting); return(result); }
/// <summary> /// Retrieves a generic config variable /// </summary> /// <param name="id">Identifier</param> /// <param name="value">Result</param> /// <returns>True, if either a variable or a default value was found</returns> public bool TryGetBotVar(string id, out JSONContainer value) { if (!BotVars.TryGetValue(id, out BotVar var)) { BotVarDefaults.TryGetValue(id, out var); } value = var.Generic; return(var.Type == BotVarType.Generic); }
public JSONContainer ToJSON() { JSONContainer result = JSONContainer.NewArray(); foreach (ulong val in hashset) { result.Add(val); } return(result); }
private static JSONContainer getFooterJSON(IEmbed embed) { EmbedFooter footer = embed.Footer.Value; JSONContainer footerJSON = JSONContainer.NewObject(); checkAddStringField(footer.Text, footerJSON, TEXT); checkAddStringField(footer.IconUrl, footerJSON, ICON_URL); return(footerJSON); }
internal async Task SafePage(int page) { JSONContainer entryList = JSONContainer.NewArray(); for (int i = page * PAGESIZE; i < pageStorables.Count && i < (page + 1) * PAGESIZE; i++) { entryList.Add(pageStorables[i].ToJSON()); } await ResourcesModel.WriteJSONObjectToFile(string.Format("{0}page-{1}.json", StorageDirectory, page), entryList); }
public bool FromJSON(JSONContainer json) { if (json.TryGetField(JSON_ID, out Id)) { json.TryGetField(JSON_ALLOWCOMMANDS, out AllowCommands, DEFAULT_ALLOWCOMMANDS); json.TryGetField(JSON_ALLOWSHITPOSTING, out AllowShitposting, DEFAULT_ALLOWSHITPOSTING); return(true); } return(false); }