示例#1
0
        /// <summary>
        /// Returns the Url of the Achievement Icon
        /// </summary>
        /// <param name="applicationId">Application ID of the icon</param>
        /// <param name="achievementId">Achievement ID</param>
        /// <param name="iconHash">Achievement Icon Hash</param>
        /// <param name="format">Format the icon is in</param>
        /// <returns>Url of the achievement icon</returns>
        /// <exception cref="ArgumentException">Throw if format is Gif</exception>
        public static string GetAchievementIconUrl(Snowflake applicationId, Snowflake achievementId, string iconHash, ImageFormat format = ImageFormat.Auto)
        {
            switch (format)
            {
            case ImageFormat.Auto:
            case ImageFormat.Jpg:
            case ImageFormat.Png:
            case ImageFormat.WebP:
                return($"{CdnUrl}/app-assets/{applicationId.ToString()}/achievements/{achievementId.ToString()}/icons/{iconHash}.{GetExtension(format, iconHash)}");

            default:
                throw new ArgumentException("ImageFormat is not valid for Achievement Icon. Valid types are (Auto, Png, Jpeg, WebP)", nameof(format));
            }
        }
示例#2
0
        /// <summary>
        /// Returns the applications asset icon url
        /// </summary>
        /// <param name="applicationId">Application ID of the icon</param>
        /// <param name="assetId">Asset ID for the application</param>
        /// <param name="format">Format the icon is in</param>
        /// <returns>Url of the application asset icon</returns>
        /// <exception cref="ArgumentException">Throw if format is Gif</exception>
        public static string GetApplicationAssetUrl(Snowflake applicationId, string assetId, ImageFormat format = ImageFormat.Auto)
        {
            switch (format)
            {
            case ImageFormat.Auto:
            case ImageFormat.Jpg:
            case ImageFormat.Png:
            case ImageFormat.WebP:
                return($"{CdnUrl}/app-assets/{applicationId.ToString()}/{assetId}.{GetExtension(format, assetId.ToString())}");

            default:
                throw new ArgumentException("ImageFormat is not valid for Application Asset. Valid types are (Auto, Png, Jpeg, WebP)", nameof(format));
            }
        }
示例#3
0
        /// <summary>
        /// Returns the Url of the User Banner
        /// </summary>
        /// <param name="userId">User ID for the Banner</param>
        /// <param name="userBanner">User Banner from user</param>
        /// <param name="format">Format the icon is in</param>
        /// <returns>Url of the User banner</returns>
        /// <exception cref="ArgumentException">Thrown if format is Gif</exception>
        public static string GetUserBanner(Snowflake userId, string userBanner, ImageFormat format = ImageFormat.Auto)
        {
            switch (format)
            {
            case ImageFormat.Auto:
            case ImageFormat.Jpg:
            case ImageFormat.Png:
            case ImageFormat.WebP:
                return($"{CdnUrl}/banners/{userId.ToString()}/{userBanner}.{GetExtension(format, userBanner)}");

            default:
                throw new ArgumentException("ImageFormat is not valid for Guild Banner. Valid types are (Auto, Png, Jpeg, WebP)", nameof(format));
            }
        }
示例#4
0
        /// <summary>
        /// Returns the Url to the Guild Icon
        /// </summary>
        /// <param name="guildId">Guild ID for the icon</param>
        /// <param name="guildIcon">Guild Icon from guild</param>
        /// <param name="format">Format the icon is in</param>
        /// <returns>Url of the guild icon</returns>
        public static string GetGuildIconUrl(Snowflake guildId, string guildIcon, ImageFormat format = ImageFormat.Auto)
        {
            switch (format)
            {
            case ImageFormat.Auto:
            case ImageFormat.Jpg:
            case ImageFormat.Png:
            case ImageFormat.WebP:
            case ImageFormat.Gif:
                return($"{CdnUrl}/icons/{guildId.ToString()}/{guildIcon}.{GetExtension(format, guildIcon)}");

            default:
                throw new ArgumentException("ImageFormat is not valid for Guild Icon. Valid types are (Auto, Png, Jpeg, WebP, Gif)", nameof(format));
            }
        }
示例#5
0
        public Button Build()
        {
            if (_handler is null)
            {
                throw new Exception("No handler");
            }

            var builtComponent = _buttonComponent with {
                CustomID = _snowflake.ToString()
            };
            var builtHandler = new ButtonHandler(_handler, _requiredPermission);

            return(new(_snowflake, builtComponent, builtHandler));
        }
    }
示例#6
0
        /// <summary>
        /// Returns the Url of the Guild Member avatar
        /// </summary>
        /// <param name="guildId">Guild ID of the Guild Member</param>
        /// <param name="userId">Discord User ID</param>
        /// <param name="memberAvatar">Guild Member avatar</param>
        /// <param name="format">Format the avatar is in</param>
        /// <returns>Url of the Guild Member avatar</returns>
        public static string GetGuildMemberAvatar(Snowflake guildId, Snowflake userId, string memberAvatar, ImageFormat format = ImageFormat.Auto)
        {
            switch (format)
            {
            case ImageFormat.Auto:
            case ImageFormat.Jpg:
            case ImageFormat.Png:
            case ImageFormat.WebP:
            case ImageFormat.Gif:
                return($"{CdnUrl}/guilds/{guildId.ToString()}/users/{userId.ToString()}/avatars/{memberAvatar}.{GetExtension(format, memberAvatar)}");

            default:
                throw new ArgumentException("ImageFormat is not valid for Guild Member Avatar. Valid types are (Auto, Png, Jpeg, WebP, Gif)", nameof(format));
            }
        }
示例#7
0
 /// <inheritdoc />
 public virtual Task <Result <IChannel> > CreateDMAsync
 (
     Snowflake recipientID,
     CancellationToken ct = default
 )
 {
     return(this.DiscordHttpClient.PostAsync <IChannel>
            (
                "users/@me/channels",
                b => b.WithJson
                (
                    json =>
     {
         json.WriteString("recipient_id", recipientID.ToString());
     }
                ),
                ct: ct
            ));
 }
            public async Task ShouldExecuteCommandAndReplyIfShouldReplyImmediately(
                string content,
                Snowflake userId,
                Snowflake channelId,
                [Frozen] Command command,
                [Frozen] ExecuteCommandResponse executeCommandResponse,
                [Frozen, Substitute] IMessageEmitter emitter,
                [Frozen, Substitute] IBrighidCommandsService commandsClient,
                [Frozen, Substitute] IDiscordChannelClient channelClient,
                [Frozen, Substitute] IUserService userService,
                [Target] MessageCreateEventController controller
                )
            {
                var cancellationToken = new CancellationToken(false);
                var author            = new User {
                    Id = userId
                };
                var message = new Message {
                    Content = content, Author = author, ChannelId = channelId
                };
                var @event = new MessageCreateEvent {
                    Message = message
                };
                var identityUserId = new UserId(Guid.NewGuid(), false, true);

                executeCommandResponse.ReplyImmediately = true;
                userService.GetIdentityServiceUserId(Any <User>(), Any <CancellationToken>()).Returns(identityUserId);
                userService.IsUserRegistered(Any <User>(), Any <CancellationToken>()).Returns(true);

                await controller.Handle(@event, cancellationToken);

                Received.InOrder(async() =>
                {
                    await commandsClient.Received().ParseAndExecuteCommandAsUser(
                        Is(@event.Message.Content),
                        Is(identityUserId.Id.ToString()),
                        Is(channelId.ToString()),
                        Is(cancellationToken)
                        );
                    await channelClient.Received().CreateMessage(Is(channelId), Is <CreateMessagePayload>(payload => payload.Content == executeCommandResponse.Response), Is(cancellationToken));
                });
            }
示例#9
0
 /// <inheritdoc />
 public virtual Task <Result <IFollowedChannel> > FollowNewsChannelAsync
 (
     Snowflake channelID,
     Snowflake webhookChannelID,
     CancellationToken ct = default
 )
 {
     return(_discordHttpClient.PostAsync <IFollowedChannel>
            (
                $"channels/{channelID}/followers",
                b => b.WithJson
                (
                    p =>
     {
         p.WriteString("webhook_channel_id", webhookChannelID.ToString());
     }
                ),
                ct: ct
            ));
 }
示例#10
0
            public async Task PerformsRequestCorrectly()
            {
                var webhookId = new Snowflake(0);
                var name      = "aaa";

                // Create a dummy PNG image
                await using var avatar       = new MemoryStream();
                await using var binaryWriter = new BinaryWriter(avatar);
                binaryWriter.Write(9894494448401390090);
                avatar.Position = 0;

                var channelId = new Snowflake(1);

                var api = CreateAPI
                          (
                    b => b
                    .Expect(HttpMethod.Patch, $"{Constants.BaseURL}webhooks/{webhookId}")
                    .WithJson
                    (
                        j => j.IsObject
                        (
                            o => o
                            .WithProperty("name", p => p.Is(name))
                            .WithProperty("avatar", p => p.IsString())
                            .WithProperty("channel_id", p => p.Is(channelId.ToString()))
                        )
                    )
                    .Respond("application/json", SampleRepository.Samples[typeof(IWebhook)])
                          );

                var result = await api.ModifyWebhookAsync
                             (
                    webhookId,
                    name,
                    avatar,
                    channelId
                             );

                ResultAssert.Successful(result);
            }
示例#11
0
            public async Task PerformsRequestCorrectly()
            {
                var  response   = "{\"webhooks\": [], \"users\": [], \"audit_log_entries\": [], \"integrations\": []}";
                var  guildID    = new Snowflake(0);
                var  userID     = new Snowflake(1);
                var  actionType = AuditLogEvent.BotAdd;
                var  before     = new Snowflake(2);
                byte limit      = 45;

                var api = CreateAPI
                          (
                    b =>
                    b.Expect(HttpMethod.Get, $"{Constants.BaseURL}guilds/*/audit-logs")
                    .WithAuthentication()
                    .WithQueryString
                    (
                        new[]
                {
                    new KeyValuePair <string, string>("user_id", userID.ToString()),
                    new KeyValuePair <string, string>("action_type", ((int)actionType).ToString()),
                    new KeyValuePair <string, string>("before", before.ToString()),
                    new KeyValuePair <string, string>("limit", limit.ToString())
                }
                    )
                    .Respond("application/json", response)
                          );

                var result = await api.GetAuditLogAsync
                             (
                    guildID,
                    userID,
                    actionType,
                    before,
                    limit
                             );

                ResultAssert.Successful(result);
            }
示例#12
0
 /// <inheritdoc />
 public Task <Result <IStageInstance> > CreateStageInstanceAsync
 (
     Snowflake channelID,
     string topic,
     Optional <StagePrivacyLevel> privacyLevel = default,
     CancellationToken ct = default
 )
 {
     return(this.DiscordHttpClient.PostAsync <IStageInstance>
            (
                "stage-instances",
                r => r.WithJson
                (
                    json =>
     {
         json.WriteString("channel_id", channelID.ToString());
         json.WriteString("topic", topic);
         json.Write("privacy_level", privacyLevel);
     }
                ),
                ct: ct
            ));
 }
示例#13
0
            public async Task PerformsRequestCorrectly()
            {
                var recipientID = new Snowflake(0);

                var api = CreateAPI
                          (
                    b => b
                    .Expect(HttpMethod.Post, $"{Constants.BaseURL}users/@me/channels")
                    .WithJson
                    (
                        j => j.IsObject
                        (
                            o => o
                            .WithProperty("recipient_id", p => p.Is(recipientID.ToString()))
                        )
                    )
                    .Respond("application/json", SampleRepository.Samples[typeof(IChannel)])
                          );

                var result = await api.CreateDMAsync(recipientID);

                ResultAssert.Successful(result);
            }
            public async Task ShouldStartAndStopATraceWithMessageAndEventAnnotations(
                string content,
                Snowflake userId,
                Snowflake channelId,
                Snowflake messageId,
                [Frozen, Substitute] ITracingService tracing,
                [Frozen, Substitute] IMessageEmitter emitter,
                [Frozen, Substitute] IUserService userService,
                [Target] MessageCreateEventController controller
                )
            {
                var cancellationToken = new CancellationToken(false);
                var author            = new User {
                    Id = userId
                };
                var message = new Message {
                    Id = messageId, Content = content, Author = author, ChannelId = channelId
                };
                var @event = new MessageCreateEvent {
                    Message = message
                };
                var remoteUserId = new UserId(Guid.NewGuid(), false, true);

                userService.IsUserRegistered(Any <User>(), Any <CancellationToken>()).Returns(true);
                userService.GetIdentityServiceUserId(Any <User>(), Any <CancellationToken>()).Returns(remoteUserId);

                await controller.Handle(@event, cancellationToken);

                Received.InOrder(() =>
                {
                    tracing.Received().StartTrace();
                    tracing.Received().AddAnnotation(Is("event"), Is("incoming-message"));
                    tracing.Received().AddAnnotation(Is("messageId"), Is(messageId.ToString()));
                    tracing.Received().EndTrace();
                });
            }
 /// <summary>
 /// Mention the the channel with the given ID
 /// </summary>
 /// <param name="channelId">Channel ID to mention</param>
 /// <returns>Mention channel formatted string</returns>
 public static string MentionChannel(Snowflake channelId) => $"<#{channelId.ToString()}>";
        public void RemoveChannelSubscription(Plugin plugin, Snowflake channelId)
        {
            if (plugin == null)
            {
                throw new ArgumentNullException(nameof(plugin));
            }

            if (!channelId.IsValid())
            {
                throw new ArgumentException("Value should be valid.", nameof(channelId));
            }

            Hash <string, DiscordSubscription> pluginSubs = _subscriptions[channelId];

            if (pluginSubs == null)
            {
                return;
            }

            pluginSubs.Remove(plugin.Name);

            if (pluginSubs.Count == 0)
            {
                _subscriptions.Remove(channelId);
            }

            _logger.Debug($"{nameof(DiscordSubscriptions)}.{nameof(RemoveChannelSubscription)} {plugin.Name} removed subscription to channel {channelId.ToString()}");
        }
        public void AddChannelSubscription(Plugin plugin, Snowflake channelId, Action <DiscordMessage> message)
        {
            if (plugin == null)
            {
                throw new ArgumentNullException(nameof(plugin));
            }

            if (!channelId.IsValid())
            {
                throw new ArgumentException("Value should be valid.", nameof(channelId));
            }

            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            _logger.Debug($"{nameof(DiscordSubscriptions)}.{nameof(AddChannelSubscription)} {plugin.Name} added subscription to channel {channelId.ToString()}");

            Hash <string, DiscordSubscription> channelSubs = _subscriptions[channelId];

            if (channelSubs == null)
            {
                channelSubs = new Hash <string, DiscordSubscription>();
                _subscriptions[channelId] = channelSubs;
            }

            channelSubs[plugin.Name] = new DiscordSubscription(channelId, plugin, message);
        }
 /// <summary>
 /// Mention the the role with the given ID
 /// </summary>
 /// <param name="roleId">Role ID to mention</param>
 /// <returns>Mention role formatted string</returns>
 public static string MentionRole(Snowflake roleId) => $"<@&{roleId.ToString()}>";
示例#19
0
 /// <summary>
 /// Invokes the callback with the message
 /// </summary>
 /// <param name="message">Message that was sent in the given channel</param>
 public void Invoke(DiscordMessage message)
 {
     Interface.Oxide.NextTick(() =>
     {
         try
         {
             _plugin.TrackStart();
             _callback.Invoke(message);
             _plugin.TrackEnd();
         }
         catch (Exception ex)
         {
             DiscordExtension.GlobalLogger.Exception($"An exception occured for discord subscription in channel {_channelId.ToString()} for plugin {_plugin?.Name}", ex);
         }
     });
 }
示例#20
0
 /// <summary>
 /// Returns the icon for a given channel
 /// </summary>
 /// <param name="channelId">Channel ID for the Icon</param>
 /// <param name="icon">Icon hash for the channel</param>
 /// <returns></returns>
 public static string GetChannelIcon(Snowflake channelId, string icon)
 {
     return($"https://cdn.discordapp.com/channel-icons/{channelId.ToString()}/{icon}.png");
 }
 /// <summary>
 /// Returns formatting string for custom emoji to be used in a url
 /// </summary>
 /// <param name="name">Name of the custom emoji</param>
 /// <param name="id">ID of the custom emoji</param>
 /// <param name="animated">If the emoji is animated</param>
 /// <returns>Custom emoji formatted string</returns>
 public static string CustomEmojiDataString(Snowflake id, string name, bool animated) => $"{(animated ? "a" : "")}:{name}:{id.ToString()}";
            public async Task ShouldParseAndExecuteCommandIfUserIsRegistered(
                string content,
                Snowflake userId,
                Snowflake channelId,
                [Frozen, Substitute] IMessageEmitter emitter,
                [Frozen, Substitute] IBrighidCommandsService commandsClient,
                [Frozen, Substitute] IUserService userService,
                [Target] MessageCreateEventController controller
                )
            {
                var cancellationToken = new CancellationToken(false);
                var identityUserId    = new UserId(Guid.NewGuid(), false, true);
                var author            = new User {
                    Id = userId
                };
                var message = new Message {
                    Content = content, Author = author, ChannelId = channelId
                };
                var @event = new MessageCreateEvent {
                    Message = message
                };

                userService.GetIdentityServiceUserId(Any <User>(), Any <CancellationToken>()).Returns(identityUserId);
                userService.IsUserRegistered(Any <User>(), Any <CancellationToken>()).Returns(true);

                await controller.Handle(@event, cancellationToken);

                Received.InOrder(async() =>
                {
                    await userService.Received().GetIdentityServiceUserId(Is(author), Is(cancellationToken));
                    await commandsClient.Received().ParseAndExecuteCommandAsUser(Is(message.Content), Is(identityUserId.Id.ToString()), Is(channelId.ToString()), Is(cancellationToken));
                });
            }
示例#23
0
        public async Task RegisterAsync(int accountNumber = -1)
        {
            Snowflake id    = Context.User.Id;
            var       users = DUserService.GetAccounts(id).Result;
            string    title;
            string    description;
            var       player = ContrackerService.GetPlayer(discordId: id.ToString());

            if (player == null)
            {
                switch (users.Count)
                {
                case 0:
                    title       = "Fail";
                    description = "`No Steam accounts associated with your account.`\n" +
                                  "[Go here](https://www.quora.com/How-will-I-add-my-gaming-accounts-in-Discord) " +
                                  "to see how to link your Steam account. You may unlink your account once you register.";
                    break;

                case 1:
                    if (DUserService.IsVerified(id).Result)
                    {
                        try
                        {
                            title       = "Success";
                            description = "`API request sent...`";
                            ContrackerService.Contracker.CreatePlayer(users.First(), id.ToString());
                        }
                        catch (XmlException e)
                        {
                            title       = "Fail";
                            description = "`An error has occured. Probably server's fault.`";
                            Console.WriteLine(e);
                        }
                    }
                    else
                    {
                        title       = "Fail";
                        description = "`Your Steam account is not verified.`\n" +
                                      "[Go here](https://www.reddit.com/r/discordapp/comments/6elfxl/its_now_possible_to_have_a_verified_steam_account/) " +
                                      "to see how to verify your Steam account.";
                    }

                    break;

                default:
                    if (accountNumber != -1 && accountNumber < users.Count)
                    {
                        title       = "Success";
                        description = "`Pretend this sends an API request...`\nwith account " +
                                      $"`{SteamService.GetSteamName(users[accountNumber]).Replace("`", "")}` " +
                                      $"or steamid `{users[accountNumber]}`";
                    }
                    else
                    {
                        title       = "Fail";
                        description = "`You have multiple linked Steam accounts.`\n" +
                                      "Use command `!register n` and replace `n` with the correct account number shown below." +
                                      "```\n" +
                                      string.Join("\n",
                                                  users.Select((x, index) =>
                                                               $"{index} - {SteamService.GetSteamName(x).Replace("`", "")}")) +
                                      "```";
                    }
                    break;
                }
            }
            else
            {
                title       = "You are already registered!";
                description = "You are registered on Steam account " +
                              $"`{SteamService.GetSteamName(player.Steam)}`";
            }
            await ReplyAsync(embed : new LocalEmbedBuilder()
                             .WithTitle(title)
                             .WithDescription(description)
                             .WithColor(Color.Honeydew)
                             .Build()).ConfigureAwait(true);
        }
 /// <summary>
 /// Mention the user displaying their user name
 /// </summary>
 /// <param name="userId">User ID to mention</param>
 /// <returns>Ping user formatted string</returns>
 public static string MentionUserNickname(Snowflake userId) => $"<@!{userId.ToString()}>";
            public void PrintsValue()
            {
                var snowflake = new Snowflake(143867839282020352u);

                Assert.Equal("143867839282020352", snowflake.ToString());
            }
 /// <summary>
 /// Mention the user with the given user ID
 /// </summary>
 /// <param name="userId">User ID to mention</param>
 /// <returns>Mention user formatted string</returns>
 public static string MentionUser(Snowflake userId) => $"<@{userId.ToString()}>";
示例#27
0
        /// <summary>
        /// Returns the Url of the users default avatar
        /// </summary>
        /// <param name="userId">Discord User ID</param>
        /// <param name="userDiscriminator">Discord User Discriminator</param>
        /// <returns>Url of the default avatar url</returns>
        public static string GetUserDefaultAvatarUrl(Snowflake userId, string userDiscriminator)
        {
            uint discriminator = uint.Parse(userDiscriminator) % 5;

            return($"{CdnUrl}/embed/avatars/{userId.ToString()}/{discriminator.ToString()}.png");
        }