public async Task <ITextChannel> CreateChannelsForFinals( ISelfUser botUser, ITournamentState state, Game finalsGame, int finalsRoundNumber, int roomIndex) { Verify.IsNotNull(this.Guild, "guild"); Verify.IsNotNull(state, nameof(state)); Verify.IsNotNull(finalsGame, nameof(finalsGame)); TournamentRoles roles = this.GetTournamentRoles(state); ICategoryChannel finalsCategoryChannel = await this.Guild.CreateCategoryAsync("Finals"); ITextChannel channel = await this.CreateTextChannelAsync( botUser, finalsCategoryChannel, finalsGame, roles, finalsRoundNumber, roomIndex); state.ChannelIds = state.ChannelIds .Concat(new ulong[] { channel.Id }) .Concat(new ulong[] { finalsCategoryChannel.Id }); return(channel); }
/// <summary> /// Constructs a new <see cref="MutePersistingHandler"/> object with the given injected dependencies. /// </summary> /// <param name="moderationService">A moderation service to interact with the infractions system.</param> /// <param name="botUser">The Discord user that the bot is running as.</param> public MutePersistingHandler( IModerationService moderationService, ISelfUser botUser) { _moderationService = moderationService; _botUser = botUser; }
public MockMessageChannel(ISelfUser bot, string name = null) { Bot = bot; var random = new Random(); Id = (ulong)random.Next(0, int.MaxValue); Name = name; }
public IDiscordClient CreateClient() { Mock <IDiscordClient> mockClient = new Mock <IDiscordClient>(); ISelfUser selfUser = CreateSelfUser(); mockClient.Setup(o => o.CurrentUser).Returns(selfUser); return(mockClient.Object); }
public async Task statusAsync() { ISelfUser SelfUser = Context.Client.CurrentUser; EmbedAuthorBuilder eab = new EmbedAuthorBuilder { IconUrl = SelfUser.GetAvatarUrl(), Name = SelfUser.Username }; EmbedBuilder builder = new EmbedBuilder(); builder.WithAuthor(eab); builder.WithDescription(SelfUser.Username + " Statistics"); TimeSpan startTime = (DateTime.Now - Process.GetCurrentProcess().StartTime); DiscordShardedClient client = Context.Client as DiscordShardedClient; SocketSelfUser SocketSelf = Context.Client.CurrentUser as SocketSelfUser; string status = "Online"; switch (SocketSelf.Status) { case UserStatus.Offline: status = "Offline"; break; case UserStatus.Online: status = "Online"; break; case UserStatus.Idle: status = "Idle"; break; case UserStatus.AFK: status = "AFK"; break; case UserStatus.DoNotDisturb: status = "Do Not Disturb"; break; case UserStatus.Invisible: status = "Invisible/Offline"; break; } string assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); int fixedCmdGlobalCount = GlobalVars.CommandExecutions + 1; int fixedCmdGlobalCount_Servers = GlobalVars.CommandExecutions_Servers + 1; int fixedCmdGlobalCount_DMs = GlobalVars.CommandExecutions_DMs + 1; builder.AddField("Bot Uptime: ", startTime.ToReadableString(), true); builder.AddField("Server Uptime: ", GlobalVars.SystemUpTime().ToReadableString(), true); builder.AddField("Usercount: ", (await userService.GetUserCountAsync()).ToString(), true); builder.AddField("Servercount: ", client.Guilds.Count, true); builder.AddField("Commands used since bot start: ", fixedCmdGlobalCount); builder.AddField("Commands in servers: ", fixedCmdGlobalCount_Servers); builder.AddField("Commands in DMs ", fixedCmdGlobalCount_DMs); builder.AddField("Bot status: ", status, true); builder.AddField("Latency: ", client.Latency + "ms", true); builder.AddField("Shards: ", client.Shards.Count, true); builder.AddField("Bot version: ", assemblyVersion, true); await Context.Channel.SendMessageAsync("", false, builder.Build()).ConfigureAwait(false); }
public ModuleA(IDiscordClient c, ISelfUser s) { if (!(c is DiscordSocketClient)) { throw new InvalidOperationException("This module requires a DiscordSocketClient"); } client = c as DiscordSocketClient; self = s; }
/// <inheritdoc /> public Task OnAuthenticatedAsync(ISelfUser self) { CurrentGuildId = null; CurrentUserId = self.Id; CurrentClaims = Enum.GetValues(typeof(AuthorizationClaim)) .Cast <AuthorizationClaim>() .ToHashSet(); return(Task.CompletedTask); }
/// <summary> /// Constructs a new <see cref="ModerationInvitePurgingHandler"/> object, with the given injected dependencies. /// </summary> /// <param name="designatedChannelService"></param> /// <param name="authorizationService"></param> /// <param name="moderationService"></param> /// <param name="botUser">The Discord user that the bot is running as.</param> public ModerationInvitePurgingHandler( IDesignatedChannelService designatedChannelService, IAuthorizationService authorizationService, IModerationService moderationService, ISelfUser botUser) { _designatedChannelService = designatedChannelService; _authorizationService = authorizationService; _moderationService = moderationService; _botUser = botUser; }
public ModerationService( IAuthorizationService authorizationService, IDesignatedRoleService designatedRoleService, IInfractionRepository infractionRepository, ISelfUser selfUser, IUserService userService) { AuthorizationService = authorizationService; DesignatedRoleService = designatedRoleService; InfractionRepository = infractionRepository; SelfUser = selfUser; UserService = userService; }
public async Task DmAsync(string user, [Remainder] string dm = "") { IUser User = await Context.Client.GetUserAsync(ulong.Parse(user)); IDMChannel Dm = await User.GetOrCreateDMChannelAsync(); ISelfUser client = Context.Client.CurrentUser; var embed = new EmbedBuilder(); embed.WithAuthor($"Owner of {client}"); embed.WithThumbnailUrl(client.GetAvatarUrl()); embed.WithColor(Color.DarkTeal); embed.WithDescription(dm); embed.WithFooter("You can reply to this message with =>contact"); await Dm.SendMessageAsync(embed : embed.Build()); }
private async Task LogoutInternalAsync() { if (LoginState == LoginState.LoggedOut) { return; } LoginState = LoginState.LoggingOut; await ApiClient.LogoutAsync().ConfigureAwait(false); await OnLogoutAsync().ConfigureAwait(false); CurrentUser = null; LoginState = LoginState.LoggedOut; await _loggedOutEvent.InvokeAsync().ConfigureAwait(false); }
public static async Task <bool> changeName(IDiscordClient client, string name) { ISelfUser self = client.CurrentUser; try { await self.ModifyAsync(x => { x.Username = name; }); return(true); } catch { return(false); } }
public static async Task <Model> ModifyAsync(ISelfUser user, BaseDiscordClient client, Action <SelfUserProperties> func, RequestOptions options) { SelfUserProperties args = new SelfUserProperties(); func(args); ModifyCurrentUserParams apiArgs = new API.Rest.ModifyCurrentUserParams { Avatar = args.Avatar.IsSpecified ? args.Avatar.Value?.ToModel() : Optional.Create <ImageModel?>(), Username = args.Username }; if (!apiArgs.Avatar.IsSpecified && user.AvatarId != null) { apiArgs.Avatar = new ImageModel(user.AvatarId); } return(await client.ApiClient.ModifySelfAsync(apiArgs, options).ConfigureAwait(false)); }
public static async Task <bool> changeProfile(IDiscordClient client, string path) { ISelfUser self = client.CurrentUser; try { Image image = new(path); await self.ModifyAsync(x => { x.Avatar = image; }); return(true); } catch { return(false); } }
public async Task CreateChannelsForRebracket( ISelfUser botUser, ITournamentState state, IEnumerable <Round> rounds, int startingRoundNumber) { Verify.IsNotNull(this.Guild, "guild"); Verify.IsNotNull(state, nameof(state)); Verify.IsNotNull(rounds, nameof(rounds)); TournamentRoles roles = this.GetTournamentRoles(state); ITextChannel[] textChannels = await this.CreateTextChannelsForRounds( botUser, rounds, roles, startingRoundNumber); IEnumerable <ulong> textCategoryChannelIds = GetCategoryChannelIds(textChannels); state.ChannelIds = state.ChannelIds .Concat(textChannels.Select(channel => channel.Id)) .Concat(textCategoryChannelIds); }
public static void SetUserAgent(ISelfUser self) { StringBuilder userAgent = new(); userAgent.Append(self.Username); userAgent.Append('-'); userAgent.Append(self.Discriminator); userAgent.Append('/'); userAgent.Append( Assembly .GetExecutingAssembly() .GetName() .Version .ToString() ); userAgent.Append(" (Discord.Net; +"); userAgent.Append(SkuldAppContext.Website); userAgent.Append(") DBots/"); userAgent.Append(self.Id); UAGENT = userAgent.ToString(); }
public async Task CreateChannelsForPrelims(ISelfUser botUser, ITournamentState state, TournamentRoles roles) { Verify.IsNotNull(this.Guild, "guild"); Verify.IsNotNull(state, nameof(state)); Verify.IsNotNull(roles, nameof(roles)); List <Task <IVoiceChannel> > createVoiceChannelsTasks = new List <Task <IVoiceChannel> >(); // We only need to go through the games for the first round to get all of the readers. Round firstRound = state.Schedule.Rounds.First(); Debug.Assert(firstRound.Games.Select(game => game.Reader.Name).Count() == firstRound.Games.Select(game => game.Reader.Name).Distinct().Count(), "All reader names should be unique."); ICategoryChannel voiceCategoryChannel = await this.Guild.CreateCategoryAsync( "Readers", options : RequestOptionsSettings.Default); foreach (Game game in firstRound.Games) { createVoiceChannelsTasks.Add( this.CreateVoiceChannelAsync(voiceCategoryChannel, game.Reader)); } IVoiceChannel[] voiceChannels = await Task.WhenAll(createVoiceChannelsTasks); // Create the text channels const int startingRoundNumber = 1; ITextChannel[] textChannels = await this.CreateTextChannelsForRounds( botUser, state.Schedule.Rounds, roles, startingRoundNumber); IEnumerable <ulong> textCategoryChannelIds = GetCategoryChannelIds(textChannels); state.ChannelIds = voiceChannels.Select(channel => channel.Id) .Concat(textChannels.Select(channel => channel.Id)) .Concat(new ulong[] { voiceCategoryChannel.Id }) .Concat(textCategoryChannelIds) .ToArray(); }
public async Task fmfeaturedAsync() { try { EmbedBuilder builder = new EmbedBuilder { Color = new Discord.Color(186, 0, 0) }; ISelfUser SelfUser = Context.Client.CurrentUser; builder.WithThumbnailUrl(SelfUser.GetAvatarUrl()); builder.AddField("Featured:", _timer.GetTrackString()); await Context.Channel.SendMessageAsync("", false, builder.Build()); this._logger.LogCommandUsed(Context.Guild?.Id, Context.Channel.Id, Context.User.Id, Context.Message.Content); } catch (Exception e) { _logger.LogError(e.Message, Context.Message.Content, Context.User.Username, Context.Guild?.Name, Context.Guild?.Id); await ReplyAsync("Unable to show the featured avatar on FMBot due to an internal error. The timer service cannot be loaded. Please wait for the bot to fully load."); } }
private async Task <ITextChannel[]> CreateTextChannelsForRounds( ISelfUser botUser, IEnumerable <Round> rounds, TournamentRoles roles, int startingRoundNumber) { Verify.IsNotNull(this.Guild, "guild"); Verify.IsNotNull(rounds, nameof(rounds)); Verify.IsNotNull(roles, nameof(roles)); List <Task <ITextChannel> > createTextChannelsTasks = new List <Task <ITextChannel> >(); List <ulong> textCategoryChannelIds = new List <ulong>(); int roundNumber = startingRoundNumber; foreach (Round round in rounds) { int roomNumber = 0; ICategoryChannel roundCategoryChannel = await this.Guild.CreateCategoryAsync( $"Round {roundNumber}", options : RequestOptionsSettings.Default); textCategoryChannelIds.Add(roundCategoryChannel.Id); foreach (Game game in round.Games) { createTextChannelsTasks.Add(this.CreateTextChannelAsync( botUser, roundCategoryChannel, game, roles, roundNumber, roomNumber)); roomNumber++; } roundNumber++; } ITextChannel[] textChannels = await Task.WhenAll(createTextChannelsTasks); return(textChannels); }
public async Task fmfullhelpAsync() { string prefix = ConfigData.Data.CommandPrefix; ISelfUser SelfUser = Context.Client.CurrentUser; string description = null; int length = 0; EmbedBuilder builder = new EmbedBuilder(); foreach (ModuleInfo module in _service.Modules.OrderByDescending(o => o.Commands.Count()).Where(w => !w.Name.Contains("SecretCommands") && !w.Name.Contains("OwnerCommands") && !w.Name.Contains("AdminCommands") && !w.Name.Contains("GuildCommands"))) { foreach (CommandInfo cmd in module.Commands) { PreconditionResult result = await cmd.CheckPreconditionsAsync(Context); if (result.IsSuccess) { if (!string.IsNullOrWhiteSpace(cmd.Summary)) { description += $"{prefix}{cmd.Aliases.First()} - {cmd.Summary}\n"; } else { description += $"{prefix}{cmd.Aliases.First()}\n"; } } } if (description.Length < 1024) { builder.AddField (module.Name + (module.Summary != null ? " - " + module.Summary : ""), description != null ? description : ""); } length += description.Length; description = null; if (length < 1990) { await Context.User.SendMessageAsync("", false, builder.Build()).ConfigureAwait(false); builder = new EmbedBuilder(); length = 0; } } builder = new EmbedBuilder { Title = "Additional information", }; builder.AddField("Quick tips", "- Be sure to use 'help' after a command name to see the parameters. \n" + "- Chart sizes range from 3x3 to 10x10 \n" + "- Most commands have no required parameters"); builder.AddField("Setting your username", "Use `" + prefix + "fmset 'username' 'embedfull/embedmini/textfull/textmini'` to set your global LastFM username. " + "The last parameter means the mode that your embed will be"); builder.AddField("Making album charts", "`" + prefix + "fmchart '3x3-10x10' 'weekly/monthly/yearly/overall' 'notitles/titles' 'user'`"); builder.AddField("Making artist charts", "`" + prefix + "fmartistchart '3x3-10x10' 'weekly/monthly/yearly/overall' 'notitles/titles' 'user'`"); builder.AddField("Setting the default server settings", "Please note that server defaults are a planned feature. \n" + "Only users with the 'Ban Members' permission or admins can use this command. \n" + "`" + prefix + "fmserverset 'embedfull/embedmini/textfull/textmini' 'Weekly/Monthly/Yearly/AllTime'`"); builder.WithFooter("Still need help? Join the FMBot Discord Server: https://discord.gg/srmpCaa"); await Context.User.SendMessageAsync("", false, builder.Build()).ConfigureAwait(false); if (!guildService.CheckIfDM(Context)) { await Context.Channel.SendMessageAsync("Check your DMs!").ConfigureAwait(false); } }
internal async Task UpdateFriend(CMsgClientPersonaState persona) { var users = new List <(IUser Before, IUser After)>(); var clans = new List <(IClan Before, IClan After)>(); ISelfUser currentBefore = null; ISelfUser currentAfter = null; await _slim.WaitAsync(); try { var flag = (ClientPersonaStateFlag)persona.status_flags; foreach (var friend in persona.friends) { SteamId friendId = friend.friendid; if (friendId == Client.SteamId) // that's us! { currentBefore = _currentUser; if (currentBefore is OfflineSelfUser) { currentAfter = SelfUser.Create(Client, friend, flag); } else { currentAfter = (currentBefore as SelfUser).WithState(friend, flag); } } else if (friendId.IsClan) { IClan before; IClan after; before = _clans[friend.friendid]; if (before is UnknownUser) { after = Clan.Create(Client, before.Relationship, friend, flag); } else { after = (before as Clan).WithPersonaState(friend, flag); } _clans[after.Id] = after; clans.Add((before, after)); } else { IUser before; IUser after; before = _users[friend.friendid]; if (before is UnknownUser) { after = User.Create(Client, before.Relationship, friend, flag); } else { after = (before as User).WithState(friend, flag); } _users[after.Id] = after; users.Add((before, after)); } } } finally { _slim.Release(); } if (currentBefore != null || currentAfter != null) { _currentUser = currentAfter; await InvokeCurrentUserUpdated(currentBefore, currentAfter).ConfigureAwait(false); } await Task.WhenAll(users.Select(t => InvokeUserUpdated(t.Before, t.After)).Concat(clans.Select(t => InvokeClanUpdated(t.Before, t.After)))).ConfigureAwait(false); }
internal async Task InitCurrentUser(string personaName) { _currentUser = new OfflineSelfUser(Client, Client.SteamId, personaName); await InvokeCurrentUserUpdated(null, _currentUser).ConfigureAwait(false); }
private async Task InvokeCurrentUserUpdated(ISelfUser before, ISelfUser after) { await CurrentUserUpdated.InvokeAsync(this, new CurrentUserUpdatedEventArgs(before, after)).ConfigureAwait(false); }
/// <summary> /// Converts an existing <see cref="ISelfUser"/> to an abstracted <see cref="ISelfUser"/> value. /// </summary> /// <param name="selfUser">The existing <see cref="ISelfUser"/> to be abstracted.</param> /// <exception cref="ArgumentNullException">Throws for <paramref name="selfUser"/>.</exception> /// <returns>An <see cref="ISelfUser"/> that abstracts <paramref name="selfUser"/>.</returns> public static ISelfUser Abstract(this ISelfUser selfUser) => selfUser switch { null => throw new ArgumentNullException(nameof(selfUser)),
public MockTextChannel(ISelfUser user, IGuild guild, string name) : base(user, name) { Guild = guild; }
public MockDMChannel(ISelfUser bot, IUser user) : base(bot, $"{user.Username}'s DM") { Recipients = new IUser[] { user, bot }.ToImmutableArray(); Recipient = user; }
public CurrentUserUpdatedEventArgs(ISelfUser before, ISelfUser after) { Before = before; After = after; }
private async Task <ITextChannel> CreateTextChannelAsync( ISelfUser botUser, ICategoryChannel parent, Game game, TournamentRoles roles, int roundNumber, int roomNumber) { Verify.IsNotNull(this.Guild, "guild"); Verify.IsNotNull(parent, nameof(parent)); Verify.IsNotNull(game, nameof(game)); Verify.IsNotNull(roles, nameof(roles)); // The room and role names will be the same. this.Logger.Debug("Creating text channel for room {0} in round {1}", roomNumber, roundNumber); string name = GetTextRoomName(game.Reader, roundNumber); ITextChannel channel = await this.Guild.CreateTextChannelAsync( name, channelProps => { channelProps.CategoryId = parent.Id; }, RequestOptionsSettings.Default); this.Logger.Debug("Text channel for room {0} in round {1} created", roomNumber, roundNumber); // We need to add the bot's permissions first before we disable permissions for everyone. await channel.AddPermissionOverwriteAsync( botUser, PrivilegedOverwritePermissions, RequestOptionsSettings.Default); this.Logger.Debug("Adding permissions to text channel for room {0} in round {1}", roomNumber, roundNumber); await channel.AddPermissionOverwriteAsync( this.Guild.EveryoneRole, EveryonePermissions, RequestOptionsSettings.Default); await channel.AddPermissionOverwriteAsync( roles.DirectorRole, PrivilegedOverwritePermissions, RequestOptionsSettings.Default); if (roles.RoomReaderRoles.TryGetValue(game.Reader, out IRole readerRole)) { await channel.AddPermissionOverwriteAsync( readerRole, PrivilegedOverwritePermissions, RequestOptionsSettings.Default); } else { this.Logger.Warning("Could not find a reader role for a reader with ID {0}.", game.Reader?.Id); } List <Task> addTeamRolesToChannel = new List <Task>(); foreach (Team team in game.Teams) { if (!roles.TeamRoles.TryGetValue(team, out IRole role)) { this.Logger.Warning("Team {name} did not have a role defined.", team.Name); continue; } // TODO: Investigate if it's possible to parallelize this. Other attempts to do so (Task.WhenAll, // AsyncEnumerable's ParallelForEachAsync) have had bugs where roles sometimes aren't assigned to a // channel. Adding an await in the loop seems to be the only thing that await this.AddPermission(channel, role); } await Task.WhenAll(addTeamRolesToChannel); this.Logger.Debug("Added permissions to text channel for room {0} in round {1}", roomNumber, roundNumber); return(channel); }