private async Task Client_MessageReceived(SocketMessage msg) { // TODO: Implement error catching, and ensure that the report was actually forwarded before replying. // TODO: Check if there is more than one staff role in use, or if standard members should also be allowed to report // Optional: Implement a command to reply from the manager channel directly to the DM to simulate // a group DM. Or maybe it'd be easier to create a real group DM and keep the bot simple. if (msg.Author.Id == socketClient.CurrentUser.Id || msg.Author.IsBot) { return; // Don't respond to our own messages or other bots to help prevent loops } if ((msg.Channel as SocketGuildChannel) == null) // Check that this is a DM (no guild associated with it) { SocketGuildUser socketUser = socketClient.GetGuild(config.MainGuild).GetUser(msg.Author.Id); // Attempt to see if the user object is cached and in the target guild RestGuildUser restUser = null; List <ulong> roles = new List <ulong>(); if (socketUser != null) // If the user is in our guild, store their roles { roles.AddRange(socketUser.Roles.Select(x => x.Id)); } else // Otherwise ensure it isn't a caching issue by attempting to manually download the user { restUser = await restClient.GetGuildUserAsync(config.MainGuild, msg.Author.Id); } if (roles.Count() == 0 && restUser == null) { return; // The user isn't in the server } else if (restUser != null) // Store the roles from the downloaded user { roles.AddRange(restUser.RoleIds); } if (!roles.Contains(config.StaffRole)) { return; // Return if the user isn't a staff member } // At this point we've determined that the user is in the server and has the staff role string source = $"Message receieved from {msg.Author.Username}#{msg.Author.Discriminator} [{msg.Author.Id}]"; // Information about who sent it to prevent abuse if (msg.Content.Length + source.Length + 2 < 2000) // Make sure we're not about to send a message larger than Discord allows { await(socketClient.GetChannel(config.ManagerChannel) as SocketTextChannel).SendMessageAsync($"{source}\n{msg.Content}"); } else { await(socketClient.GetChannel(config.ManagerChannel) as SocketTextChannel).SendMessageAsync(source); await(socketClient.GetChannel(config.ManagerChannel) as SocketTextChannel).SendMessageAsync(msg.Content); } await msg.Channel.SendMessageAsync($"Thank you for your report {msg.Author.Mention}, it has been forwarded to the relevant channel."); } }
public static void SendPlanInformation(this IDiscordRestApi discordRestApi, ulong discordId, ulong duserId, string priorityState, TimeSpan Remining) { try { RestGuildUser usr = null; RestGuild gld = null; string namefor = ""; string priorityId = ""; string title = "? Updated"; if (priorityState == "User") { usr = discordRestApi.GetGuildUserAsync(discordId, duserId).Result; namefor = $"{usr?.Username}#{usr?.Discriminator}"; priorityId = $"{priorityState}-{usr.Id}"; title = $"INDIVIDUAL PLAN IS UPDATED"; } else if (priorityState == "Guild") { gld = discordRestApi.GetApi.GetGuildAsync(discordId).Result; usr = gld?.GetOwnerAsync().Result; namefor = $"{gld?.Name}"; priorityId = $"{priorityState}-{gld.Id}"; title = $"PRO PLAN IS UPDATED"; } DateTime dtx = new DateTime(); dtx = dtx.Add(Remining); EmbedBuilder embed = new EmbedBuilder() { Author = new EmbedAuthorBuilder() { IconUrl = discordRestApi.GetApi.CurrentUser.GetAvatarUrl(), Name = discordRestApi.GetApi.CurrentUser.Username }, Color = Color.Green, Title = title }; embed.Description += $"Type: **{priorityState}**\n" + $"Name: {namefor}\n" + $"Expires In: **{dtx.Year - 1}**Years **{dtx.Month - 1}**Months **{dtx.Day - 1}**days **{dtx.Hour}**hours\n"; embed.Description += "\n\n"; try { RestDMChannel dm = usr.GetOrCreateDMChannelAsync().Result; Embed bembed = embed.Build(); RestUserMessage msg = dm.SendMessageAsync(string.Empty, false, bembed).Result; dm.CloseAsync().Wait(); } catch (Exception e) { } } catch (Exception ee) { throw ee; } }
private static bool RestIsGuildAdmin(RestGuildUser user, SocketGuild guild) { if (guild.Owner.Id == user.Id) { return(true); } else if (user.RoleIds.Intersect(guild.Roles.Where(r => r.Permissions.Administrator).Select(r => r.Id)).Any()) { return(true); } return(false); }
private int GetHierarchyOfUser(RestGuild guild, RestGuildUser user) { var orderedRoles = guild.Roles.OrderByDescending(r => r.Position).ToArray(); var orderedRoleIds = orderedRoles.Select(x => x.Id).ToArray(); for (int i = 0; i < orderedRoleIds.Length; i++) { var test = user.RoleIds.FirstOrDefault(x => x == orderedRoleIds[i]); if (test != 0) { return(orderedRoles[i].Position); } } return(0); }
public DiscordUser(RestGuildUser user) { ID = user.Id; Discriminator = user.Discriminator; Username = user.Username; Status = user.Status; IsBot = user.IsBot; ActivityType = user.Activity.Type; ActivityName = user.Activity.Name; AvatarId = user.AvatarId; GuildId = user.GuildId; IsDeafened = user.IsDeafened; IsMuted = user.IsMuted; JoinedAt = user.JoinedAt; Permissions = user.GuildPermissions.RawValue; }
public static Color GetUserTopColour(this RestGuildUser user, DiscordSocketRestClient client, ulong guildId) { var guild = client.GetGuildAsync(guildId).GetAwaiter().GetResult(); var userRoleIds = user.RoleIds.ToArray(); for (int i = 0; i < userRoleIds.Length; i++) { var role = guild.Roles.FirstOrDefault(x => x.Id == userRoleIds[i]); if (role.Color == Color.Default) { continue; } return(role.Color); } return(new Color(5198940)); }
public async Task GetTime([Summary("The IANA or Windows time zone to get the time for")][Remainder] string timeZone = null) { await Context.Channel.TriggerTypingAsync(); _logger.LogInformation("{username}#{discriminator} executed time ({timezone}) on {server}/{channel}", Context.User.Username, Context.User.Discriminator, timeZone, Context.Guild?.Name ?? "DM", Context.Channel.Name); //if (timeZone == null) //{ // await Context.Channel.SendEmbedAsync("Unable to parse time zone", "Please provide a windows or IANA timezone", // ColorHelper.GetColor(await _serverService.GetServer(Context.Guild))); // //return; //} if (timeZone != null && TryParseTimeZone(timeZone, out TimeZoneInfo tzi)) { DateTime time = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi); await Context.Channel.SendEmbedAsync("Current Time", $"The current time in {timeZone} is:\n`{time}`", ColorHelper.GetColor(await _serverService.GetServer(Context.Guild))); return; } else { await Context.Channel.SendEmbedAsync("Invalid Time Zone", $"{timeZone} is *not* a valid windows or IANA timezone.", ColorHelper.GetColor(await _serverService.GetServer(Context.Guild))); } //TimeZoneInfo tzi; //if (!TZConvert.TryGetTimeZoneInfo(timeZone, out tzi)) //{ // await Context.Channel.SendEmbedAsync("Invalid Time Zone", $"{timeZone} is *not* a valid windows or IANA timezone.", // ColorHelper.GetColor(await _serverService.GetServer(Context.Guild))); //} //else //{ // DateTime time = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi); // await Context.Channel.SendEmbedAsync("Current Time", $"The current time in {timeZone} is:\n`{time}`", // ColorHelper.GetColor(await _serverService.GetServer(Context.Guild))); //} RestGuildUser user = null; if (timeZone != null) { user = (await Context.Guild.SearchUsersAsync(timeZone, 1)).FirstOrDefault(); } if (user == null) { user = (await Context.Guild.SearchUsersAsync(Context.User.Username)).FirstOrDefault(); if (user == null) { await ReplyAsync("Couldn't find you...."); return; } } var server = await _serverService.GetServer(Context.Guild); var prefix = String.Empty; if (server != null) { prefix = server.Prefix; } await ReplyAsync($"The command you are looking for is `{prefix}utime`, but I helped you out anyway!"); await UserTime(Context.Guild.GetUser(user.Id)); }
static bool TryGetUser(TypeParserResult <RestGuildUser> res, out RestGuildUser user) { user = res.IsSuccessful ? res.Value : null; return(user != null); }
public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Manage")); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return(View("ExternalLoginFailure")); } var user = new ApplicationUser { UserName = info.DefaultUserName, Email = info.DefaultUserName }; DiscordRestClient dcli = new DiscordRestClient(new DiscordRestConfig { LogLevel = Discord.LogSeverity.Info }); await dcli.LoginAsync(Discord.TokenType.Bot, ConfigHelper.Instance.DiscordBotToken); ulong discordUserId = Convert.ToUInt64(info.ExternalIdentity.Claims.First().Value); ulong guildId = Convert.ToUInt64(ConfigHelper.Instance.DiscordGuildID); RestGuildUser guser = dcli.GetGuildUserAsync(guildId, discordUserId).Result; if (guser != null) { RestGuild guild = dcli.GetGuildAsync(guildId).Result; List <string> roleNames = guild.Roles.Where(x => guser.RoleIds.Contains(x.Id)).Select(x => x.Name).ToList(); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new ApplicationDbContext())); foreach (string roleName in roleNames) { if (!roleManager.RoleExists(roleName)) { roleManager.Create(new IdentityRole(roleName)); } } var result = await UserManager.CreateAsync(user); if (result.Succeeded) { await UserManager.AddToRolesAsync(user.Id, roleNames.ToArray()); result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); return(RedirectToLocal(returnUrl)); } } AddErrors(result); } } ViewBag.ReturnUrl = returnUrl; return(View(model)); }
public static PermissionLevels GetPermissions(ulong userId, ulong guildId) { var guild = Core.DiscordClient.GetGuild(guildId); if (guild == null) { return(PermissionLevels.None); } SocketGuildUser sUser = null; RestGuildUser rUser = null; try{ sUser = Core.DiscordClient.GetGuild(guildId).GetUser(userId); } catch { } if (sUser == null) { rUser = Core.DiscordClient.GetShardFor(guild).Rest.GetGuildUserAsync(guildId, userId).Result; } if (Core.CheckBlacklisted(userId)) { return(PermissionLevels.None); } else if (userId.Equals(Core.GetOwnerId())) { return(PermissionLevels.BotOwner); } else if (Core.CheckGlobalAdmin(userId)) { return(PermissionLevels.GlobalAdmin); } if (sUser != null) { if (SocketIsGuildAdmin(sUser, guild)) { return(PermissionLevels.GuildOwner); } else if (sUser.Roles.Select(r => r.Id).Intersect(Core.GetGuildConfig(guildId).AdminRoleIds).Any()) { return(PermissionLevels.Admin); } else if (sUser.Roles.Select(r => r.Id).Intersect(Core.GetGuildConfig(guildId).ModRoleIds).Any()) { return(PermissionLevels.Moderator); } } else { if (RestIsGuildAdmin(rUser, guild)) { return(PermissionLevels.GuildOwner); } else if (rUser.RoleIds.Intersect(Core.GetGuildConfig(guildId).AdminRoleIds).Any()) { return(PermissionLevels.Admin); } else if (rUser.RoleIds.Intersect(Core.GetGuildConfig(guildId).ModRoleIds).Any()) { return(PermissionLevels.Moderator); } } return(PermissionLevels.User); }
public static bool HasRole(this RestGuildUser member, IRole role) { return(member.HasRole(role?.Id ?? 0)); }
public static bool HasRole(this RestGuildUser member, ulong roleId) { return(member.RoleIds.FirstOrDefault(r => r == roleId) != default); }
public Task _UpdateName(string mention) { return(Task.Run(async() => { Regex r = new Regex("<@!?(\\d+)>", RegexOptions.Singleline); var m = r.Match(mention); if (m.Success) { RestGuildUser cuser = Context.DiscordRestApi.GetGuildUserAsync(Context.Guild.Id, m.Groups[1].Value.ToUlong()).Result; if (cuser == null) { return; } if (cuser.IsServerOwner()) { await ReplyEmbedErrorAsync(Translate.GetBotTranslation(BotTranslationString.CanNotUpdateDiscordOwner, GetLanguage(), cuser.Mention)); return; } var uid = cuser.Id.ToString(); { var usr = Context.Repo.Db <FortniteUser>() .GetById(uid); NameState ns = usr.NameStates.FirstOrDefault(p => p.FortniteUserId == uid && p.DiscordServerId == Context.Guild.Id.ToString()); if (usr == null) { await ReplyEmbedErrorAsync(Translate.GetBotTranslation(BotTranslationString.FirstlyUseAnotherCmd1, GetLanguage(), cuser.Mention)); return; } else if (ns == null) { ns = await Context.Repo.User.AddOrGetNameStateAsync(usr, Context.Guild.Id.ToString()); } if (!usr.IsValidName) { await ReplyEmbedErrorAsync(Translate.GetBotTranslation(BotTranslationString.FirstlyUseAnotherCmd2, GetLanguage(), cuser.Mention)); return; } var pstate = await CheckUserPriority(new TimeSpan(0, 0, 10, 0), usr, cuser, ns); if (pstate.Value == null) { return; } var msg = await ReplyEmbedPriorityAsync(ToTranslate(BotTranslationString.UpdateRequestReceived, GetLanguage(), mention), pstate); if (!string.IsNullOrWhiteSpace(usr.EpicId)) { if (usr.GameUserMode == GameUserMode.PVE) { FortnitePVEProfile fortniteProfile = Context.Repo.Db <FortnitePVEProfile>() .All() .FirstOrDefault(f => f.EpicId == usr.EpicId); await SetNewNameViaMode <FortnitePVEProfile>(cuser, usr, msg, fortniteProfile); } else { FortnitePVPProfile fortniteProfile = Context.Repo.Db <FortnitePVPProfile>() .All() .FirstOrDefault(f => f.EpicId == usr.EpicId); await SetNewNameViaMode <FortnitePVPProfile>(cuser, usr, msg, fortniteProfile); } } else { await msg.SetErrorAsync(); } } } else { ReplyEmbedErrorAsync($"invalid user mention.").Wait(); } })); }
public async Task StreamOnline(List <TwitchUser> userList, StreamStatus streamStatus) { foreach (TwitchUser t in userList) { //Really iterating over servers here. Task <Server> getServerTask = _context.ServerList.AsQueryable().FirstAsync(s => s.ServerId == t.ServerId); RestGuild guild = (RestGuild)await _client.GetGuildAsync(ulong.Parse(t.ServerId)); Task <RestGuildUser> getUserTask = null; if (!string.IsNullOrEmpty(t.DiscordUserId)) { //We don't need this yet so we'll do this later. getUserTask = guild.GetUserAsync(ulong.Parse(t.DiscordUserId)); } Server server = await getServerTask; string twitchChannelId = server.TwitchChannel; RestGuildUser user = null; if (getUserTask != null) { user = await getUserTask; } if (user != null && !string.IsNullOrEmpty(server?.TwitchLiveRoleId)) { //We need to update the role IRole twitchLiveRole = guild.GetRole(ulong.Parse(server.TwitchLiveRoleId)); await user.AddRoleAsync(twitchLiveRole); } if (!string.IsNullOrEmpty(twitchChannelId)) { //We post updates to the channel, so now we need to see if we've already posted. string streamUrl = "https://twitch.tv/" + t.ChannelName; DateTimeOffset streamStartedUTC = streamStatus.started_at; RestTextChannel channel = await guild.GetTextChannelAsync(ulong.Parse(twitchChannelId)); //Find whether or not we've selected a message ulong lastMessageId = 0; bool sendMessage = true; while (true) { IAsyncEnumerable <IReadOnlyCollection <RestMessage> > messagesUnflattened = lastMessageId == 0 ? channel.GetMessagesAsync(100) : channel.GetMessagesAsync(lastMessageId, Direction.Before, 100); List <RestMessage> messages = (await messagesUnflattened.FlattenAsync()).ToList(); var myMessages = messages.Where(m => m.Author.Id == _client.CurrentUser.Id && m.Timestamp > streamStartedUTC && m.Content.Contains(streamUrl)).ToList(); if (myMessages.Any()) { //Already sent message. We don't need to send it again sendMessage = false; break; } else { if (messages.Last().Timestamp < streamStartedUTC) { //We're past when the stream started break; } } lastMessageId = messages.Last().Id; } if (sendMessage) { //We still need to send the message string stringToSend = ""; if (user != null && String.IsNullOrEmpty(user?.Nickname)) { stringToSend += !String.IsNullOrEmpty(user.Nickname) ? user.Nickname : user.Username; } else { stringToSend += t.ChannelName; } stringToSend += " is now live at " + streamUrl; await channel.SendMessageAsync(stringToSend); } } } }