示例#1
0
        private void makeSnowflakes()
        {
            Snowflake snowflake = null;

            snowflakes = new Snowflake[count];
            for (int i = 0; i < count; i++) {
                snowflake = new Snowflake();
                snowflake.Reset(sky.ActualWidth, sky.ActualHeight);
                snowflakes[i] = snowflake;
            }
        }
示例#2
0
 public VoiceSpeakingEventArgs(Snowflake userId, int ssrc, bool isSpeaking)
 {
     UserId     = userId;
     Ssrc       = ssrc;
     IsSpeaking = isSpeaking;
 }
示例#3
0
        /// <summary>
        /// Deletes a reaction posted by any user.
        /// <para>Requires <see cref="DiscordPermission.ManageMessages"/>.</para>
        /// </summary>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="DiscordHttpApiException"></exception>
        public async Task DeleteUserReaction(Snowflake channelId, Snowflake messageId, Snowflake userId, DiscordReactionEmoji emoji)
        {
            if (emoji == null)
            {
                throw new ArgumentNullException(nameof(emoji));
            }

            await rest.Delete($"channels/{channelId}/messages/{messageId}/reactions/{emoji}/{userId}",
                              $"channels/{channelId}/messages/message/reactions/emoji/user").ConfigureAwait(false);
        }
示例#4
0
 static Widget renderTestView(BuildContext context)
 {
     return(new ListView(
                children: new List <Widget> {
         new Container(height: 10),
         new GestureDetector(
             onTap: () => { StoreProvider.store.dispatcher.dispatch(new StartLoginByEmailAction()); },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "LoginByEmail",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => { StoreProvider.store.dispatcher.dispatch(new StartFetchArticlesAction()); },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "FetchArticles",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => { StoreProvider.store.dispatcher.dispatch(new StartFetchArticleDetailAction()); },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "FetchArticleDetail",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => {
             StoreProvider.store.dispatcher.dispatch(new LikeArticleAction
             {
                 articleId = "59c8cdfe09091500294d1bb9"
             });
         },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "LikeArticle",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => {
             StoreProvider.store.dispatcher.dispatch(new StartReportItemAction
             {
                 itemId = "59c8cdfe09091500294d1bb9", itemType = "project"
             });
         },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "ReportArticle",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => {
             StoreProvider.store.dispatcher.dispatch(new StartFetchArticleCommentsAction());
         },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "FetchArticleCommentsFirst",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => {
             StoreProvider.store.dispatcher.dispatch(new StartFetchArticleCommentsAction());
         },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "FetchArticleCommentsMore",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => { StoreProvider.store.dispatcher.dispatch(new StartLikeCommentAction()); },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "LikeComment",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => {
             StoreProvider.store.dispatcher.dispatch(new StartRemoveLikeCommentAction
             {
                 messageId = "05d5ffd1ed800000"
             });
         },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "RemoveLikeComment",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => {
             var nonce = Snowflake.CreateNonce();
             StoreProvider.store.dispatcher.dispatch(new StartSendCommentAction
             {
                 channelId = "032f7a336d800000", content = "wow!", nonce = nonce
             });
         },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "SendComment",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => {
             var nonce = Snowflake.CreateNonce();
             StoreProvider.store.dispatcher.dispatch(new StartSendCommentAction {
                 channelId = "032f7a336d800000", content = "good!", nonce = nonce,
                 parentMessageId = "04c4adc7ed800000"
             });
         },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "SendReplyComment",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => {
             StoreProvider.store.dispatcher.dispatch(new StartReportItemAction
             {
                 itemId = "05d5ffd1ed800000", itemType = "comment", reportContext = "测试举报功能测试举报功能"
             });
         },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "ReportComment",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => { StoreProvider.store.dispatcher.dispatch(new StartFetchEventOngoingAction()); },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "FetchEvents",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => { StoreProvider.store.dispatcher.dispatch(new StartFetchEventDetailAction()); },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "FetchEventDetail",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => { StoreProvider.store.dispatcher.dispatch(new StartFetchNotificationsAction()); },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "FetchNotifications",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => { StoreProvider.store.dispatcher.dispatch(new StartJoinEventAction()); },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "JoinEvent",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => { StoreProvider.store.dispatcher.dispatch(new StartFetchMyFutureEventsAction()); },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "FetchMyFutureEvents",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => { StoreProvider.store.dispatcher.dispatch(new StartFetchMyPastEventsAction()); },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "FetchMyPastEvents",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => {
             StoreProvider.store.dispatcher.dispatch(Actions.fetchMessages("0522ffbb43000001", "",
                                                                           true));
         },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "FetchMessagesFirst",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => {
             StoreProvider.store.dispatcher.dispatch(Actions.fetchMessages("0522ffbb43000001",
                                                                           "0587f55b2b40c000", false));
         },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "FetchMessagesMore",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => { StoreProvider.store.dispatcher.dispatch(new StartSendMessageAction()); },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "SendMessage",
                     style: CTextStyle.H4
                     )
                 )
             ),
         new Container(height: 10),
         new GestureDetector(
             onTap: () => { StoreProvider.store.dispatcher.dispatch(new StartSearchArticleAction()); },
             child: new Container(
                 color: CColors.White,
                 child: new Text(
                     "SearchArticle",
                     style: CTextStyle.H4
                     )
                 )
             )
     }
                ));
 }
 /// <summary>
 /// Command to send a restart command to a server.
 /// </summary>
 public record Command(string ServerId, Snowflake ChannelId) : IRequest <Result>;
示例#6
0
 internal RestSnowflakeEntity(RestDiscordClient client, Snowflake id) : base(client)
 {
     Id = id;
 }
        /// <summary>
        ///     Gets a cached guild event with the given ID within this guild.
        /// </summary>
        /// <param name="guild"> The guild to get the guild event within. </param>
        /// <param name="eventId"> The ID of the guild event to get. </param>
        /// <returns>
        ///     The guild event or <see langword="null"/> if it was not cached.
        /// </returns>
        public static CachedGuildEvent GetEvent(this IGuild guild, Snowflake eventId)
        {
            var client = guild.GetGatewayClient();

            return(client.GetGuildEvent(guild.Id, eventId));
        }
        /// <summary>
        ///     Gets a cached presence of a member with the given ID within this guild.
        /// </summary>
        /// <param name="guild"> The guild to get the presence within. </param>
        /// <param name="memberId"> The ID of the member to get the presence of. </param>
        /// <returns>
        ///     The presence or <see langword="null"/> if it was not cached.
        /// </returns>
        public static CachedPresence GetPresence(this IGuild guild, Snowflake memberId)
        {
            var client = guild.GetGatewayClient();

            return(client.GetPresence(guild.Id, memberId));
        }
        public static CachedUserMessage GetMessage(this IGatewayClient client, Snowflake channelId, Snowflake messageId)
        {
            if (client.CacheProvider.TryGetMessages(channelId, out var cache, true))
            {
                return(cache.GetValueOrDefault(messageId));
            }

            return(null);
        }
 public static Task DeleteStageAsync(this IRestClient client, Snowflake channelId, IRestRequestOptions options = null)
 => client.ApiClient.DeleteStageInstanceAsync(channelId, options);
示例#11
0
 public GuildSettings CreateDefaultGuildSettings(Snowflake guildId)
 {
     return(new(guildId, DefaultPrefixes));
 }
示例#12
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);
        }
 /// <inheritdoc />
 public virtual Task <IRestResult> ModifyGuildChannelPositionsAsync
 (
     Snowflake guildID,
     IReadOnlyList <(Snowflake ChannelID, int?Position)> positionModifications,
        /// <inheritdoc />
        public virtual async Task <IModifyRestEntityResult <IGuild> > ModifyGuildAsync
        (
            Snowflake guildID,
            Optional <string> name    = default,
            Optional <string?> region = default,
            Optional <VerificationLevel?> verificationLevel = default,
            Optional <MessageNotificationLevel?> defaultMessageNotifications = default,
            Optional <ExplicitContentFilterLevel?> explicitContentFilter     = default,
            Optional <Snowflake?> afkChannelID           = default,
            Optional <TimeSpan> afkTimeout               = default,
            Optional <Stream?> icon                      = default,
            Optional <Snowflake> ownerID                 = default,
            Optional <Stream?> splash                    = default,
            Optional <Stream?> banner                    = default,
            Optional <Snowflake?> systemChannelID        = default,
            Optional <Snowflake?> rulesChannelID         = default,
            Optional <Snowflake?> publicUpdatesChannelID = default,
            Optional <string?> preferredLocale           = default,
            CancellationToken ct = default
        )
        {
            await using var memoryStream = new MemoryStream();

            Optional <string?> iconData = default;

            if (icon.HasValue)
            {
                if (icon.Value is null)
                {
                    iconData = new Optional <string?>(null);
                }
                else
                {
                    var packImage = await ImagePacker.PackImageAsync(icon.Value, ct);

                    if (!packImage.IsSuccess)
                    {
                        return(ModifyRestEntityResult <IGuild> .FromError(packImage));
                    }

                    iconData = packImage.Entity;
                }
            }

            Optional <string?> splashData = default;

            if (splash.HasValue)
            {
                if (splash.Value is null)
                {
                    splashData = new Optional <string?>(null);
                }
                else
                {
                    var packImage = await ImagePacker.PackImageAsync(splash.Value, ct);

                    if (!packImage.IsSuccess)
                    {
                        return(ModifyRestEntityResult <IGuild> .FromError(packImage));
                    }

                    splashData = packImage.Entity;
                }
            }

            var packBanner = await ImagePacker.PackImageAsync(banner, ct);

            if (!packBanner.IsSuccess)
            {
                return(ModifyRestEntityResult <IGuild> .FromError(packBanner));
            }

            var bannerData = packBanner.Entity;

            return(await _discordHttpClient.PatchAsync <IGuild>
                   (
                       $"guilds/{guildID}",
                       b => b.WithJson
                       (
                           json =>
            {
                json.Write("name", name, _jsonOptions);
                json.Write("region", region, _jsonOptions);
                json.WriteEnum("verification_level", verificationLevel, jsonOptions: _jsonOptions);
                json.WriteEnum
                (
                    "default_message_notifications",
                    defaultMessageNotifications,
                    jsonOptions: _jsonOptions
                );

                json.WriteEnum("explicit_content_filter", explicitContentFilter, jsonOptions: _jsonOptions);
                json.Write("afk_channel_id", afkChannelID, _jsonOptions);

                if (afkTimeout.HasValue)
                {
                    json.WriteNumber("afk_timeout", (ulong)afkTimeout.Value.TotalSeconds);
                }

                json.Write("icon", iconData, _jsonOptions);
                json.Write("owner_id", ownerID, _jsonOptions);
                json.Write("splash", splashData, _jsonOptions);
                json.Write("banner", bannerData, _jsonOptions);
                json.Write("system_channel_id", systemChannelID, _jsonOptions);
                json.Write("rules_channel_id", rulesChannelID, _jsonOptions);
                json.Write("public_updates_channel_id", publicUpdatesChannelID, _jsonOptions);
                json.Write("preferred_locale", preferredLocale, _jsonOptions);
            }
                       ),
                       ct : ct
                   ));
        }
 public VoiceServerUpdatedEventArgs(Snowflake guildId, string token, string endpoint)
 {
     GuildId  = guildId;
     Token    = token;
     Endpoint = endpoint;
 }
        /// <summary>
        ///     Gets a cached channel with the given ID within this guild.
        /// </summary>
        /// <param name="guild"> The guild to get the channel within. </param>
        /// <param name="channelId"> The ID of the channel to get. </param>
        /// <returns>
        ///     The channel or <see langword="null"/> if it was not cached.
        /// </returns>
        public static CachedGuildChannel GetChannel(this IGuild guild, Snowflake channelId)
        {
            var client = guild.GetGatewayClient();

            return(client.GetChannel(guild.Id, channelId));
        }
        public static IReadOnlyDictionary <Snowflake, CachedUserMessage> GetMessages(this IGatewayClient client, Snowflake channelId)
        {
            if (client.CacheProvider.TryGetMessages(channelId, out var cache, true))
            {
                return(cache.ReadOnly());
            }

            return(ReadOnlyDictionary <Snowflake, CachedUserMessage> .Empty);
        }
        /// <summary>
        ///     Gets a cached stage with the given ID within this guild.
        /// </summary>
        /// <param name="guild"> The guild to get the stage within. </param>
        /// <param name="stageId"> The ID of the stage to get. </param>
        /// <returns>
        ///     The stage or <see langword="null"/> if it was not cached.
        /// </returns>
        public static CachedStage GetStage(this IGuild guild, Snowflake stageId)
        {
            var client = guild.GetGatewayClient();

            return(client.GetStage(guild.Id, stageId));
        }
        public static CachedGuildChannel GetChannel(this IGatewayClient client, Snowflake guildId, Snowflake channelId)
        {
            if (client.CacheProvider.TryGetChannels(guildId, out var cache, true))
            {
                return(cache.GetValueOrDefault(channelId));
            }

            return(null);
        }
示例#20
0
        public override ValueTask <TypeParserResult <CachedUser> > ParseAsync(Parameter parameter, string value, CommandContext _)
        {
            var context = (DiscordCommandContext)_;

            if (context.Guild != null)
            {
                var memberParser = _memberParser ?? (_memberParser = parameter.Service.GetSpecificTypeParser <CachedMember, CachedMemberTypeParser>()
                                                                     ?? new CachedMemberTypeParser(_comparison));
                var memberParserResult = _memberParser.ParseAsync(parameter, value, _).Result;
                return(memberParserResult.IsSuccessful
                    ? TypeParserResult <CachedUser> .Successful(memberParserResult.Value)
                    : TypeParserResult <CachedUser> .Unsuccessful(memberParserResult.Reason));
            }

            IReadOnlyDictionary <Snowflake, CachedUser> users;

            if (context.Channel is CachedDmChannel dmChannel)
            {
                users = new Dictionary <Snowflake, CachedUser>
                {
                    [dmChannel.Recipient.Id]     = dmChannel.Recipient,
                    [context.Bot.CurrentUser.Id] = context.Bot.CurrentUser
                };
            }
            else if (context.Channel is CachedGroupChannel groupChannel)
            {
                var dictionary = groupChannel.Recipients.ToDictionary(x => x.Key, x => x.Value);
                dictionary[context.Bot.CurrentUser.Id] = context.Bot.CurrentUser;
                users = dictionary;
            }
            else
            {
                throw new InvalidOperationException("Unknown channel type.");
            }

            CachedUser user = null;

            if (Discord.TryParseUserMention(value, out var id) || Snowflake.TryParse(value, out id))
            {
                users.TryGetValue(id, out user);
            }

            if (user == null)
            {
                var values    = users.Values;
                var hashIndex = value.LastIndexOf('#');
                if (hashIndex != -1 && hashIndex + 5 == value.Length)
                {
                    user = values.FirstOrDefault(x =>
                    {
                        var valueSpan         = value.AsSpan();
                        var nameSpan          = valueSpan.Slice(0, value.Length - 5);
                        var discriminatorSpan = valueSpan.Slice(hashIndex + 1);
                        return(x.Name.AsSpan().Equals(nameSpan, _comparison) &&
                               x.Discriminator.AsSpan().Equals(discriminatorSpan, default));
                    });
                }

                if (user == null)
                {
                    // TODO: custom result type returning the users?
                    var matchingUsers = values.Where(x => x.Name.Equals(value, _comparison) || x is CachedMember member && member.Nick != null && member.Nick.Equals(value, _comparison)).ToArray();
                    if (matchingUsers.Length > 1)
                    {
                        return(TypeParserResult <CachedUser> .Unsuccessful("Multiple users found. Mention the user or use their tag or ID."));
                    }

                    if (matchingUsers.Length == 1)
                    {
                        user = matchingUsers[0];
                    }
                }
            }

            return(user == null
                ? TypeParserResult <CachedUser> .Unsuccessful("No user found matching the input.")
                : TypeParserResult <CachedUser> .Successful(user));
        }
        public static CachedMember GetMember(this IGatewayClient client, Snowflake guildId, Snowflake memberId)
        {
            if (client.CacheProvider.TryGetMembers(guildId, out var cache, true))
            {
                return(cache.GetValueOrDefault(memberId));
            }

            return(null);
        }
 public ChannelCategory(Snowflake id, string name, int?position)
 {
     Id       = id;
     Name     = name;
     Position = position;
 }
        public static IReadOnlyDictionary <Snowflake, CachedMember> GetMembers(this IGatewayClient client, Snowflake guildId)
        {
            if (client.CacheProvider.TryGetMembers(guildId, out var cache, true))
            {
                return(cache.ReadOnly());
            }

            return(ReadOnlyDictionary <Snowflake, CachedMember> .Empty);
        }
示例#24
0
 public TransientThreadCreatedAuditLog(IClient client, Snowflake guildId, AuditLogJsonModel auditLogJsonModel, AuditLogEntryJsonModel model)
     : base(client, guildId, auditLogJsonModel, model)
 {
     Data = new TransientThreadAuditLogData(client, model, true);
 }
        public static CachedRole GetRole(this IGatewayClient client, Snowflake guildId, Snowflake roleId)
        {
            if (client.CacheProvider.TryGetRoles(guildId, out var cache, true))
            {
                return(cache.GetValueOrDefault(roleId));
            }

            return(null);
        }
示例#26
0
 /// <summary>
 /// Deletes all reactions on a message.
 /// <para>Requires <see cref="DiscordPermission.ManageMessages"/>.</para>
 /// </summary>
 /// <exception cref="DiscordHttpApiException"></exception>
 public async Task DeleteAllReactions(Snowflake channelId, Snowflake messageId)
 {
     await rest.Delete($"channels/{channelId}/messages/{messageId}/reactions",
                       $"channels/{channelId}/messages/message/reactions").ConfigureAwait(false);
 }
示例#27
0
 internal WebhooksUpdatedEventArgs(DiscordClientBase client, Snowflake guildId, Snowflake channelId) : base(client)
 {
     GuildId   = guildId;
     ChannelId = channelId;
 }
示例#28
0
        /// <summary>
        /// Gets a paginated list of users who reacted to the specified message with the specified emoji.
        /// </summary>
        /// <param name="baseUserId">The user ID to start at when retrieving reactions.</param>
        /// <param name="limit">The maximum number of reactions to return or null to use the default.</param>
        /// <param name="getStrategy">The pagination strategy to use based on <paramref name="baseUserId"/>.</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="DiscordHttpApiException"></exception>
        public async Task <IReadOnlyList <DiscordUser> > GetReactions(Snowflake channelId, Snowflake messageId,
                                                                      DiscordReactionEmoji emoji, Snowflake?baseUserId = null, int?limit = null,
                                                                      ReactionGetStrategy getStrategy = ReactionGetStrategy.Before)
        {
            if (emoji == null)
            {
                throw new ArgumentNullException(nameof(emoji));
            }

            UrlParametersBuilder builder = new UrlParametersBuilder();

            if (baseUserId.HasValue)
            {
                builder.Add(getStrategy.ToString().ToLower(), baseUserId.Value.ToString());
            }
            if (limit.HasValue)
            {
                builder.Add("limit", limit.Value.ToString());
            }

            DiscordApiData data = await rest.Get(
                $"channels/{channelId}/messages/{messageId}/reactions/{emoji}{builder.ToQueryString()}",
                $"channels/{channelId}/messages/message/reactions/emoji").ConfigureAwait(false);

            DiscordUser[] users = new DiscordUser[data.Values.Count];
            for (int i = 0; i < users.Length; i++)
            {
                users[i] = new DiscordUser(false, data.Values[i]);
            }

            return(users);
        }
示例#29
0
        /// <summary>
        /// The main entrypoint of the program.
        /// </summary>
        /// <param name="args">The command-line arguments.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous program execution.</returns>
        public static async Task Main(string[] args)
        {
            var cancellationSource = new CancellationTokenSource();

            Console.CancelKeyPress += (_, eventArgs) =>
            {
                eventArgs.Cancel = true;
                cancellationSource.Cancel();
            };

            var botToken =
                Environment.GetEnvironmentVariable("REMORA_BOT_TOKEN")
                ?? throw new InvalidOperationException
                      (
                          "No bot token has been provided. Set the REMORA_BOT_TOKEN environment variable to a valid token."
                      );

            var serviceCollection = new ServiceCollection()
                                    .AddLogging
                                    (
                c => c
                .AddConsole()
                .AddFilter("System.Net.Http.HttpClient.*.LogicalHandler", LogLevel.Warning)
                .AddFilter("System.Net.Http.HttpClient.*.ClientHandler", LogLevel.Warning)
                                    )
                                    .AddDiscordGateway(_ => botToken)
                                    .AddDiscordCommands(true)
                                    .AddCommandGroup <HttpCatCommands>()
                                    .AddDiscordCaching();

            serviceCollection.AddHttpClient();

            var services = serviceCollection.BuildServiceProvider(true);
            var log      = services.GetRequiredService <ILogger <Program> >();

            Snowflake?debugServer = null;

#if DEBUG
            var debugServerString = Environment.GetEnvironmentVariable("REMORA_DEBUG_SERVER");
            if (debugServerString is not null)
            {
                if (!Snowflake.TryParse(debugServerString, out debugServer))
                {
                    log.LogWarning("Failed to parse debug server from environment");
                }
            }
#endif

            var slashService = services.GetRequiredService <SlashService>();

            if (!slashService.SupportsSlashCommands())
            {
                log.LogWarning("The registered commands of the bot don't support slash commands");
            }
            else
            {
                var updateSlash = await slashService.UpdateSlashCommandsAsync(debugServer, cancellationSource.Token);

                if (!updateSlash.IsSuccess)
                {
                    log.LogWarning("Failed to update slash commands: {Reason}", updateSlash.Error.Message);
                }
            }

            var gatewayClient = services.GetRequiredService <DiscordGatewayClient>();

            var runResult = await gatewayClient.RunAsync(cancellationSource.Token);

            if (!runResult.IsSuccess)
            {
                switch (runResult.Error)
                {
                case ExceptionError exe:
                {
                    log.LogError
                    (
                        exe.Exception,
                        "Exception during gateway connection: {ExceptionMessage}",
                        exe.Message
                    );

                    break;
                }

                case GatewayWebSocketError:
                case GatewayDiscordError:
                {
                    log.LogError(runResult.Error.Message);
                    break;
                }

                default:
                {
                    log.LogError
                    (
                        "Unknown error: {Message}",
                        runResult.Error.Message
                    );
                    break;
                }
                }
            }

            log.LogInformation("Bye bye");
        }
        /// <summary>
        ///     Gets a cached member with the given ID within this guild.
        /// </summary>
        /// <param name="guild"> The guild to get the member within. </param>
        /// <param name="memberId"> The ID of the member to get. </param>
        /// <returns>
        ///     The member or <see langword="null"/> if it was not cached.
        /// </returns>
        public static CachedMember GetMember(this IGuild guild, Snowflake memberId)
        {
            var client = guild.GetGatewayClient();

            return(client.GetMember(guild.Id, memberId));
        }
示例#31
0
 public TransientMembersDisconnectedAuditLog(IClient client, Snowflake guildId, AuditLogJsonModel auditLogJsonModel, AuditLogEntryJsonModel model)
     : base(client, guildId, auditLogJsonModel, model)
 {
 }