/// <summary> /// Deletes a roleplay and its associated channel, if any. /// </summary> /// <param name="roleplay">The roleplay.</param> /// <returns>A deletion result which may or may not have succeeded.</returns> public async Task <DeleteEntityResult> DeleteRoleplayAsync(Roleplay roleplay) { var guild = await _client.GetGuildAsync((ulong)roleplay.Server.DiscordID); if (guild is null) { return(DeleteEntityResult.FromError("Could not retrieve the associated guild.")); } if (roleplay.DedicatedChannelID.HasValue) { var deleteChannel = await _dedicatedChannels.DeleteChannelAsync(guild, roleplay); if (!deleteChannel.IsSuccess) { return(deleteChannel); } } var deleteRoleplay = await _roleplays.DeleteRoleplayAsync(roleplay); if (!deleteRoleplay.IsSuccess) { return(deleteRoleplay); } return(DeleteEntityResult.FromSuccess()); }
public async Task SendMessage(string message) { RestGuild guild = (RestGuild)await _client.GetGuildAsync(225374061386006528); RestTextChannel channel = await guild.GetTextChannelAsync(718854497245462588); await channel.SendMessageAsync(message); }
public async Task <IReadOnlyList <PermissionGroup> > GetPermissionGroups(ulong userId, ulong?guildId) { if (!guildId.HasValue) { return(GetDefaultPermissions(await _client.GetUserAsync(userId))); } var user = await _client.GetGuildUserAsync(userId, guildId.Value); var guild = await _client.GetGuildAsync(guildId.Value); return(await GetPermissionGroups(user, guild)); }
public async Task PingChannel(ulong guildId, string channelName, string message) { IGuild guild = await _client.GetGuildAsync(guildId); if (guild == null) { throw new Exception(string.Format("Guild {0} was not found", guildId)); } var channel = await guild.GetChannelByName <IMessageChannel>(channelName); if (channel == null) { throw new Exception(string.Format("Channel {0} was not found on guild {1}", channelName, guild.Name)); } await PingChannel(channel, message); }
private async Task <bool> RemoveFromRole(ulong userId, ulong guildId, ulong roleId) { try { if (!((await _discord.GetGuildAsync(guildId)) is SocketGuild guild) || !((await _discord.GetUserAsync(userId)) is SocketGuildUser user)) { _logger.LogInformation($"User {userId} or guild {guildId} does not exist."); return(true); } var role = guild.Roles.SingleOrDefault(a => a.Id == roleId); if (role == null) { _logger.LogInformation($"Role {roleId} does not exist in guild {guildId}"); return(true); } await user.RemoveRoleAsync(role); _logger.LogInformation($"User {userId} was removed from role {roleId} in guild {guildId}"); return(true); } catch (Exception ex) { _logger.LogCritical(ex, $"Unable to remove user {userId} form role {roleId} in guild {guildId}"); return(false); } }
public async Task ExecuteGiveaway(GiveawayEntry entry, ulong serverId) { IGuild guild = await m_client.GetGuildAsync(serverId); ServerEntry server = m_db.GetServerEntry(serverId); ITextChannel channel = await guild.GetTextChannelAsync(entry.ChannelId); IUserMessage message = await channel.GetMessageAsync(entry.ReactionMessageId) as IUserMessage; var asyncparticipants = message.GetReactionUsersAsync(new Emoji(server.GiveawayReactionEmote), int.MaxValue); IEnumerable <IUser> users = await asyncparticipants.FlattenAsync(); List <IUser> participants = users.Where(user => user.Id != m_client.CurrentUser.Id).ToList(); List <IUser> winners = new List <IUser>(); if (participants.Count <= 0) { await channel.SendMessageAsync($"No one participated for {entry.Content}"); } else { for (int i = 0; i < entry.Count; i++) { IUser winner; do { winner = participants[m_random.Next(0, participants.Count)]; } while(winners.Contains(winner) && entry.Count < participants.Count); winners.Add(winner); } await channel.SendMessageAsync($"{string.Join(' ', winners.Select(winner => winner.Mention))} won **{entry.Content}**!"); } }
public async Task ExecuteCommandAsync(IDiscordClient client, SocketMessage socketMessage) { try { var command = GetCommand(socketMessage.Content); var services = provider.GetServices <ICommandService>(); var filteredServices = services.Where(s => s.ImplementedCommands.Any(c => c.name == command)).ToArray(); var args = new ExecuteCommandArgs() { Command = command, Client = client, OurGuild = await client.GetGuildAsync(this.serverId), Message = socketMessage }; if (filteredServices.Length == 0) { args.IsCustom = true; filteredServices = services.Where(s => s.CanExecuteCustomCommand).ToArray(); } await Task.WhenAll(filteredServices.Select(s => s.ExecuteCommand(args)).ToArray()); } catch (Exception ex) { (socketMessage.Channel as IMessageChannel)?.SendMessageAsync($"Произошла ошибка: {ex.Message}"); } }
public async Task OnGetAsync() { var guilds = await _userRepository.UsersGuildsAsync(UserId).ConfigureAwait(false); var ownerGuilds = new List <ulong>(); foreach (var guild in guilds) { if (await IsGuildOwnerAsync(UserId, guild).ConfigureAwait(false)) { ownerGuilds.Add(guild); } } Settings = await _settingsRepository.GetServerSettingsAsync(ownerGuilds).ConfigureAwait(false); Roles = new Dictionary <ulong, List <IRole> >(); TextChannels = new Dictionary <ulong, List <ITextChannel> >(); foreach (var guildId in Settings.Keys) { var guild = await _client.GetGuildAsync(guildId).ConfigureAwait(false); Roles.Add(guildId, guild.Roles.ToList()); TextChannels.Add(guildId, (await guild.GetChannelsAsync().ConfigureAwait(false)).OfType <ITextChannel>().ToList()); } }
private async Task <bool> IsProtectedByFilter(IMessage message, AutoModerationConfig autoModerationConfig) { if (_config.GetSiteAdmins().Contains(message.Author.Id)) { return(true); } IGuild guild = await _client.GetGuildAsync((message.Channel as ITextChannel).Guild.Id); IGuildUser member = await guild.GetUserAsync(message.Author.Id); if (member == null) { return(false); } if (member.Guild.OwnerId == member.Id) { return(true); } if (member.RoleIds.Any(x => _guildConfig.ModRoles.Contains(x) || _guildConfig.AdminRoles.Contains(x) || autoModerationConfig.IgnoreRoles.Contains(x))) { return(true); } return(autoModerationConfig.IgnoreChannels.Contains((message.Channel as ITextChannel).Id)); }
public async Task ProcessMessage(IMessage message, CancellationToken token) { const string MessageLinkRegex = "/channels/(?<guildId>[0-9]*)/(?<channelId>[0-9]*)/(?<messageId>[0-9]*)"; var regex = new Regex(MessageLinkRegex); var match = regex.Match(message.Content); if (!match.Success) { return; } var guildId = ulong.Parse(match.Groups["guildId"].Value); var channelId = ulong.Parse(match.Groups["channelId"].Value); var messageId = ulong.Parse(match.Groups["messageId"].Value); var guild = await discordClient.GetGuildAsync(guildId, options : token.ToRequestOptions()); var channel = (IMessageChannel)await guild.GetChannelAsync(channelId, options : token.ToRequestOptions()); var quotedMessage = await channel.GetMessageAsync(messageId, options : token.ToRequestOptions()); if (message.Channel.Id != quotedMessage.Channel.Id && !quotedMessage.Channel.IsPublicChannel()) { return; } await message.Channel.SendMessageAsync(string.Empty, false, quotedMessage.QuoteMessage(message.Author), token.ToRequestOptions()); }
private async Task PostMessage() { var guild = await _discordClient.GetGuildAsync(368117880547573760, CacheMode.AllowDownload, new RequestOptions { CancelToken = _tokenSource.Token }); if (guild == null) { return; } var channel = await guild.GetTextChannelAsync(845981918130733106, CacheMode.AllowDownload, new RequestOptions { CancelToken = _tokenSource.Token }); if (channel == null) { return; } if (!_messageQueue.TryDequeue(out DiscordLogMessage logMessage)) { return; } string text = $"{_logLevelEmoji[logMessage.Level]} `{logMessage.Category}` {logMessage.Message}"; if (logMessage.Exception != null) { text += "```\n" + logMessage.Exception.ToString().Truncate(1024) + "\n```"; } await channel.SendMessageAsync(text, embed : logMessage.AssociatedMessage?.QuoteMessage(), options : new RequestOptions { CancelToken = _tokenSource.Token }); }
public async Task GetProfileDataAsync(ProfileDataRequestContext context) { if (context.Caller == IdentityServerConstants.ProfileDataCallers.UserInfoEndpoint) { var accessToken = _protector.Unprotect(context.Subject.FindFirstValue("discord")); var user = await _discord.GetUserAsync(accessToken); var userGuilds = await _discord.GetUserGuildsAsync(accessToken); var mutualGuilds = userGuilds.Where(userGuild => _bot.GetGuildAsync(ulong.Parse(userGuild.Id, CultureInfo.InvariantCulture)).Result != null); var mutualGuildsMap = new Dictionary <string, string>(); foreach (var guild in mutualGuilds) { mutualGuildsMap.Add(guild.Name, $"{guild.Id}:{guild.Permissions}:{guild.Owner}:{guild.Icon}"); } var serializerOptions = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, IgnoreNullValues = true }; context.IssuedClaims.Add(new Claim("user", JsonSerializer.Serialize(user, serializerOptions), "json")); context.IssuedClaims.Add(new Claim("user_guilds", JsonSerializer.Serialize(mutualGuildsMap, serializerOptions), "json")); } else if (context.Caller == IdentityServerConstants.ProfileDataCallers.ClaimsProviderAccessToken) { var accessToken = context.Subject.FindFirstValue("discord"); context.IssuedClaims.Add(new Claim("discord", _protector.Protect(accessToken))); } }
public async Task <Dictionary <IUser, string> > GetTrackerUrls( ulong guildId, ulong authorId, string channelName, string message) { IGuild guild = await _client.GetGuildAsync(guildId); if (guild == null) { throw new Exception(string.Format("Guild {0} was not found", guildId)); } var author = await guild.GetUserAsync(authorId); if (author == null) { throw new Exception(string.Format("User {0} was not found", authorId)); } var channel = await guild.GetChannelByName <IMessageChannel>(channelName); if (channel == null) { throw new Exception(string.Format("Channel {0} was not found on guild {1}", channelName, guild.Name)); } return(await GetTrackerUrls(author, channel, message)); }
/// <summary> /// Sends the text to the specified guild's channel using a connected Discord client /// </summary> /// <param name="client">Connected Discord Client connection</param> /// <param name="guildID">Id of the Discord guild</param> /// <param name="channelID">Id of the Discord channel</param> /// <param name="text">Text to post</param> public static async Task <RestUserMessage> SendChannelMessageAsync(IDiscordClient client, ulong guildID, ulong channelID, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null) { var guild = await(client?.GetGuildAsync(guildID)).ConfigureAwait(false); var channel = await(guild?.GetChannelAsync(channelID)).ConfigureAwait(false) as SocketTextChannel; return(await(channel?.SendMessageAsync(text, isTTS, embed, options)).ConfigureAwait(false)); }
public async Task <IActionResult> ListMyRoles(ulong guildId) { var guild = await _client.GetGuildAsync(guildId); if (guild == null) { throw new GuildNotFoundException(); } var user = await guild.GetUserAsync(User.GetId()); if (user == null) { throw new UserNotFoundException(); } return(Content(user.RoleIds)); }
#pragma warning disable IDE0060 // Remove unused parameter public async Task <ActionResult <IEnumerable <MyRole> > > TryGetRolesForServerFromCache(string accessToken, string serverId) #pragma warning restore IDE0060 // Remove unused parameter { //TODO: delete when it's time List <IRole> roles = new List <IRole>((await _client.GetGuildAsync(ulong.Parse(serverId))).Roles.ToList()); List <MyRole> myRoles = new List <MyRole>(); foreach (IRole r in roles) { myRoles.Add(new MyRole() { name = r.Name, color = r.Color.GetHashCode(), position = r.Position, id = r.Id.ToString(), }); } return(myRoles); }
public async Task <IActionResult> ListRoles(ulong guildId) { var guild = await _client.GetGuildAsync(guildId); if (guild == null) { throw new GuildNotFoundException(); } return(Content(guild.Roles.Select(c => new ApiGuildRole(c.Id, c.Name)))); }
/// <summary> /// Updates the name of the roleplay channel. /// </summary> /// <param name="roleplay">The roleplay.</param> /// <returns>A modification result which may or may not have succeeded.</returns> public async Task <ModifyEntityResult> UpdateChannelNameAsync(Roleplay roleplay) { var guild = await _client.GetGuildAsync((ulong)roleplay.Server.DiscordID); if (guild is null) { return(ModifyEntityResult.FromError("Could not retrieve a valid guild.")); } var getChannel = await GetDedicatedChannelAsync(guild, roleplay); if (!getChannel.IsSuccess) { return(ModifyEntityResult.FromError(getChannel)); } var channel = getChannel.Entity; await channel.ModifyAsync(m => m.Name = $"{roleplay.Name}-rp"); return(ModifyEntityResult.FromSuccess()); }
public async Task <IActionResult> ListChannels(ulong guildId) { var guild = await _client.GetGuildAsync(guildId); if (guild == null) { throw new GuildNotFoundException(); } var channels = await guild.GetTextChannelsAsync(); return(Content(channels.Select(c => new ApiGuildChannel(c.Id, c.Name)))); }
public async Task <Quote> RandomQuoteAsync() { var dbQuote = await _botContext.Quotes .Include(q => q.ServerUser.User) .Include(q => q.ServerUser.Server) .OrderBy(r => Guid.NewGuid()) .FirstOrDefaultAsync().ConfigureAwait(false); if (dbQuote == null) { return(null); } var server = await _discordClient.GetGuildAsync((ulong)dbQuote.ServerUser.Server.DiscordGuildId).ConfigureAwait(false); var user = await server.GetUserAsync((ulong)dbQuote.ServerUser.User.DiscordUserId).ConfigureAwait(false); return(new Quote { Author = user, Content = dbQuote.QuoteBody }); }
public async Task Broadcast(Embed embed) { await foreach (var subscription in _subscriptions.GetSubscriptions()) { var guild = await _client.GetGuildAsync(subscription.Guild); if (guild == null) { continue; } var channel = await guild.GetTextChannelAsync(subscription.Channel); if (channel == null) { continue; } await channel.SendMessageAsync(embed : embed); await Task.Delay(100); } }
public async IAsyncEnumerable <IUserMessage> Broadcast(Embed embed) { var subs = await _subscriptions.GetSubscriptions().ToArrayAsync(); foreach (var subscription in subs) { IUserMessage?r = null; try { var guild = await _client.GetGuildAsync(subscription.Guild); if (guild == null) { continue; } var channel = await guild.GetTextChannelAsync(subscription.Channel); if (channel == null) { continue; } r = await channel.SendMessageAsync(embed : embed); } catch (Exception e) { Console.WriteLine(e); } if (r != null) { yield return(r); } await Task.Delay(100); } }
/// <summary> /// Deletes the character role for the given Discord role. /// </summary> /// <param name="role">The character role.</param> /// <param name="ct">The cancellation token in use.</param> /// <returns>A deletion result which may or may not have succeeded.</returns> public async Task <DeleteEntityResult> DeleteCharacterRoleAsync ( CharacterRole role, CancellationToken ct = default ) { var currentOwnersWithRole = await _database.Characters.ServerScopedServersideQueryAsync ( role.Server, q => q .Where(c => c.Role == role) .Where(c => c.IsCurrent) .Select(c => c.Owner) .Distinct(), ct ); _database.CharacterRoles.Remove(role); var guild = await _client.GetGuildAsync((ulong)role.Server.DiscordID); if (guild is null) { return(DeleteEntityResult.FromError("Could not retrieve the guild the role was on.")); } foreach (var characterOwner in currentOwnersWithRole) { var owner = await guild.GetUserAsync((ulong)characterOwner.DiscordID); var discordRole = guild.GetRole((ulong)role.DiscordID); if (owner is null || discordRole is null) { return(DeleteEntityResult.FromError("Failed to get the owner or role.")); } var removeRole = await _discord.RemoveUserRoleAsync(owner, discordRole); if (!removeRole.IsSuccess) { return(DeleteEntityResult.FromError(removeRole)); } } await _database.SaveChangesAsync(ct); return(DeleteEntityResult.FromSuccess()); }
public async Task <ServerSettings> GetServerSettingsAsync(ulong discordGuildId) { var settings = await GetDbServerSettingsAsync(discordGuildId).ConfigureAwait(false); return(new ServerSettings { GuildName = (await _client.GetGuildAsync(discordGuildId).ConfigureAwait(false)).Name, CommandPrefix = settings.CommandPrefix, CustomCommandPrefix = settings.CustomCommandPrefix, ModeratorRoleId = (ulong?)settings.ModeratorRoleId, WelcomeChannel = (ulong?)settings.WelcomeChannel, LeaveChannel = (ulong?)settings.LeaveChannel, BanChannel = (ulong?)settings.BanChannel, KickChannel = (ulong?)settings.KickChannel, BlockedWords = settings.BlockedWords }); }
/// <summary> /// Contacts the Discord API to verify that the user is administrator of a given guild. /// </summary> /// <param name="client">Discord client to check admin status of.</param> /// <param name="userId">The Id of user, to check admin status of.</param> /// <param name="guildId">The Id of guild to check if user is admin of.</param> /// <param name="modRoleId">Id of role which moderates a resource.</param> /// <returns>True if user was confirmed to be admin of a given guild.</returns> public static async Task <bool> ValidateInRoleAsync(this IDiscordClient client, ulong userId, ulong guildId, ulong modRoleId) { var guild = await client.GetGuildAsync(guildId); if (guild == null) { return(false); } var user = await guild.GetUserAsync(userId); if (user == null) { return(false); } return(user.RoleIds.Any(r => r == modRoleId)); }
/// <summary> /// Contacts the Discord API to verify that the user is administrator of a given guild. /// </summary> /// <param name="client">Discord client to check admin status of.</param> /// <param name="userId">The Id of user, to check admin status of.</param> /// <param name="guildId">The Id of guild to check if user is admin of.</param> /// <returns>True if user was confirmed to be admin of a given guild.</returns> public static async Task <bool> ValidateGuildAdminAsync(this IDiscordClient client, ulong userId, ulong guildId) { var guild = await client.GetGuildAsync(guildId); if (guild == null) { return(false); } var user = await guild.GetUserAsync(userId); if (user == null) { return(false); } return(user.GuildPermissions.Administrator); }
/// <summary> /// Contacts the Discord API to verify that the user is administrator of a given guild. /// </summary> /// <param name="client">Discord client to check admin status of.</param> /// <param name="userId">The Id of user, to check admin status of.</param> /// <param name="guildId">The Id of guild to check if user is admin of.</param> /// <param name="modRoleId">Id of role which moderates a resource.</param> /// <returns>True if user was confirmed to be admin of a given guild.</returns> public static async Task <bool> ValidateResourceModeratorAsync(this IDiscordClient client, ulong userId, ulong guildId, ulong?modRoleId) { var guild = await client.GetGuildAsync(guildId); if (guild == null) { return(false); } var user = await guild.GetUserAsync(userId); if (user == null) { return(false); } // Check if user has moderator role, or is administrator. // Do not iterate thru roles if modrole is undefined. return(modRoleId != null && user.RoleIds.Any(r => r == modRoleId) || user.GuildPermissions.Administrator); }
private async Task UpdateTwitchStatusChannelsAsync() { var twitchRepository = Config.ServiceProvider.GetService <ITwitchRepository>(); var twitchUpdateChannels = await twitchRepository.AllTwitchUpdateChannelsAsync().ConfigureAwait(false); foreach (var twitchChannel in twitchUpdateChannels) { var isStreaming = await _twitchClient.IsStreamingAsync(twitchChannel.TwitchLoginName) .ConfigureAwait(false); if (twitchChannel.LastStatus == isStreaming) { continue; } await twitchRepository .UpdateLastStatusAsync(twitchChannel.GuildId, twitchChannel.TwitchLoginName, isStreaming) .ConfigureAwait(false); if (!isStreaming) { continue; } while (!_ready) { await Task.Delay(500).ConfigureAwait(false); } var guild = await _client.GetGuildAsync((ulong)twitchChannel.GuildId).ConfigureAwait(false); var channel = await guild.GetChannelAsync((ulong)twitchChannel.UpdateChannel) .ConfigureAwait(false); var embed = await GetTwitchStreamEmbedAsync(twitchChannel.TwitchLoginName).ConfigureAwait(false); (channel as ITextChannel)?.SendMessageAsync(string.Empty, embed: embed); } }
/// <summary> /// Validates if the user has access write access to the guild bank. /// </summary> /// <param name="bank">Bank to check access of.</param> /// <param name="userId">Id of user.</param> /// <returns>Corresponding HTTP error result. null if user has write access.</returns> private async Task <bool> ValidateWriteAccess(GuildBank bank, ulong userId) { // Get the guild and check if it is present. var guild = await _client.GetGuildAsync(bank.GuildId); if (guild == null) { throw new GuildNotFoundException(); } // Check if user even exists in the guild. var user = await guild.GetUserAsync(userId); if (user == null) { throw new UserNotFoundException(); } // Check if user has write access to the bank. return(user.RoleIds.Any(r => r == bank.ModeratorRoleId) || user.GuildPermissions.Administrator); }
public async Task <IActionResult> ListBanks(ulong guildId) { var guild = await _client.GetGuildAsync(guildId); if (guild == null) { throw new GuildNotFoundException(); } var user = await guild.GetUserAsync(User.GetId()); if (user == null) { throw new UserNotFoundException(); } var banks = await _bank.GetGuildBanksAsync(guildId, o => o.Include(b => b.Contents)); var outBanks = banks.Select(b => new ApiGuildBank(b)); return(Content(outBanks)); }