private async Task SendNotification(TimerItem timer, ulong channel) { try { var remains = timer.GetRemains(); var stage = timer.GetStageName(); var mode = timer.GetModeName(); var embed = new EmbedBuilder() .WithTitle(LM.Get("timerNotifyTitle", string.IsNullOrEmpty(timer.timerLocation) ? "-" : timer.timerLocation)) .AddField(LM.Get("timersType"), string.IsNullOrEmpty(mode) ? "-" : mode, true) .AddField(LM.Get("timersStage"), string.IsNullOrEmpty(stage) ? "-" : stage, true) .AddField(LM.Get("timersOwner"), string.IsNullOrEmpty(timer.timerOwner) ? "-" : timer.timerOwner, true) .AddField(LM.Get("timersRemaining"), string.IsNullOrEmpty(remains) ? "-" : remains, true) .AddField(LM.Get("timersNotes"), string.IsNullOrEmpty(timer.timerNotes) ? "-" : timer.timerNotes); if (!string.IsNullOrEmpty(Settings.Resources.ImgTimerAlert)) { embed.WithThumbnailUrl(Settings.Resources.ImgTimerAlert); } var ch = APIHelper.DiscordAPI.GetChannel(channel); if (ch == null) { await LogHelper.LogWarning($"Discord channel {channel} not found!", Category); } else { await APIHelper.DiscordAPI.SendMessageAsync(ch, Settings.TimersModule.DefaultMention ?? " ", embed.Build()).ConfigureAwait(false); } } catch (Exception ex) { await LogHelper.LogEx(ex.Message, ex, Category); } }
public async Task AuthNotify() { var channels = APIHelper.DiscordAPI.GetAuthAllowedChannels(); if (channels.Length != 0 && !channels.Contains(Context.Channel.Id)) { return; } if (SettingsManager.GetBool("config", "moduleWebServer") && SettingsManager.GetBool("config", "moduleNotificationFeed")) { try { await APIHelper.DiscordAPI.ReplyMessageAsync(Context, string.Format(LM.Get("authNotifyInvite"), WebServerModule.GetAuthNotifyURL()), true); } catch (Exception ex) { await LogHelper.LogEx("authnotify", ex); await Task.FromException(ex); } } else { await APIHelper.DiscordAPI.ReplyMessageAsync(Context, LM.Get("authDisabled"), true); } }
public async Task Auth() { var channels = APIHelper.DiscordAPI.GetAuthAllowedChannels(); if (channels.Length != 0 && !channels.Contains(Context.Channel.Id)) { return; } if (SettingsManager.GetBool("config", "moduleWebServer") && SettingsManager.GetBool("config", "moduleAuthWeb")) { try { await APIHelper.DiscordAPI.ReplyMessageAsync(Context, string.Format(LM.Get("authInvite"), $"http://{SettingsManager.Get("webServerModule", "webExternalIP")}:{SettingsManager.Get("webServerModule", "webExternalPort")}/auth.php"), true); } catch (Exception ex) { await LogHelper.LogEx("auth", ex); await Task.FromException(ex); } } else { await APIHelper.DiscordAPI.ReplyMessageAsync(Context, LM.Get("authDisabled"), true); } }
public async Task <List <WebMailHeader> > WebGetMailHeaders(long id, string token) { var mailHeaders = (await APIHelper.ESIAPI.GetMailHeaders(Reason, id, token, 0, null))?.Result; if (mailHeaders == null) { return(null); } var list = new List <WebMailHeader>(); foreach (var h in mailHeaders) { var from = await APIHelper.ESIAPI.GetCharacterData(Reason, h.@from); var rcp = await MailModule.GetRecepientNames(Reason, h.recipients, id, token); list.Add(new WebMailHeader { MailId = h.mail_id, FromName = from?.name ?? LM.Get("Unknown"), ToName = rcp.Length > 0 ? rcp : LM.Get("Unknown"), Subject = h.subject, Date = h.Date }); } return(list); }
public async Task <string> IsAdminAccess(ICommandContext context) { if (context.Guild != null) { var roles = new List <IRole>(context.Guild.Roles); var userRoleIDs = (await context.Guild.GetUserAsync(context.User.Id)).RoleIds; var roleMatch = SettingsManager.GetSubList("config", "discordAdminRoles"); if ((from role in roleMatch select roles.FirstOrDefault(x => x.Name == role.Value) into tmp where tmp != null select userRoleIDs.FirstOrDefault(x => x == tmp.Id)) .All(check => check == 0)) { return(LM.Get("comRequirePriv")); } } else { var guild = (await context.Client.GetGuildsAsync()).FirstOrDefault(); if (guild == null) { return("Error getting guild!"); } var roles = new List <IRole>(guild.Roles); var userRoleIDs = (await guild.GetUserAsync(context.User.Id)).RoleIds; var roleMatch = SettingsManager.GetSubList("config", "discordAdminRoles"); if ((from role in roleMatch select roles.FirstOrDefault(x => x.Name == role.Value) into tmp where tmp != null select userRoleIDs.FirstOrDefault(x => x == tmp.Id)) .All(check => check == 0)) { return(LM.Get("comRequirePriv")); } } await Task.CompletedTask; return(null); }
private async Task SendNotification(TimerItem timer, ulong channel) { try { var remains = timer.GetRemains(); var stage = timer.GetStageName(); var mode = timer.GetModeName(); var embed = new EmbedBuilder() .WithTitle(LM.Get("timerNotifyTitle", string.IsNullOrEmpty(timer.timerLocation) ? "-" : timer.timerLocation)) .AddInlineField(LM.Get("timersType"), string.IsNullOrEmpty(mode) ? "-" : mode) .AddInlineField(LM.Get("timersStage"), string.IsNullOrEmpty(stage) ? "-" : stage) .AddInlineField(LM.Get("timersOwner"), string.IsNullOrEmpty(timer.timerOwner) ? "-" : timer.timerOwner) .AddInlineField(LM.Get("timersRemaining"), string.IsNullOrEmpty(remains) ? "-" : remains) .AddField(LM.Get("timersNotes"), string.IsNullOrEmpty(timer.timerNotes) ? "-" : timer.timerNotes); if (!string.IsNullOrEmpty(Settings.Resources.ImgTimerAlert)) { embed.WithThumbnailUrl(Settings.Resources.ImgTimerAlert); } await APIHelper.DiscordAPI.SendMessageAsync(APIHelper.DiscordAPI.GetChannel(channel), "@everyone", embed.Build()).ConfigureAwait(false); } catch (Exception ex) { await LogHelper.LogEx(ex.Message, ex, Category); } }
private static async Task Event_UserJoined(SocketGuildUser arg) { await AsyncHelper.RedirectToThreadPool(); try { if (SettingsManager.Settings.Config.WelcomeMessage) { var channel = SettingsManager.Settings.Config.WelcomeMessageChannelId == 0 ? arg.Guild.DefaultChannel : arg.Guild.GetTextChannel(SettingsManager.Settings.Config.WelcomeMessageChannelId); var authurl = WebServerModule.GetAuthPageUrl(); if (!string.IsNullOrWhiteSpace(authurl)) { await APIHelper.DiscordAPI.SendMessageAsync(channel, LM.Get("welcomeMessage", arg.Mention, authurl, SettingsManager.Settings.Config.BotDiscordCommandPrefix)); } else { await APIHelper.DiscordAPI.SendMessageAsync(channel, LM.Get("welcomeAuth", arg.Mention)); } } } catch (Exception ex) { await LogHelper.LogEx(nameof(Event_UserJoined), ex, LogCat.Discord); } }
public async Task Pc([Remainder] string x) { var forbidden = APIHelper.DiscordAPI.GetConfigForbiddenPublicChannels(); if (forbidden.Any() && forbidden.Contains(Context.Channel.Id)) { return; } if (SettingsManager.GetBool("config", "modulePriceCheck")) { var forbiddenChannels = APIHelper.DiscordAPI.GetConfigForbiddenPublicChannels(); if (x == null) { await APIHelper.DiscordAPI.ReplyMessageAsync(Context, LM.Get("enterItemName"), true); } else if (forbiddenChannels.Contains(Context.Channel.Id)) { await ReplyAsync(LM.Get("commandToPrivate")); } else { await PriceCheckModule.Check(Context, x, ""); } } }
public async Task SendEmbedKillMessage(ulong channelId, Color color, int shipID, int kmId, string shipName, long value, string sysName, string secstatus, string killTime, string cName, string corpName , string aTicker, bool isNpcKill, string atName, string atCorp, string atTicker, int atCount, string radiusMessage, string msg = "") { msg = msg ?? ""; var killString = string.Format(LM.Get("killFeedString"), !string.IsNullOrEmpty(radiusMessage) ? "R " : null, shipName, value, cName, corpName, string.IsNullOrEmpty(aTicker) ? null : aTicker, sysName, secstatus, killTime); var killedBy = isNpcKill ? null : string.Format(LM.Get("killFeedBy"), atName, atCorp, string.IsNullOrEmpty(atTicker) ? null : atTicker, atCount); var builder = new EmbedBuilder() .WithColor(color) .WithThumbnailUrl($"https://image.eveonline.com/Type/{shipID}_32.png") .WithAuthor(author => { author.WithName($"{killString} {killedBy}") .WithUrl($"https://zkillboard.com/kill/{kmId}/"); if (isNpcKill) { author.WithIconUrl("http://www.panthernet.org/uf/npc2.jpg"); } }); if (!string.IsNullOrEmpty(radiusMessage)) { builder.AddInlineField(LM.Get("radiusInfoHeader"), radiusMessage); } var embed = builder.Build(); var channel = GetGuild()?.GetTextChannel(channelId); if (channel != null) { await SendMessageAsync(channel, msg, embed).ConfigureAwait(false); } }
private async Task NotifyNullsecCampaign(JsonClasses.NullCampaignItem campaign, string message, string region, string system, string defender, NullCampaignGroup @group, uint color) { try { var embed = new EmbedBuilder() .WithTitle(message) .AddInlineField(LM.Get("NC_StartTime"), LM.Get("NC_StartTimeText", $"{campaign.Time.ToString(Settings.Config.ShortTimeFormat)} ET", (campaign.Time - DateTimeOffset.UtcNow).ToFormattedString())) .AddInlineField(LM.Get("NC_type"), campaign.event_type == "ihub_defense" ? "IHUB" : "TCU") .AddInlineField(LM.Get("NC_Score"), LM.Get("NC_ScoreText", campaign.attackers_score.ToPercent(), campaign.defender_score.ToPercent())) //"Attacker {0} vs Defender {1}" .AddInlineField(LM.Get("NC_Location"), LM.Get("NC_LocationText", region, system)) // "{0} / {1}" .AddInlineField(LM.Get("NC_Defender"), defender) .WithTimestamp(campaign.Time) .WithColor(color); if (!string.IsNullOrEmpty(Settings.Resources.ImgEntosisAlert)) { embed.WithThumbnailUrl(Settings.Resources.ImgEntosisAlert); } var mention = group.Mentions.Any() ? string.Join(", ", group.Mentions) : group.DefaultMention; await APIHelper.DiscordAPI.SendMessageAsync(APIHelper.DiscordAPI.GetChannel(group.DiscordChannelId), mention, embed.Build()).ConfigureAwait(false); } catch (Exception ex) { await LogHelper.LogEx(ex.Message, ex, Category); } }
internal static string Get404Page() { return(File.ReadAllText(SettingsManager.FileTemplateAuth3).Replace("{message}", "404 Not Found!") .Replace("{headerContent}", GetHtmlResourceDefault(false)) .Replace("{header}", LM.Get("authTemplateHeader")) .Replace("{body}", LM.Get("WebRequestUnexpected")) .Replace("{backText}", LM.Get("backText"))); }
private async Task <bool> OnAuthRequest(HttpListenerRequestEventArgs context) { var request = context.Request; var response = context.Response; try { var extPort = SettingsManager.Get("webServerModule", "webExternalPort"); var port = SettingsManager.Get("webServerModule", "webListenPort"); if (request.HttpMethod == HttpMethod.Get.ToString()) { if (request.Url.LocalPath == "/callback.php" || request.Url.LocalPath == $"{extPort}/callback.php" || request.Url.LocalPath == $"{port}/callback.php") { var clientID = SettingsManager.Get("auth", "ccpAppClientId"); var secret = SettingsManager.Get("auth", "ccpAppSecret"); var prms = request.Url.Query.TrimStart('?').Split('&'); var code = prms[0].Split('=')[1]; var state = prms.Length > 1 ? prms[1].Split('=')[1] : null; if (state != "12") { return(false); } //state = 12 && have code var result = await WebAuthModule.GetCHaracterIdFromCode(code, clientID, secret); if (result == null) { //TODO invalid auth await response.RedirectAsync(new Uri(WebServerModule.GetWebSiteUrl())); return(true); } await SQLHelper.SQLiteDataInsertOrUpdateTokens("", result[0], result[1]); response.Headers.ContentEncoding.Add("utf-8"); response.Headers.ContentType.Add("text/html;charset=utf-8"); await response.WriteContentAsync(File.ReadAllText(SettingsManager.FileTemplateMailAuthSuccess) .Replace("{header}", "authTemplateHeader") .Replace("{body}", LM.Get("mailAuthSuccessHeader")) .Replace("{body2}", LM.Get("mailAuthSuccessBody")) ); return(true); } } } catch (Exception ex) { await LogHelper.LogEx(ex.Message, ex, Category); } return(false); }
private static async Task GoMarketeer(HttpClient httpClient, ICommandContext context, string system, JsonClasses.SearchInventoryType itemIDResults, JsonClasses.SearchName itemNameResults) { var url = "https://api.evemarketer.com/ec"; var systemAddon = string.Empty; var systemTextAddon = string.IsNullOrEmpty(system) ? null : $"{LM.Get("fromSmall")} {system}"; switch (system?.ToLower()) { case "jita": systemAddon = "&usesystem=30000142"; break; case "amarr": systemAddon = "&usesystem=30002187"; break; case "rens": systemAddon = "&usesystem=30002510"; break; case "dodixie": systemAddon = "&usesystem=30002659"; break; } httpClient.DefaultRequestHeaders.Clear(); httpClient.DefaultRequestHeaders.Add("User-Agent", SettingsManager.DefaultUserAgent); var webReply = await httpClient.GetStringAsync($"{url}/marketstat/json?typeid={itemIDResults.inventory_type[0]}{systemAddon}"); var marketReply = JsonConvert.DeserializeObject <List <JsonEveCentral.Items> >(webReply)[0]; await LogHelper.LogInfo($"Sending {context.Message.Author}'s Price check", LogCat.PriceCheck); var builder = new EmbedBuilder() .WithColor(new Color(0x00D000)) .WithThumbnailUrl($"https://image.eveonline.com/Type/{itemNameResults.id}_64.png") .WithAuthor(author => { author .WithName($"{LM.Get("Item")}: {itemNameResults.name}") .WithUrl($"https://www.fuzzwork.co.uk/info/?typeid={itemNameResults.id}/"); }) .WithDescription($"{LM.Get("Prices")} {systemTextAddon}") .AddField(LM.Get("Buy"), $"{LM.Get("marketLow")}: {marketReply.buy.min:N2}{Environment.NewLine}" + $"{LM.Get("marketMid")}: {marketReply.buy.avg:N2}{Environment.NewLine}" + $"{LM.Get("marketHigh")}: {marketReply.buy.max:N2}", true) .AddField(LM.Get("Sell"), $"{LM.Get("marketLow")}: {marketReply.sell.min:N2}{Environment.NewLine}" + $"{LM.Get("marketMid")}: {marketReply.sell.avg:N2}{Environment.NewLine}" + $"{LM.Get("marketHigh")}: {marketReply.sell.max:N2}", true) .AddField(LM.Get("Extra"), "\u200b") .AddField(LM.Get("Buy"), $"5%: {marketReply.buy.fivePercent:N2}{Environment.NewLine}" + $"{LM.Get("Volume")}: {marketReply.buy.volume}", true) .AddField(LM.Get("Sell"), $"5%: {marketReply.sell.fivePercent:N2}{Environment.NewLine}" + $"{LM.Get("Volume")}: {marketReply.sell.volume:N0}", true); var embed = builder.Build(); await APIHelper.DiscordAPI.ReplyMessageAsync(context, "", embed).ConfigureAwait(false); }
internal async Task SendEmbedKillMessage(List <ulong> channelIds, Color color, KillDataEntry km, string radiusMessage, string msg = "") { msg = msg ?? ""; var victimName = $"{LM.Get("killFeedName", $"[{km.rVictimCharacter?.name}]({GetKillMailLink(km.victimCharacterID, KillMailLinkTypes.character)})")}"; var victimCorp = $"{LM.Get("killFeedCorp", $"[{km.rVictimCorp?.name}]({GetKillMailLink(km.victimCorpID, KillMailLinkTypes.corporation)})")}"; var victimAlliance = km.rVictimAlliance == null ? "" : $"{LM.Get("killFeedAlliance", $"[{km.rVictimAlliance?.name}]")}({GetKillMailLink(km.victimAllianceID, KillMailLinkTypes.alliance)})"; var victimShip = $"{LM.Get("killFeedShip", $"[{km.rVictimShipType?.name}]({GetKillMailLink(km.victimShipID, KillMailLinkTypes.ship)})")}"; string[] victimStringArray = new string[] { victimName, victimCorp, victimAlliance, victimShip }; var attackerName = $"{LM.Get("killFeedName", $"[{km.rAttackerCharacter?.name}]({GetKillMailLink(km.finalBlowAttackerCharacterId, KillMailLinkTypes.character)})")}"; var attackerCorp = $"{LM.Get("killFeedCorp", $"[{km.rAttackerCorp?.name}]({GetKillMailLink(km.finalBlowAttackerCorpId, KillMailLinkTypes.corporation)})")}"; var attackerAlliance = km.rAttackerAlliance == null || km.finalBlowAttackerAllyId == 0 ? null : $"{LM.Get("killFeedAlliance", $"[{km.rAttackerAlliance?.name}]({GetKillMailLink(km.finalBlowAttackerAllyId, KillMailLinkTypes.alliance)})")}"; var attackerShip = $"{LM.Get("killFeedShip", $"[{km.rAttackerShipType?.name}]({GetKillMailLink(km.attackerShipID, KillMailLinkTypes.ship)})")}"; string[] attackerStringArray = new string[] { attackerName, attackerCorp, attackerAlliance, attackerShip }; var killFeedDetails = LM.Get("killFeedDetails", km.killTime, km.value.ToString("#,##0 ISk")); var killFeedDetailsSystem = LM.Get("killFeedDetailsSystem", $"[{km.sysName}]({GetKillMailLink(km.systemId, KillMailLinkTypes.system)})"); string[] detailsStringArray = new string[] { killFeedDetails, killFeedDetailsSystem }; var builder = new EmbedBuilder() .WithColor(color) .WithThumbnailUrl($"https://image.eveonline.com/Type/{km.victimShipID}_64.png") .WithAuthor(author => { author.WithName(LM.Get("killFeedHeader", km.rVictimShipType?.name, km.rSystem?.name)) .WithUrl($"https://zkillboard.com/kill/{km.killmailID}/"); if (km.isNPCKill) { author.WithIconUrl("http://www.panthernet.org/uf/npc2.jpg"); } }) .AddField(LM.Get("Victim"), string.Join("\n", victimStringArray.Where(c => !string.IsNullOrWhiteSpace(c)))) .AddField(LM.Get("Finalblow"), string.Join("\n", attackerStringArray.Where(c => !string.IsNullOrWhiteSpace(c)))) .AddField(LM.Get("Details"), string.Join("\n", detailsStringArray.Where(c => !string.IsNullOrWhiteSpace(c)))); if (!string.IsNullOrEmpty(radiusMessage)) { builder.AddField(LM.Get("radiusInfoHeader"), radiusMessage); } var embed = builder.Build(); foreach (var id in channelIds) { var channel = GetGuild()?.GetTextChannel(id); if (channel != null) { await SendMessageAsync(channel, msg, embed).ConfigureAwait(false); } } }
private async Task <string> GenerateCorpHistory(long charId) { var history = (await APIHelper.ESIAPI.GetCharCorpHistory(Reason, charId))?.OrderByDescending(a => a.record_id).ToList(); if (history == null || history.Count == 0) { return(null); } JsonClasses.CorporationHistoryEntry last = null; foreach (var entry in history) { var corp = await APIHelper.ESIAPI.GetCorporationData(Reason, entry.corporation_id); entry.CorpName = corp.name; entry.IsNpcCorp = corp.creator_id == 1; if (last != null) { entry.Days = (int)(last.Date - entry.Date).TotalDays; } entry.CorpTicker = corp.ticker; last = entry; } var l = history.FirstOrDefault(); if (l != null) { l.Days = (int)(DateTime.UtcNow - l.Date).TotalDays; } var sb = new StringBuilder(); sb.AppendLine("<thead>"); sb.AppendLine("<tr>"); sb.AppendLine($"<th scope=\"col-md-auto\">#</th>"); sb.AppendLine($"<th scope=\"col-md-auto\">{LM.Get("hrmCVCorpName")}</th>"); sb.AppendLine($"<th scope=\"col-md-auto\">{LM.Get("hrmCVJoined")}</th>"); sb.AppendLine($"<th scope=\"col\">{LM.Get("hrmCVDays")}</th>"); sb.AppendLine("</tr>"); sb.AppendLine("</thead>"); sb.AppendLine("<tbody>"); var counter = 1; foreach (var entry in history) { sb.AppendLine("<tr>"); sb.AppendLine($" <th scope=\"row\">{counter++}</th>"); sb.AppendLine($" <td><a href=\"https://zkillboard.com/corporation/{entry.corporation_id}\">{entry.CorpName}</a> [{entry.CorpTicker}]{(entry.IsNpcCorp ? " (npc)" : null)}{(entry.is_deleted ? " (closed)" : null)}</td>"); sb.AppendLine($" <td>{entry.Date.ToShortDateString()}</td>"); sb.AppendLine($" <td>{entry.Days}</td>"); sb.AppendLine("</tr>"); } sb.AppendLine("</tbody>"); return(sb.ToString()); }
public static string GetAccessDeniedPage(string header, string message, string description = null) { return(File.ReadAllText(SettingsManager.FileTemplateAuth3) .Replace("{message}", message) .Replace("{header}", header) .Replace("{header2}", header) .Replace("{description}", description) .Replace("{backText}", LM.Get("backText"))); }
private async Task <string> GenerateContractsHtml(string token, int inspectCharId, int page) { var items = await APIHelper.ESIAPI.GetCharacterContracts(Reason, inspectCharId, token); var startIndex = (page - 1) * Settings.HRMModule.TableEntriesPerPage; items = items.GetRange(startIndex, items.Count > startIndex + Settings.HRMModule.TableEntriesPerPage ? Settings.HRMModule.TableEntriesPerPage : (items.Count - startIndex)); var sb = new StringBuilder(); sb.AppendLine("<thead>"); sb.AppendLine("<tr>"); sb.AppendLine($"<th scope=\"col-md-auto\">#</th>"); sb.AppendLine($"<th scope=\"col-md-auto\">{LM.Get("hrmContractName")}</th>"); sb.AppendLine($"<th scope=\"col-md-auto\">{LM.Get("hrmContractType")}</th>"); sb.AppendLine($"<th scope=\"col-md-auto\">{LM.Get("hrmContractFrom")}</th>"); sb.AppendLine($"<th scope=\"col-md-auto\">{LM.Get("hrmContractTo")}</th>"); sb.AppendLine($"<th scope=\"col-md-auto\">{LM.Get("hrmContractStatus")}</th>"); sb.AppendLine($"<th scope=\"col-md-auto\">{LM.Get("hrmContractDate")}</th>"); sb.AppendLine($"<th scope=\"col-md-auto\">{LM.Get("hrmContractInfo")}</th>"); sb.AppendLine("</tr>"); sb.AppendLine("</thead>"); sb.AppendLine("<tbody>"); var counter = startIndex + 1; foreach (var entry in items) { try { var fromPlace = entry.issuer_id != 0 ? "character" : "corporation"; var toPlace = !entry.for_corporation ? "character" : "corporation"; var fromId = entry.issuer_id != 0 ? entry.issuer_id : entry.issuer_corporation_id; var toId = entry.acceptor_id; var from = entry.issuer_id != 0 ? (await APIHelper.ESIAPI.GetCharacterData(Reason, entry.issuer_id))?.name : (await APIHelper.ESIAPI.GetCorporationData(Reason, entry.issuer_corporation_id))?.name; var to = entry.for_corporation ? (await APIHelper.ESIAPI.GetCorporationData(Reason, entry.acceptor_id))?.name : (await APIHelper.ESIAPI.GetCharacterData(Reason, entry.acceptor_id))?.name; sb.AppendLine($"<tr>"); sb.AppendLine($" <th scope=\"row\">{counter++}</th>"); sb.AppendLine($" <td>Contract</td>"); sb.AppendLine($" <td>{entry.type}</td>"); sb.AppendLine($" <td><a href=\"https://zkillboard.com/{fromPlace}/{fromId}/\">{from}</a></td>"); sb.AppendLine($" <td><a href=\"https://zkillboard.com/{toPlace}/{toId}/\">{to}</a></td>"); sb.AppendLine($" <td>{entry.status}</td>"); sb.AppendLine($" <td>{entry.DateCompleted?.ToString(Settings.Config.ShortTimeFormat) ?? LM.Get("hrmContractInProgress")}</td>"); sb.AppendLine($" <td>{entry.title}</td>"); sb.AppendLine("</tr>"); } catch (Exception ex) { await LogHelper.LogEx("", ex, Category); } } sb.AppendLine("</tbody>"); return(sb.ToString()); }
public async Task TimersCommand() { if (!SettingsManager.Settings.Config.ModuleTimers) { await APIHelper.DiscordAPI.ReplyMessageAsync(Context, LM.Get("timersModuleDisabled"), true); return; } if (!await APIHelper.DiscordAPI.IsBotPrivateChannel(Context.Channel)) { await APIHelper.DiscordAPI.ReplyMessageAsync(Context, LM.Get("onyBotPrivateCommand"), true); return; } if (await APIHelper.DiscordAPI.IsAdminAccess(Context) == null) { var timers = await TimersModule.GetUpcomingTimersString(); await APIHelper.DiscordAPI.ReplyMessageAsync(Context, $"```\n{timers}\n```", true); return; } var allys = SettingsManager.Settings.TimersModule.AccessList.Values.Where(a => a.IsAlliance && a.Id > 0).Select(a => a.Id); var corps = SettingsManager.Settings.TimersModule.AccessList.Values.Where(a => a.IsCorporation && a.Id > 0).Select(a => a.Id); var chars = SettingsManager.Settings.TimersModule.AccessList.Values.Where(a => a.IsCharacter && a.Id > 0).Select(a => a.Id); var skip = !allys.Any() && !corps.Any() && !chars.Any(); var dataList = (await SQLHelper.GetAuthUser(Context.User.Id))?.FirstOrDefault(); if (skip || (dataList != null && dataList.Count > 0 && dataList.ContainsKey("characterID"))) { var chId = Convert.ToInt64(dataList["characterID"]); var ch = await APIHelper.ESIAPI.GetCharacterData("Discord", chId, true); if (skip || ch != null) { if (!skip && (!ch.alliance_id.HasValue || !allys.Contains(ch.alliance_id.Value) && !corps.Contains(ch.corporation_id) && !chars.Contains((int)chId))) { await APIHelper.DiscordAPI.ReplyMessageAsync(Context, LM.Get("timersCmdAccessDenied"), true); return; } var timers = await TimersModule.GetUpcomingTimersString(); await APIHelper.DiscordAPI.ReplyMessageAsync(Context, $"```\n{timers}\n```", true); return; } } await APIHelper.DiscordAPI.ReplyMessageAsync(Context, LM.Get("timersCmdAccessDenied"), true); }
public override async Task Initialize() { await WebPartInitialization(); //check entities foreach (var(groupName, group) in Settings.WebAuthModule.AuthGroups) { var keys = group.AllowedMembers.GetDupeKeys(); if (keys.Any()) { await LogHelper.LogWarning( $"Group {groupName} contains duplicate `AllowedMembers` names {string.Join(',', keys)}! Set unique names to avoid inconsistency during auth checks!", Category); } await APIHelper.DiscordAPI.CheckAndNotifyBadDiscordRoles(group.AllowedMembers.Values.SelectMany(a => a.DiscordRoles).Distinct().ToList(), Category); await APIHelper.DiscordAPI.CheckAndNotifyBadDiscordRoles(group.ManualAssignmentRoles, Category); await APIHelper.DiscordAPI.CheckAndNotifyBadDiscordRoles(group.AuthRoles, Category); if (group.StandingsAuth != null) { await APIHelper.DiscordAPI.CheckAndNotifyBadDiscordRoles(group.StandingsAuth.StandingFilters.Values.SelectMany(a => a.DiscordRoles).Distinct().ToList(), Category); } } lock (UpdateLock) ParsedMembersLists.Clear(); //parse data foreach (var(key, value) in Settings.WebAuthModule.GetEnabledAuthGroups()) { var aGroupDic = new Dictionary <string, Dictionary <string, List <long> > >(); foreach (var(fKey, fValue) in value.AllowedMembers) { var aData = await ParseMemberDataArray(fValue.Entities .Where(a => (a is long i && i != 0) || (a is string s && s != string.Empty)).ToList()); aGroupDic.Add(fKey, aData); } lock (UpdateLock) ParsedMembersLists.Add(key, aGroupDic); } //we can't proceed if there was unresolved entities as this will lead to role stripping failures if (IsEntityInitFailed) { await LogHelper.LogError("WebAuth module has been suspended due to errors in resolving specified char/corp/alliance entities! Please actualize auth config or restart the bot if this is an ESI issue.", Category); if (Settings.WebAuthModule.AuthReportChannel > 0) { await APIHelper.DiscordAPI.SendMessageAsync(Settings.WebAuthModule.AuthReportChannel, LM.Get("initialEntityParseError")); } } }
public static async Task Stats(ICommandContext context, string commandText) { if (!SettingsManager.Settings.Config.ModuleStats) { return; } try { var comms = commandText.Split(' ').ToList(); var isSingle = comms.Count == 1; var command = string.IsNullOrEmpty(commandText) ? "t" : comms[0].ToLower(); var isNewDay = command.Equals("newday", stringComparison); if (!isNewDay && !SettingsManager.Settings.StatsModule.EnableStatsCommand) { return; } string entity = null; if (!isSingle) { comms.RemoveAt(0); entity = string.Join(' ', comms); } if (isNewDay) { foreach (var group in SettingsManager.Settings.StatsModule.DailyStatsGroups.Where(a => !a.Value.IncludeInRating)) { await ProcessStats(context, command, entity, group.Value); } var groups = SettingsManager.Settings.StatsModule.DailyStatsGroups.Values.Where(a => a.IncludeInRating); if (groups.Any()) { await ProcessStats(context, command, entity, null); } } else { if (command != "d" && command != "t" && command != "today" && command != "y" && command != "year" && command != "m" && command != "month" && command != "w" && command != "week" && command != "lastweek" && command != "lw" && command != "lastday" && command != "ld" && !command.All(char.IsDigit) && !command.Contains('/') && command != "r" && command != "rating") { await APIHelper.DiscordAPI.ReplyMessageAsync(context, LM.Get("statUnknownCommandSyntax", SettingsManager.Settings.Config.BotDiscordCommandPrefix)); return; } await ProcessStats(context, command, entity, null); } } catch (Exception ex) { await LogHelper.LogEx(ex.Message, ex, LogCat.Stats); } }
public string GetRemains(bool addWord = false) { if (!Date.HasValue) { return(null); } var dif = (Date.Value - DateTime.UtcNow); return($"{(addWord ? $"{LM.Get("Remains")} " : null)}{LM.Get("timerRemains", dif.Days, dif.Hours, dif.Minutes)}"); }
public async Task TimersUrl() { if (SettingsManager.Settings.Config.ModuleTimers) { await APIHelper.DiscordAPI.ReplyMessageAsync(Context, LM.Get("timersUrlText", string.IsNullOrEmpty(SettingsManager.Settings.TimersModule.TinyUrl) ? WebServerModule.GetTimersAuthURL() : SettingsManager.Settings.TimersModule.TinyUrl), true); } else { await APIHelper.DiscordAPI.ReplyMessageAsync(Context, LM.Get("timersModuleDisabled"), true); } }
private async Task <string> GenerateTransactionsHtml(string token, long inspectCharId, int page) { var items = await APIHelper.ESIAPI.GetCharacterWalletTransactions(Reason, inspectCharId, token); //var totalCount = mailHeaders.Count; var startIndex = (page - 1) * Settings.HRMModule.TableEntriesPerPage; items = items.Count == 0 ? items : items.GetRange(startIndex, items.Count > startIndex + Settings.HRMModule.TableEntriesPerPage ? Settings.HRMModule.TableEntriesPerPage : (items.Count - startIndex)); var sb = new StringBuilder(); sb.AppendLine("<thead>"); sb.AppendLine("<tr>"); sb.AppendLine($"<th scope=\"col-md-auto\">#</th>"); sb.AppendLine($"<th scope=\"col-md-auto\">{LM.Get("hrmTransDateHeader")}</th>"); sb.AppendLine($"<th scope=\"col-md-auto\">{LM.Get("hrmTransTypeHeader")}</th>"); sb.AppendLine($"<th scope=\"col-md-auto\">{LM.Get("hrmTransCreditHeader")}</th>"); sb.AppendLine($"<th scope=\"col-md-auto\">{LM.Get("hrmTransClientHeader")}</th>"); sb.AppendLine($"<th scope=\"col-md-auto\">{LM.Get("hrmTransWhereHeader")}</th>"); sb.AppendLine("</tr>"); sb.AppendLine("</thead>"); sb.AppendLine("<tbody>"); var counter = startIndex + 1; foreach (var entry in items) { try { var fromChar = await APIHelper.ESIAPI.GetCharacterData(Reason, entry.client_id); var from = fromChar?.name ?? (await APIHelper.ESIAPI.GetCorporationData(Reason, entry.client_id))?.name; var urlSection = fromChar == null ? "corporation" : "character"; var bgClass = entry.is_buy ? "bgNegativeSum" : "bgPositiveSum"; var foreColor = entry.is_buy ? "fgNegativeSum" : "fgPositiveSum"; var type = await APIHelper.ESIAPI.GetTypeId(Reason, entry.type_id); var amount = entry.quantity * entry.unit_price * (entry.is_buy ? -1 : 1); sb.AppendLine($"<tr>"); sb.AppendLine($" <th scope=\"row\">{counter++}</th>"); sb.AppendLine($" <td>{entry.DateEntry.ToString(Settings.Config.ShortTimeFormat)}</td>"); sb.AppendLine($" <td>{type?.name}</td>"); sb.AppendLine($" <td class=\"{bgClass}\"><font class=\"{foreColor}\">{amount:N}</font></td>"); sb.AppendLine($" <td><a href=\"https://zkillboard.com/{urlSection}/{entry.client_id}/\">{from}</a></td>"); sb.AppendLine($" <td>{entry.location_id}</td>"); sb.AppendLine("</tr>"); } catch (Exception ex) { await LogHelper.LogEx("", ex, Category); } } sb.AppendLine("</tbody>"); return(sb.ToString()); }
public async Task <string> IsAdminAccess(ICommandContext context) { if (!IsAvailable) { return(null); } if (!await Throttle()) { return(null); } try { if (context.Guild != null) { var roles = new List <IRole>(context.Guild.Roles); var userRoleIDs = (await context.Guild.GetUserAsync(context.User.Id)).RoleIds; var roleMatch = SettingsManager.Settings.Config.DiscordAdminRoles; if ((from role in roleMatch select roles.FirstOrDefault(x => x.Name == role) into tmp where tmp != null select userRoleIDs.FirstOrDefault(x => x == tmp.Id)) .All(check => check == 0)) { return(LM.Get("comRequirePriv")); } } else { var guild = (await context.Client.GetGuildsAsync()).FirstOrDefault(); if (guild == null) { return("Error getting guild!"); } var roles = new List <IRole>(guild.Roles); var userRoleIDs = (await guild.GetUserAsync(context.User.Id)).RoleIds; var roleMatch = SettingsManager.Settings.Config.DiscordAdminRoles; if ((from role in roleMatch select roles.FirstOrDefault(x => x.Name.Equals(role, StringComparison.OrdinalIgnoreCase)) into tmp where tmp != null select userRoleIDs.FirstOrDefault(x => x == tmp.Id)) .All(check => check == 0)) { return(LM.Get("comRequirePriv")); } } await Task.CompletedTask; return(null); } catch (Exception ex) { await LogHelper.LogEx(nameof(IsAdminAccess), ex, LogCat.Discord); return("ERROR"); } }
public async Task Web() { if (SettingsManager.GetBool("config", "moduleWebServer")) { await APIHelper.DiscordAPI.ReplyMessageAsync(Context, WebServerModule.GetWebSiteUrl()); } else { await APIHelper.DiscordAPI.ReplyMessageAsync(Context, $"{LM.Get("webServerOffline")}"); } }
public string GetRemains() { var d = GetDateTime(); if (!d.HasValue) { return(null); } var dif = (d.Value - DateTime.UtcNow); return(string.Format(LM.Get("timerRemains"), dif.Days, dif.Hours, dif.Minutes)); }
internal static string GetAccessDeniedPage(string header, string message, string backUrl, string description = null) { return(File.ReadAllText(SettingsManager.FileTemplateAuth3) .Replace("{headerContent}", GetHtmlResourceDefault(false)) .Replace("{message}", message) .Replace("{header}", header) .Replace("{header2}", header) .Replace("{description}", description) .Replace("{body}", "") .Replace("{backText}", LM.Get("backText")) .Replace("{backUrl}", backUrl)); }
private async Task SendNotification(TimerItem timer, ulong channel) { var embed = new EmbedBuilder() .WithTitle(string.Format(LM.Get("timerNotifyTitle"), timer.timerLocation) ?? "-") .WithThumbnailUrl(SettingsManager.Get("resources", "imgTimerAlert") ?? "-") .AddInlineField(LM.Get("timersType"), timer.GetModeName()) .AddInlineField(LM.Get("timersStage"), timer.GetStageName()) .AddInlineField(LM.Get("timersOwner"), timer.timerOwner ?? "-") .AddInlineField(LM.Get("timersRemaining"), timer.GetRemains()) .AddField(LM.Get("timersNotes"), timer.timerNotes ?? "-"); await APIHelper.DiscordAPI.SendMessageAsync(APIHelper.DiscordAPI.GetChannel(channel), "@everyone", embed.Build()).ConfigureAwait(false); }
public string GetModeName() { switch (timerType) { case 1: return(LM.Get("timerOffensive")); case 2: return(LM.Get("timerDefensive")); default: return(null); } }
private async Task SendMailNotification(ulong channel, JsonClasses.Mail mail, string labelNames) { var sender = await APIHelper.ESIAPI.GetCharacterData(Reason, mail.from); var labels = string.IsNullOrEmpty(labelNames) ? null : $"{LM.Get("mailLabels")} {labelNames} | "; var stamp = DateTime.Parse(mail.timestamp).ToString(SettingsManager.Get("config", "shortTimeFormat")); var embed = new EmbedBuilder() .WithThumbnailUrl(SettingsManager.Get("resources", "imgMail")) .AddField($"{LM.Get("mailSubject")} {mail.subject}", await PrepareBodyMessage(mail.body)) .WithFooter($"{labels}{LM.Get("mailDate")} {stamp}"); var ch = APIHelper.DiscordAPI.GetChannel(channel); await APIHelper.DiscordAPI.SendMessageAsync(ch, string.Format(LM.Get("mailMsgTitle"), sender?.name), embed.Build()).ConfigureAwait(false); }