public void SetUpCustomReplyEditor(DiscordChannel channel, ulong userId) { Task.Run(async () => { if (ActiveEditorsInChannels.Contains(channel.Id)) { await channel.SendMessageAsync("An editor is already active in this channel.").ConfigureAwait(false); return; } else { ActiveEditorsInChannels.Add(channel.Id); } try { var interactivity = _client.GetInteractivity(); await EditorList(interactivity, channel, userId).ConfigureAwait(false); } catch (Exception e) { await channel.SendMessageAsync($"Error occurred within editor: {e.Message}").ConfigureAwait(false); AegisLog.Log(e.Message, e); } finally { await channel.SendMessageAsync("Custom reply editor exited.").ConfigureAwait(false); ActiveEditorsInChannels.Remove(channel.Id); } }); }
private void SetUpCustomReplies() { var customReplies = new List<CustomReply>(); var uow = _db.UnitOfWork(); var customRepliesDb = uow.CustomReplies.GetAll(); foreach (var customReplyDb in customRepliesDb) { try { var channels = string.IsNullOrEmpty(customReplyDb.ChannelIds) ? new List<DiscordChannel>() : customReplyDb.ChannelIds.Split(',').Select(x => ulong.Parse(x.Trim())).Distinct().Select(x => _client.GetChannelAsync(x).Result).ToList(); var triggers = customReplyDb.Triggers.Split(';').Select(x => x.Split(',').Select(y => y.ToLower()).ToList()).ToList(); var customReply = new CustomReply { Id = customReplyDb.Id, GuildId = customReplyDb.GuildId, Channels = channels, Message = customReplyDb.Message, Triggers = triggers, Cooldown = customReplyDb.Cooldown }; customReplies.Add(customReply); } catch (Exception e) { AegisLog.Log($"Error adding customReply: {JsonConvert.SerializeObject(customReplyDb)}", e); } } CustomReplies = customReplies.GroupBy(x => x.GuildId).ToList(); }
private void SetUpAllStreamers() { try { var liveUsers = new List <LiveUser>(); var uow = _db.UnitOfWork(); var liveUsersDb = uow.LiveUsers.GetAll(); foreach (var liveUserDb in liveUsersDb) { var liveUser = new LiveUser { GuildId = liveUserDb.GuildId, UserId = liveUserDb.UserId, TwitchName = liveUserDb.TwitchName, PriorityUser = liveUserDb.PriorityUser, TwitchAlert = liveUserDb.TwitchAlert, IsStreaming = liveUserDb.IsStreaming, LastStreamed = liveUserDb.LastStreamed, StreamStateChanged = false, HasRole = liveUserDb.HasRole }; liveUsers.Add(liveUser); } LiveUsers = liveUsers.GroupBy(x => x.GuildId).ToList(); } catch (Exception ex) { AegisLog.Log(ex.Message, ex); return; } HasInit = true; }
private async Task GetNewToken() { if (_accessTokenTimer.Enabled) { return; } _accessTokenTimer.Enabled = true; try { var hcHandle = new HttpClientHandler(); var hc = new HttpClient(hcHandle, false); hc.Timeout = TimeSpan.FromSeconds(5); var stringContent = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("client_id", TwitchClientId), new KeyValuePair <string, string>("client_secret", TwitchClientSecret), new KeyValuePair <string, string>("grant_type", "client_credentials") }); var response = await hc.PostAsync("https://id.twitch.tv/oauth2/token", stringContent); response.EnsureSuccessStatusCode(); var jsonString = await response.Content.ReadAsStringAsync(); var jsonObject = JObject.Parse(jsonString); var jsonData = jsonObject["access_token"]; AccessToken = jsonData.ToString(); } catch (Exception e) { AegisLog.Log(e.Message, e); } }
private async void SyncDatabase(object Sender, System.Timers.ElapsedEventArgs e) { try { var uow = _db.UnitOfWork(); foreach (var liveUserGroup in LiveUsers) { foreach (var liveUser in liveUserGroup) { uow.LiveUsers.AddOrUpdateByLiveUser(liveUser); } } await uow.SaveAsync().ConfigureAwait(false); } catch (Exception ex) { AegisLog.Log(ex.Message, ex); } finally { if (!_twitchPollTimer.Enabled) { _twitchPollTimer.Start(); } } }
private void SetUpQueues() { InhouseQueues = new List <InhouseQueue>(); InhouseGames = new List <InhouseGame>(); try { var uow = _db.UnitOfWork(); var inhouses = uow.Inhouses.GetAll(); foreach (var inhouse in inhouses) { var inhouseQueue = new InhouseQueue(inhouse.ChannelId); inhouseQueue.Emojis[PlayerRole.Top] = inhouse.TopEmoji; inhouseQueue.Emojis[PlayerRole.Jgl] = inhouse.JglEmoji; inhouseQueue.Emojis[PlayerRole.Mid] = inhouse.MidEmoji; inhouseQueue.Emojis[PlayerRole.Bot] = inhouse.BotEmoji; inhouseQueue.Emojis[PlayerRole.Sup] = inhouse.SupEmoji; inhouseQueue.Emojis[PlayerRole.Fill] = inhouse.FillEmoji; InhouseQueues.Add(inhouseQueue); } } catch (Exception ex) { AegisLog.Log(ex.Message, ex); } }
private async void PollTwitchStreams(object Sender, System.Timers.ElapsedEventArgs e) { try { // we always init first if (!HasInit) { if (!Initing) { try { Initing = true; SetUpAllStreamers(); } catch (Exception ex) { AegisLog.Log(ex.Message, ex); return; } finally { Initing = false; } } } if (HasInit && !IsPolling) { try { IsPolling = true; if (AccessToken == "") { await GetNewToken().ConfigureAwait(false); } await TryPollTwitchStreams().ConfigureAwait(false); await UpdateAllRoles().ConfigureAwait(false); } catch (Exception ex) { AegisLog.Log(ex.Message, ex); } finally { IsPolling = false; } } } finally { if (!_twitchPollTimer.Enabled) { _twitchPollTimer.Start(); } } }
public async Task CustomReplyEditor(CommandContext ctx) { try { _service.SetUpCustomReplyEditor(ctx.Channel, ctx.User.Id); } catch (Exception e) { await ctx.Channel.SendMessageAsync($"Some error occured: {e.Message}").ConfigureAwait(false); AegisLog.Log(e.Message, e); } }
private async Task DayGif(CommandContext ctx, DayOfWeek dayOfWeek) { try { switch (dayOfWeek) { case DayOfWeek.Monday: await ctx.Channel.SendMessageAsync($"https://tenor.com/view/lazy-cat-stairs-monday-gif-15789725").ConfigureAwait(false); break; case DayOfWeek.Tuesday: await ctx.Channel.SendMessageAsync($"https://tenor.com/view/three-amigos-taco-tuesday-dance-gif-14760901").ConfigureAwait(false); break; case DayOfWeek.Wednesday: await ctx.Channel.SendMessageAsync($"https://tenor.com/view/its-chinese-wednesday-funny-asian-chinese-kid-gif-16305229").ConfigureAwait(false); break; case DayOfWeek.Thursday: await ctx.Channel.SendMessageAsync($"https://tenor.com/view/excited-friday-tomorrow-yay-end-of-the-week-gif-5319510").ConfigureAwait(false); break; case DayOfWeek.Friday: await ctx.Channel.SendMessageAsync($"https://cdn.discordapp.com/attachments/268196447667617803/716023791985229844/friday.mov").ConfigureAwait(false); break; case DayOfWeek.Saturday: await ctx.Channel.SendMessageAsync($"https://tenor.com/view/saturday-dance-old-dancing-party-hard-gif-11712974").ConfigureAwait(false); break; case DayOfWeek.Sunday: await ctx.Channel.SendMessageAsync($"https://tenor.com/view/holiday-weekend-sunday-back-to-work-gif-10666503").ConfigureAwait(false); break; } } catch (Exception e) { AegisLog.Log(e.Message, e); } ctx.Message.DeleteAfter(3); }
private async Task <bool> TryPollTwitchStreamBulk(HttpClientHandler hcHandle, IEnumerable <LiveUser> liveUsers) { // return value var hasLive = false; // error checking here if (liveUsers.Count() == 0) { return(false); } var uow = _db.UnitOfWork(); var hasGuild = _client.Guilds.TryGetValue(liveUsers.First().GuildId, out var guild); if (!hasGuild) { AegisLog.Log($"Server does not exist!"); return(false); } var hc = new HttpClient(hcHandle, false); hc.DefaultRequestHeaders.Add("Client-ID", TwitchClientId); hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", AccessToken); hc.DefaultRequestHeaders.UserAgent.ParseAdd("AegisLiveBot"); hc.Timeout = TimeSpan.FromSeconds(15); // separate them into bulks of 100 users (most likely wont hit 100 users) var bulkLiveUsers = new List <List <LiveUser> >(); var currentBulk = new List <LiveUser>(); foreach (var liveUser in liveUsers) { currentBulk.Add(liveUser); if (currentBulk.Count >= 100) { bulkLiveUsers.Add(currentBulk); currentBulk = new List <LiveUser>(); } } if (currentBulk.Count() != 0) { bulkLiveUsers.Add(currentBulk); } // call twitch api for each bulk foreach (var liveUserBulk in bulkLiveUsers) { var userLoginString = "user_login="******"&user_login="******"https://api.twitch.tv/helix/streams?{userLoginString}", cancellationToken).ConfigureAwait(false); try { cancellationToken.ThrowIfCancellationRequested(); try { response.EnsureSuccessStatusCode(); // if not OK if (response.StatusCode != HttpStatusCode.OK) { await GetNewToken().ConfigureAwait(false); continue; } // if ratelimit reaching limits, wait a bit var limit = int.Parse(response.Headers.FirstOrDefault(x => x.Key == "Ratelimit-Remaining").Value.ToList()[0]); if (limit <= 5) { await Task.Delay(5000).ConfigureAwait(false); } } catch (Exception ex) { AegisLog.Log(ex.Message); await Task.Delay(5000).ConfigureAwait(false); } var jsonString = await response.Content.ReadAsStringAsync(); var jsonObject = JObject.Parse(jsonString); var jsonData = jsonObject["data"]; // jsonData has the live streams returned foreach (var liveUser in liveUserBulk) { var streamData = jsonData.FirstOrDefault(x => x["user_name"].ToString().ToLower() == liveUser.TwitchName.ToLower()); var jsonType = streamData != null ? streamData["type"] : null; if (streamData == null || jsonType == null || jsonType.ToString() != "live") { liveUser.IsStreaming = false; if (liveUser.HasRole) { liveUser.StreamStateChanged = true; } } else { hasLive = true; liveUser.IsStreaming = true; if (!liveUser.HasRole) { liveUser.StreamStateChanged = true; } } } } catch (Exception ex) { AegisLog.Log(ex.Message, ex); } } return(hasLive); }
private async Task UpdateAllRoles() { foreach (var liveUsersGroup in LiveUsers) { var hasGuild = _client.Guilds.TryGetValue(liveUsersGroup.Key, out var guild); if (!hasGuild) { AegisLog.Log($"Bot is not in guild #{liveUsersGroup.Key}"); continue; } var uow = _db.UnitOfWork(); var serverSetting = uow.ServerSettings.GetOrAddByGuildId(liveUsersGroup.Key); await uow.SaveAsync().ConfigureAwait(false); var role = guild.GetRole(serverSetting.RoleId); if (role == null) { AegisLog.Log($"Role not set for guild #{liveUsersGroup.Key}"); continue; } var twitchAlertChannel = guild.GetChannel(serverSetting.TwitchChannelId); if (twitchAlertChannel == null && serverSetting.TwitchAlertMode) { AegisLog.Log($"Twitch alert channel not set for guild #{liveUsersGroup.Key}"); } foreach (var liveUser in liveUsersGroup) { var user = await guild.GetMemberAsync(liveUser.UserId).ConfigureAwait(false); if (user == null) { AegisLog.Log($"User does not exist!"); await RemoveLiveUser(liveUser.GuildId, liveUser.UserId).ConfigureAwait(false); continue; } if (liveUser.StreamStateChanged) { if (liveUser.HasRole) { await user.RevokeRoleAsync(role).ConfigureAwait(false); } else { if (serverSetting.TwitchAlertMode && liveUser.TwitchAlert && liveUser.LastStreamed.AddHours(STREAM_ALERT_COOLDOWN_HOUR) < DateTime.UtcNow) { await twitchAlertChannel.SendMessageAsync($"@everyone streamer is LIVE YO https://www.twitch.tv/{liveUser.TwitchName}").ConfigureAwait(false); } liveUser.LastStreamed = DateTime.UtcNow; await user.GrantRoleAsync(role).ConfigureAwait(false); } liveUser.StreamStateChanged = false; liveUser.HasRole = !liveUser.HasRole; } } } }