public TypeReader GetDefaultTypeReader(Type type) { if (_defaultTypeReaders.TryGetValue(type, out var reader)) { return(reader); } var typeInfo = type.GetTypeInfo(); //Is this an enum? if (typeInfo.IsEnum) { reader = DiscordHelper.GetTypeReader(type); _defaultTypeReaders[type] = reader; return(reader); } //Is this an entity? for (int i = 0; i < _entityTypeReaders.Count; i++) { if (type == _entityTypeReaders[i].Item1 || typeInfo.ImplementedInterfaces.Contains(_entityTypeReaders[i].Item1)) { reader = Activator.CreateInstance(_entityTypeReaders[i].Item2.MakeGenericType(type)) as TypeReader; _defaultTypeReaders[type] = reader; return(reader); } } return(null); }
public ChannelsController(ProxyDataContext db, DiscordHelper discordHelper, IConfiguration cfg, WebhookCache webhookCache) { this.db = db; this.discordHelper = discordHelper; this.cfg = cfg; this.webhookCache = webhookCache; }
private void UserControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { if (IsVisible && IsLoaded) { DiscordHelper.SetDiscordRPCStatus("Ribbon/Backstage"); } }
private void UserControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { if (IsVisible) { DiscordHelper.SetDiscordRPCStatus("Document View"); } }
public async Task EchoOnline([Remainder] string message) { var discordHelper = new DiscordHelper(Context.Client); var onlineUsers = discordHelper.GetAllUsers().Where(u => u.Status == UserStatus.Online); await SendMessageToPlayers(onlineUsers, message); }
private void UserControl_IsVisibleChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e) { if (IsVisible) { DiscordHelper.SetDiscordRPCStatus("Backstage - Open File"); } }
private void DataWindow_IsVisibleChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e) { if (IsVisible) { DiscordHelper.SetDiscordRPCStatus("Journal Editor"); } }
public async Task <bool> UserPingInfo() { try { var pingHistory = DiscordHelper.GetTotalPingHistory(DataSocketGuildUser, 10); var builder = DiscordHelper.GetEmbedForPingHistory(pingHistory, DataSocketGuildUser); ulong channelId = 0; if (SocketUserCommand.Channel is SocketThreadChannel SocketThreadChannel) { channelId = SocketThreadChannel.ParentChannel.Id; } else { channelId = SocketUserCommand.Channel.Id; } var settings = CommonHelper.GetChannelSettingByChannelId(channelId).Setting; if (((BotPermissionType)settings.ChannelPermissionFlags).HasFlag(BotPermissionType.EnableType2Commands)) { await SocketUserCommand.Channel.SendMessageAsync("", false, builder.Build()); } else { return(false); } } catch (Exception ex) { } return(true); }
private void UserControl_IsVisibleChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e) { if (IsVisible) { DiscordHelper.SetDiscordRPCStatus("Setting - General"); } }
public async Task RemoveBinding(CommandContext ctx, [Description("URL of the message.")] string url, [Description("Emoji to react with.")] DiscordEmoji emoji, [Description("Roles which will be toggled after reaction")] params DiscordRole[] roles) { DiscordMessage?message = await DiscordHelper.FindMessageFromLink(ctx.Guild, url); if (message == null) { throw new ArgumentOutOfRangeException($"Couldn't find message with link: {url}"); } ulong channelId = message.ChannelId; ulong messageId = message.Id; bool someRemained = await _roleBindingsService.RemoveBindingsAsync(channelId, messageId, emoji.Name, roles.Select(r => r.Id).ToHashSet()); DiscordEmoji thumbsUp = DiscordEmoji.FromName(ctx.Client, ":+1:"); await ctx.Message.CreateReactionAsync(thumbsUp); if (!someRemained) { try { // await message.DeleteReactionsEmojiAsync(emoji); } catch (Exception e) { _logger.LogError(e, "Couldn't add reaction for emoji: {EmojiName} on {Url}", emoji.Name, url); } } }
public MainViewModel() { var feed = Feed <TransitionerMoveStruct> .Instance; feed.RegisterNode(this); DiscordHelper.Initialize(); }
void OnLeftRoom() { DiscordHelper.SetPresence(new Discord.Activity { Details = "Idle..." }); }
private void DataWindow_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { if (IsVisible) { DiscordHelper.SetDiscordRPCStatus("Asset Browser"); } }
public async Task ReactToMessage(CommandContext ctx, [Description("URL of the message.")] string url, [Description("Emojis to react with.")] params DiscordEmoji[] emojis) { DiscordMessage?oldMessage = await DiscordHelper.FindMessageFromLink(ctx.Message.Channel.Guild, url); if (oldMessage == null) { await ctx.Message.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":-1:")); return; } foreach (DiscordEmoji emoji in emojis) { try { await oldMessage.CreateReactionAsync(emoji); } catch (Exception e) { _logger.LogWarning(e, "Couldn't react with emoji {Emoji}", emoji); await ctx.Message.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":bug:")); return; } } await ctx.Message.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":+1:")); }
public static Embed GetMapInfoEmbed(DetailedMapOverviewModel map) { try { var builder = new EmbedBuilder(); builder.WithTitle(map.Name); var tierText = $"Solly : T{map.TierInfo.Soldier}"; if (!string.IsNullOrWhiteSpace(map.Videos.Soldier)) { tierText += $" [Showcase]({TempusHelper.GetYoutubeUrl(map.Videos.Soldier)})"; } tierText += $" | Demo : T{map.TierInfo.Demoman} "; if (!string.IsNullOrWhiteSpace(map.Videos.Demoman)) { tierText += $"[Showcase]({TempusHelper.GetYoutubeUrl(map.Videos.Demoman)})"; } builder.WithDescription(tierText + Environment.NewLine + DiscordHelper.FormatUrlMarkdown("Tempus.xyz", TempusHelper.GetMapUrl(map.Name))); return(builder.Build()); } catch (Exception e) { return(Logger.LogException(e)); } }
/// <inheritdoc /> /// <summary> /// UnloadContent will be called once per game and is the place to unload /// game-specific content. /// </summary> protected override void UnloadContent() { OnlineManager.Client?.Disconnect(); Transitioner.Dispose(); DiscordHelper.Shutdown(); base.UnloadContent(); }
private void BtnTest_Click(object sender, System.EventArgs e) { if (string.IsNullOrEmpty(textboxWebhookURL.Text)) { return; } var acc = GetSelectedAcc(); try { acc.WebhookClient = DiscordHelper.InitWebhookClient(textboxWebhookURL.Text); DiscordHelper.SendMessage(acc, "This is the test message from TravianBotSharp"); acc.AccInfo.WebhookUrl = textboxWebhookURL.Text; acc.Settings.DiscordWebhook = UseDiscordAlert.Checked; acc.Settings.DiscordOnlineAnnouncement = onlineAnnouncement.Checked; } catch (System.ArgumentException) { MessageBox.Show("The given webhook Url was not in a vaild format"); } catch (Discord.Net.HttpException error) { MessageBox.Show(error.Message, error.HelpLink); } catch (System.InvalidOperationException error) { MessageBox.Show(error.Message); } catch (System.Exception error) { acc.Wb.Log(error.ToString()); } }
public async Task <ActionResult> PurgeAsync([Description("The amount of messages to purge.")] int count, [Description("If provided, will only delete messages by this user within `count` messages.")] RestUser targetAuthor = null) { //+1 to include the command invocation message, and actually delete the last x messages instead of x - 1. //lets you theoretically use 0 to delete only the invocation message, for testing or something. var messages = (await Context.Channel.GetMessagesAsync(count + 1).FlattenAsync()).ToList(); try { await Context.Channel.DeleteMessagesAsync( messages.Where(x => targetAuthor is null || x.Author.Id == targetAuthor.Id), DiscordHelper.CreateRequestOptions(opts => opts.AuditLogReason = $"Messages purged by {Context.User}.")); } catch (ArgumentOutOfRangeException) { return(BadRequest( $"Messages bulk deleted must be younger than 14 days. {Format.Code("This is a Discord restriction, not a Volte one.")}")); } //-1 to show that the correct amount of messages were deleted. return(None(async() => { await Interactive.ReplyAndDeleteAsync(Context, string.Empty, embed: Context.CreateEmbed($"Successfully deleted {Format.Bold("message".ToQuantity(messages.Count - 1))}."), timeout: 3.Seconds()); await ModerationService.OnModActionCompleteAsync(ModActionEventArgs.New .WithDefaultsFromContext(Context) .WithActionType(ModActionType.Purge) .WithCount(count)); }, false)); }
public static PollInfo FromDefaultFields(IEnumerable <string> choices) { var emojis = DiscordHelper.GetPollEmojis(); var collection = choices as string[] ?? choices.ToArray(); if (collection.Length - 1 > 10) { return(FromInvalid("More than 9 options specified.")); } if (collection.Length is 1) { return(FromInvalid("No options specified.")); } var fields = new List <(object Name, object Value)>(); collection.ForEachIndexed((entry, index) => { if (index is 0) { return; } fields.Add((emojis[index - 1], collection[index])); }); return(FromFields(fields)); }
public override PluginResponse OnEnable(IBotSettings botSettings) { if (!botSettings.loadEntities || !botSettings.loadPlayers) { return(new PluginResponse(false, "'Load entities & load players' must be enabled.")); } if (!botSettings.loadWorld && !string.IsNullOrWhiteSpace(Setting[7].Get <string>())) { return(new PluginResponse(false, "'Load worlds' must be enabled.")); } try { if (string.IsNullOrWhiteSpace(Setting[0].Get <string>())) { return(new PluginResponse(false, "Could not parse discord id.")); } ulong.Parse(Setting[0].Get <string>()); } catch (Exception ex) { return(new PluginResponse(false, "Could not parse discord id.")); } // Do warnings. if (string.IsNullOrWhiteSpace(Setting[7].Get <string>()) && (!botSettings.loadWorld || botSettings.staticWorlds)) { DiscordHelper.Error("[RaidAlerts] 'Load worlds' should be enabled, 'Shared worlds' should be disabled.", 584); } if (Setting[10].Get <bool>() && (!botSettings.loadEntities || !botSettings.loadMobs)) { DiscordHelper.Error("[RaidAlerts] 'Load entities' & 'Load mobs' should be enabled.", 585); } return(new PluginResponse(true)); }
private void UserControl_IsVisibleChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e) { if (IsVisible) { DiscordHelper.SetDiscordRPCStatus("CyberCAT Save Editor"); } }
private void UserControl_IsVisibleChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e) { if (IsVisible) { DiscordHelper.SetDiscordRPCStatus("Animation Exporter"); } }
protected override async void OnStartup(StartupEventArgs e) { #if DEBUG LogManager.AddDebugListener(); #endif Log.Info("Starting application"); apphelper = new WKitGlobal.AppHelper(); discordhelper = new DiscordHelper(); GithubHelper = new GithubHelper(); themehelper = new ThemeHelper(); await apphelper.InitializeMVVM(); themehelper.InitializeThemeHelper(); await apphelper.InitializeShell(); discordhelper.InitDiscordRPC(); Log.Info("Calling base.OnStartup"); base.OnStartup(e); NNViewRegistrar.RegisterSplat(); }
void Start() { if (!Initialized) { // Check for an update before doing anything StartCoroutine(CheckForUpdate()); // Host whitelist (for skins) if (!File.Exists(HostWhitelistPath)) { HostWhitelist.Add("i.imgur.com"); HostWhitelist.Add("imgur.com"); HostWhitelist.Add("cdn.discordapp.com"); HostWhitelist.Add("cdn.discord.com"); HostWhitelist.Add("media.discordapp.net"); HostWhitelist.Add("i.gyazo.com"); File.WriteAllLines(HostWhitelistPath, HostWhitelist.ToArray()); } LoadSkinHostWhitelist(); // Auto-load RC name and guild (if possible) FengGameManagerMKII.NameField = PlayerPrefs.GetString("name", string.Empty); if (FengGameManagerMKII.NameField.Uncolored().Length == 0) { FengGameManagerMKII.NameField = LoginFengKAI.Player.Name; } LoginFengKAI.Player.Guild = PlayerPrefs.GetString("guildname", string.Empty); // Load various features Commands.Load(); Properties.Load(); // Print out debug information Logger.Info($"Installed Version: {Build}"); Logger.Info($"Unity Version: {Application.unityVersion}"); Logger.Info($"OS: {SystemInfo.operatingSystem}"); Logger.Info($"Platform: {Application.platform}"); // Property whitelist NetworkPatches.PropertyWhitelist.Add("sender"); NetworkPatches.PropertyWhitelist.Add("GuardianMod"); foreach (FieldInfo field in typeof(PhotonPlayerProperty).GetFields(BindingFlags.Public | BindingFlags.Static)) { NetworkPatches.PropertyWhitelist.Add((string)field.GetValue(null)); } Initialized = true; DiscordHelper.StartTime = GameHelper.CurrentTimeMillis(); } base.gameObject.AddComponent <UI.ModUI>(); base.gameObject.AddComponent <MicEF>(); DiscordHelper.SetPresence(new Discord.Activity { Details = $"Staring at the main menu...", }); }
public async Task UpdateLastInteractedWithMessage(string update) { if (_lastMessagedInteractedWith != null) { var embed = DiscordHelper.CreateEmbeddedMessage(update); await _lastMessagedInteractedWith.ModifyAsync(msg => msg.Embed = embed); } }
public async Task <string> Respond(string response) { var embed = DiscordHelper.CreateEmbeddedMessage(response); var mes = await _responseChannel.SendMessageAsync(embed : embed); _lastMessagedInteractedWith = mes; return(mes.Id.ToString()); }
public ProxiesController(ProxyDataContext db, IConfiguration cfg, DiscordHelper discordHelper, AvatarHelper avatarHelper, ILogger <ProxiesController> logger) { this.db = db; this.cfg = cfg; this.discordHelper = discordHelper; this.avatarHelper = avatarHelper; this.logger = logger; }
public MusicService(PlaylistDataAccess db, DiscordHelper helper, DiscordClient client, ConfigService config) { this.db = db; this.helper = helper; this.client = client; this.config = config; lavalink = client.GetLavalink(); playlist = db.GetAllPlaylistTracks().Result; }
public static async Task <Embed> UpdateStalkTopEmbedAsync(TempusDataAccess tempusDataAccess) { try { var servers = (await tempusDataAccess.GetServerStatusAsync()).Where(x => x != null).ToArray(); var users = servers.Where(x => x.GameInfo != null && (x.GameInfo != null || x.ServerInfo != null || x.GameInfo.Users != null) && x.GameInfo.Users.Count != 0) .SelectMany(x => x.GameInfo.Users).Where(x => x?.Id != null).ToArray(); var userIdStrings = (from user in users where user?.Id != null select user.Id.ToString()).ToList(); var rankTasks = new List <Task <Rank> >(); rankTasks.AddRange(userIdStrings.Select(tempusDataAccess.GetUserRankAsync)); var ranks = await Task.WhenAll(rankTasks); var rankedUsers = ranks.ToDictionary(rank => users.First(x => x.Id == rank.PlayerInfo.Id), rank => rank.ClassRankInfo.DemoRank.Rank <= rank.ClassRankInfo.SoldierRank.Rank ? rank.ClassRankInfo.DemoRank.Rank : rank.ClassRankInfo.SoldierRank.Rank); var output = rankedUsers.OrderBy(x => x.Value).Take(7); var rankedLines = ""; foreach (var(key, value) in output) { if (key == null || value > 100) { continue; } var server = servers .FirstOrDefault(x => x.GameInfo?.Users != null && x.GameInfo.Users.Count(z => z.Id.HasValue && z.Id == key.Id) != 0); if (server == null || key.Id == null) { continue; } rankedLines += $"Rank {value} - {DiscordHelper.FormatUrlMarkdown(key.Name.EscapeDiscordChars(), TempusHelper.GetPlayerUrl(key.Id.Value))} on {DiscordHelper.FormatUrlMarkdown(server.GameInfo.CurrentMap.EscapeDiscordChars(), TempusHelper.GetMapUrl(server.GameInfo.CurrentMap))} {DiscordHelper.FormatUrlMarkdown(server.ServerInfo.Shortname, TempusHelper.GetServerUrl(server.ServerInfo.Id))}{Environment.NewLine}"; } var builder = new EmbedBuilder { Title = "**Highest Ranked Players Online** (Top 100)", Description = rankedLines } .WithCurrentTimestamp().WithColor(ColorConstants.InfoColor); CachedStalkTopEmbed = builder.Build(); return(builder.Build()); } catch (Exception e) { return(Logger.LogException(e)); } }
public async Task EchoAll(string message, [Remainder] string password) { if (password == "Prohumper" && message.Trim() != "") { var discordHelper = new DiscordHelper(Context.Client); var onlineUsers = discordHelper.GetAllUsers(); await SendMessageToPlayers(onlineUsers, message); } }