public async Task SendMessage(string message)
        {
            RestGuild guild = (RestGuild)await _client.GetGuildAsync(225374061386006528);

            RestTextChannel channel = await guild.GetTextChannelAsync(718854497245462588);

            await channel.SendMessageAsync(message);
        }
示例#2
0
        public async Task GetGuildUsersAsync()
        {
            string response = "";

            // Implementation via Guild.Users
            // foreach (var x in Context.Guild.Users) { response += (x.Username + " "); };

            //Implementation via REST Client directly
            //RestGuild guildRest = await _clientRest.GetGuildAsync(Context.Guild.Id);
            //await guildRest.GetUsersAsync().ForEachAsync(x =>
            //{
            //    foreach (IGuildUser y in x) { Console.Write("{name} ", y.Username); };
            //});

            // Implementation via Websocket method that uses REST API
            await Context.Guild.GetUsersAsync().ForEachAsync(x =>
            {
                foreach (IGuildUser y in x)
                {
                    response += y.Username + " ";
                }
                ;
            });

            // Sending response via REST for test purposes
            RestGuild guildRest = await _clientRest.GetGuildAsync(Context.Guild.Id);

            RestTextChannel channelRest = await guildRest.GetTextChannelAsync(Context.Channel.Id);

            await channelRest.SendMessageAsync(response);

            // Sending response via WebSocket
            // await ReplyAsync(response);
        }
示例#3
0
        public async Task AssignSingleRole(string id, string roletoadd, string classid)
        {
            var userid = Convert.ToUInt64(id);
            var guild  = await discordrest.GetGuildAsync(718945666348351570);

            var trimmed = roletoadd.Trim();

            if (guild.Roles.Any(tr => tr.Value.Name.Equals(trimmed)))
            {
                var roleid = guild.Roles.FirstOrDefault(x => x.Value.Name.ToString() == trimmed).Key;
                await discordrest.AddGuildMemberRoleAsync(718945666348351570, userid, roleid, "");

                var sql = $"UPDATE classes SET d_role_snowflake='{roleid}' WHERE g_class_id='{classid}'";
                var cmd = new MySqlCommand(sql, conn);
                cmd.ExecuteNonQuery();
            }
            else
            {
                var role = await guild.CreateRoleAsync(trimmed, Permissions.SendMessages);

                var channel = await guild.CreateChannelAsync(trimmed, ChannelType.Text);

                await channel.AddOverwriteAsync(role, Permissions.AccessChannels);

                await channel.AddOverwriteAsync(guild.EveryoneRole, Permissions.None, Permissions.AccessChannels);

                await discordrest.AddGuildMemberRoleAsync(718945666348351570, userid, role.Id, "");

                var sql = $"UPDATE classes SET d_role_snowflake='{role.Id}',d_text_channel_snowflake='{channel.Id}' WHERE g_class_id='{classid}'";
                var cmd = new MySqlCommand(sql, conn);
                cmd.ExecuteNonQuery();
            }
        }
示例#4
0
        public static Task <DiscordMember> GetMember(this DiscordRestClient client, ulong guild, ulong user)
        {
            async Task <DiscordMember> Inner() =>
            await(await client.GetGuildAsync(guild)).GetMemberAsync(user);

            return(WrapDiscordCall(Inner()));
        }
示例#5
0
        private async Task <(RestRole role, RestChannel channel)> CreateCourseChannelAsync(DiscordRestClient client, string courseName, string auditLogMessage)
        {
            var requestOptions = new RequestOptions()
            {
                AuditLogReason = auditLogMessage,
            };
            var guild = await client.GetGuildAsync(GuildId);

            var channelCategory = await GetChannelCategory(client);

            courseName = NormalizeCourseChannelName(courseName);

            var roleName = $"member_{channelCategory.Name}_{courseName}".ToLower();
            var role     = await CreateRoleAsync(guild, roleName, requestOptions);

            if (role == null)
            {
                // duplicate
                throw new Exception("Cannot create a duplicate role.");
            }

            var channel = await CreateTextChannelAsync(guild, courseName, requestOptions, role.Id);

            if (channel == null)
            {
                throw new Exception("Cannot create a duplicate channel.");
            }

            await channel.SendMessageAsync(auditLogMessage);

            return(role, channel);
        }
        /// <summary>
        /// Creates a ban infraction for the user if they do not already have one.
        /// </summary>
        /// <param name="guild">The guild that the user was banned from.</param>
        /// <param name="user">The user who was banned.</param>
        /// <returns>
        /// A <see cref="Task"/> that will complete when the operation completes.
        /// </returns>
        private async Task TryCreateBanInfractionAsync(ISocketUser user, ISocketGuild guild)
        {
            if (await _moderationService.AnyInfractionsAsync(GetBanSearchCriteria(guild, user)))
            {
                return;
            }

            var restGuild = await _restClient.GetGuildAsync(guild.Id);

            var auditLogs = (await restGuild.GetAuditLogsAsync(10)
                             .FlattenAsync())
                            .Where(x => x.Action == ActionType.Ban && x.Data is BanAuditLogData)
                            .Select(x => (Entry: x, Data: (BanAuditLogData)x.Data));

            var banLog = auditLogs.FirstOrDefault(x => x.Data.Target.Id == user.Id);

            var reason = string.IsNullOrWhiteSpace(banLog.Entry.Reason)
                ? $"Banned by {banLog.Entry.User.GetFullUsername()}."
                : banLog.Entry.Reason;

            var guildUser = guild.GetUser(banLog.Entry.User.Id);

            await _authorizationService.OnAuthenticatedAsync(guildUser);

            await _moderationService.CreateInfractionAsync(guild.Id, banLog.Entry.User.Id, InfractionType.Ban, user.Id, reason, null);
        }
示例#7
0
 public DiscordAnnouncer(DiscordRestClient discordClient, ulong guildId, ulong purgeLogChannelId, string warningText)
 {
     _warningText  = warningText;
     _guild        = discordClient.GetGuildAsync(guildId).Result;
     _purgeChannel = _guild.GetTextChannelAsync(purgeLogChannelId).Result;
     _userDict     = _guild.GetUsersAsync().FlattenAsync().Result.ToDictionary(u => u.Id, u => u);
 }
示例#8
0
        public async Task MigrateAsync()
        {
            DiscordRestClient client = null;
            RestGuild         guild  = null;

            await _cache.LoadInfoAsync(_config.GuildId).ConfigureAwait(false);

            while (_cache.Info.Version != MigrationCount)
            {
                if (client == null)
                {
                    client = new DiscordRestClient();
                    await client.LoginAsync(TokenType.Bot, _config.Token).ConfigureAwait(false);

                    guild = await client.GetGuildAsync(_config.GuildId);
                }

                uint nextVer = _cache.Info.Version + 1;
                try
                {
                    await DoMigrateAsync(client, guild, nextVer).ConfigureAwait(false);

                    _cache.Info.Version = nextVer;
                    await _cache.SaveInfoAsync().ConfigureAwait(false);
                }
                catch
                {
                    await _cache.ClearAsync().ConfigureAwait(false);

                    throw;
                }
            }
        }
        public async Task <ActionResult <GuildLeaderboard> > GetLocalLeaderboard(ulong guildId)
        {
            var guild = _client.GetGuild(guildId);

            if (guild == null)
            {
                return(NotFound("The specified guild could not be found!"));
            }
            var gl = new GuildLeaderboard()
            {
                AvatarUrl = guild.IconUrl ?? _client.CurrentUser.GetAvatarUrl(),
                GuildName = guild.Name,
                Ranks     = new List <GuildRank>(guild.MemberCount > 100 ? 100: guild.MemberCount) // Properly set capacity already for best performance!
            };

            var gUsersO = await _profileRepo.GetGuildUsersSorted(guildId);

            if (!gUsersO)
            {
                return(NotFound("Guild has no saved users!"));
            }

            var g = await _restClient.GetGuildAsync(guildId);

            // Create dictionary for easy and fast lookups later :)
            var users  = (await g.GetUsersAsync().FlattenAsync()).ToDictionary(x => x.Id, x => x);
            var gUsers = (~gUsersO);

            for (var i = 0; i < gUsers.Count; i++)
            {
                var user = gUsers[i];
                int rank = i + 1;
                if (rank > 100)
                {
                    break;
                }
                if (!users.TryGetValue(user.UserId, out var u))
                {
                    continue;
                }
                gl.Ranks.Add(new GuildRank()
                {
                    AvatarUrl = u.GetAvatarUrl() ?? u.GetDefaultAvatarUrl(),
                    Discrim   = u.Discriminator,
                    Exp       = user.Exp,
                    Name      = u.Username,
                    Rank      = rank,
                    UserId    = u.Id.ToString()
                });
            }

            return(Ok(gl));
        }
示例#10
0
        /// <summary>
        /// Tries repeatedly to get a <see cref="RestGuild"/> even if there's a common 5XX error
        /// </summary>
        public static async Task <RestGuild> SuperGetRestGuild(this DiscordRestClient client, ulong ID)
        {
            var requestOptions = new RequestOptions()
            {
                RetryMode = RetryMode.AlwaysRetry
            };
            Func <Task <RestGuild> > func = async() =>
            {
                return(await client.GetGuildAsync(ID, requestOptions));
            };

            return(await func.SuperGet());
        }
示例#11
0
        private async void PageOne_Load(object sender, EventArgs e)
        {
            await discord.LoginAsync(TokenType.Bot, _config["token"]);

            var guild = await discord.GetGuildAsync(432496922134052882);

            var channels = await guild.GetTextChannelsAsync();

            foreach (var channel in channels)
            {
                channelList.Add(channel);
                boxChannels.Items.Add(channel);
            }
        }
示例#12
0
        protected override void CycleThink()
        {
            if (World.GameConfiguration.DiscordGuildID != null && World.GameConfiguration.DiscordToken != null)
            {
                foreach (var player in Player.GetWorldPlayers(this.World)
                         .Where(p => !string.IsNullOrEmpty(p.Token) && !p.AuthenticationStarted))
                {
                    player.AuthenticationStarted = true;
                    Task.Run(async() =>
                    {
                        using (var drc = new DiscordRestClient())
                        {
                            try
                            {
                                await drc.LoginAsync(Discord.TokenType.Bearer, player.Token);
                                if (drc.CurrentUser != null)
                                {
                                    var playerRoles = new List <string>();

                                    var userId = drc.CurrentUser.Id;

                                    await drc.LoginAsync(Discord.TokenType.Bot, World.GameConfiguration.DiscordToken);

                                    var user  = await drc.GetGuildUserAsync(World.GameConfiguration.DiscordGuildID.Value, userId);
                                    var guild = await drc.GetGuildAsync(World.GameConfiguration.DiscordGuildID.Value);
                                    foreach (var roleID in user.RoleIds)
                                    {
                                        var role = guild.Roles.FirstOrDefault(r => r.Id == roleID);
                                        if (role != null)
                                        {
                                            playerRoles.Add(role.Name);
                                        }
                                    }

                                    player.LoginName = user.Username;
                                    player.LoginID   = user.Id;
                                    player.Roles     = playerRoles;

                                    player.Avatar = $"https://cdn.discordapp.com/avatars/{user.Id}/{user.AvatarId}.png?size=128";
                                    player.OnAuthenticated();
                                }
                            }
                            catch (Exception) { }
                        }
                    });
                }
            }
        }
示例#13
0
        /// <summary>
        /// Creates a ban infraction for the user if they do not already have one.
        /// </summary>
        /// <param name="guild">The guild that the user was banned from.</param>
        /// <param name="user">The user who was banned.</param>
        /// <returns>
        /// A <see cref="Task"/> that will complete when the operation completes.
        /// </returns>
        private async Task TryCreateBanInfractionAsync(ISocketUser user, ISocketGuild guild)
        {
            if (await _moderationService.AnyInfractionsAsync(GetBanSearchCriteria(guild, user)))
            {
                return;
            }

            var restGuild = await _restClient.GetGuildAsync(guild.Id);

            var allAudits = await restGuild.GetAuditLogsAsync(10).FlattenAsync();

            var banLog = allAudits
                         .Where(x => x.Action == ActionType.Ban && x.Data is BanAuditLogData)
                         .Select(x => (Entry: x, Data: (BanAuditLogData)x.Data))
                         .FirstOrDefault(x => x.Data.Target.Id == user.Id);

            // We're in a scenario in where the guild does not have a Discord audit of the
            // ban MODiX just received, if that's the case something has gone wrong and we
            // need to investigate.
            if (banLog.Data is null ||
                banLog.Entry is null)
            {
                // Snapshot the most amount of information possible about this event
                // to log this incident and investigate further
                var mostRecentAudit = allAudits.OrderByDescending(x => x.CreatedAt).FirstOrDefault();

                Log.Error("No ban audit found when handling {message} for user {userId}, in guild {guild} - " +
                          "the most recent audit was created at {mostRecentAuditTime}: {mostRecentAuditAction} for user: {mostRecentAuditUserId}",
                          nameof(UserBannedNotification),
                          user.Id,
                          guild.Id,
                          mostRecentAudit?.CreatedAt,
                          mostRecentAudit?.Action,
                          mostRecentAudit?.User.Id);

                return;
            }

            var reason = string.IsNullOrWhiteSpace(banLog.Entry.Reason)
                ? $"Banned by {banLog.Entry.User.GetFullUsername()}."
                : banLog.Entry.Reason;

            var guildUser = guild.GetUser(banLog.Entry.User.Id);

            await _authorizationService.OnAuthenticatedAsync(guildUser);

            await _moderationService.CreateInfractionAsync(guild.Id, banLog.Entry.User.Id, InfractionType.Ban, user.Id, reason, null);
        }
示例#14
0
文件: Tests.cs 项目: Lelouch99/bot_cc
        public TestsFixture()
        {
            _cache = new CachedRestClient();

            _config = TestConfig.LoadFile("./config.json");
            var config = new DiscordRestConfig
            {
                RestClientProvider = url =>
                {
                    _cache.SetUrl(url);
                    return(_cache);
                }
            };

            _client = new DiscordRestClient(config);
            _client.LoginAsync(TokenType.Bot, _config.Token).Wait();

            MigrateAsync().Wait();
            _guild = _client.GetGuildAsync(_config.GuildId).Result;
        }
示例#15
0
        /// <inheritdoc />
        public async Task <GuildResult> GetGuildInformationAsync(ulong guildId)
        {
            IGuild guild = DiscordSocketClient.GetGuild(guildId);

            if (guild != null)
            {
                return(new GuildResult(guild));
            }

            try
            {
                guild = await DiscordRestClient.GetGuildAsync(guildId);
            }
            catch (HttpException ex) when(ex.DiscordCode == 50001)
            {
                return(new GuildResult("Sorry, I do not have access to any guilds with that ID."));
            }

            return(new GuildResult(guild));
        }
        /// <summary>
        /// Creates a ban infraction for the user if they do not already have one.
        /// </summary>
        /// <param name="guild">The guild that the user was banned from.</param>
        /// <param name="user">The user who was banned.</param>
        /// <returns>
        /// A <see cref="Task"/> that will complete when the operation completes.
        /// </returns>
        private async Task TryCreateBanInfractionAsync(IGuild guild, IUser user)
        {
            if (await _moderationService.AnyInfractionsAsync(GetBanSearchCriteria(guild, user)))
            {
                return;
            }

            var restGuild = await _restClient.GetGuildAsync(guild.Id);

            var auditLogs = (await restGuild.GetAuditLogsAsync(10)
                             .FlattenAsync())
                            .Where(x => x.Action == ActionType.Ban)
                            .Select(x => (Entry: x, Data: (BanAuditLogData)x.Data));

            var banLog = auditLogs.FirstOrDefault(x => x.Data.Target.Id == user.Id);

            var reason = string.IsNullOrWhiteSpace(banLog.Entry.Reason)
                ? $"Banned by {banLog.Entry.User.GetDisplayNameWithDiscriminator()}."
                : banLog.Entry.Reason;

            await _moderationService.CreateInfractionAsync(guild.Id, banLog.Entry.User.Id, InfractionType.Ban, user.Id, reason, null);
        }
示例#17
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index", "Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }
                var user = new ApplicationUser {
                    UserName = info.DefaultUserName, Email = info.DefaultUserName
                };

                DiscordRestClient dcli = new DiscordRestClient(new DiscordRestConfig
                {
                    LogLevel = Discord.LogSeverity.Info
                });



                await dcli.LoginAsync(Discord.TokenType.Bot, ConfigHelper.Instance.DiscordBotToken);

                ulong discordUserId = Convert.ToUInt64(info.ExternalIdentity.Claims.First().Value);
                ulong guildId       = Convert.ToUInt64(ConfigHelper.Instance.DiscordGuildID);


                RestGuildUser guser = dcli.GetGuildUserAsync(guildId, discordUserId).Result;

                if (guser != null)
                {
                    RestGuild     guild     = dcli.GetGuildAsync(guildId).Result;
                    List <string> roleNames = guild.Roles.Where(x => guser.RoleIds.Contains(x.Id)).Select(x => x.Name).ToList();

                    var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(new ApplicationDbContext()));


                    foreach (string roleName in roleNames)
                    {
                        if (!roleManager.RoleExists(roleName))
                        {
                            roleManager.Create(new IdentityRole(roleName));
                        }
                    }

                    var result = await UserManager.CreateAsync(user);

                    if (result.Succeeded)
                    {
                        await UserManager.AddToRolesAsync(user.Id, roleNames.ToArray());

                        result = await UserManager.AddLoginAsync(user.Id, info.Login);

                        if (result.Succeeded)
                        {
                            await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                            return(RedirectToLocal(returnUrl));
                        }
                    }
                    AddErrors(result);
                }
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
示例#18
0
        private async Task <RestCategoryChannel> GetChannelCategory(DiscordRestClient client)
        {
            var guild = await client.GetGuildAsync(GuildId);

            return(await guild.GetChannelAsync(CategoryId) as RestCategoryChannel);
        }
示例#19
0
 public static Task <DiscordGuild> GetGuild(this DiscordRestClient client, ulong id) =>
 WrapDiscordCall(client.GetGuildAsync(id));
示例#20
0
        public async Task Assign(CommandContext ctx, string message)
        {
            var intakeStrings = message.Split(' ').ToList();
            var classes       = "";
            var id            = intakeStrings[0];

            intakeStrings.RemoveAt(0);
            foreach (var elem in intakeStrings)
            {
                classes = classes + elem + " ";
            }

            var rolestoadd = classes.Split(',');
            var token      = File.ReadAllText(@"token.txt");

            var discord = new DiscordRestClient(new DiscordConfiguration
            {
                Token                 = token,
                TokenType             = TokenType.Bot,
                UseInternalLogHandler = true,
                LogLevel              = LogLevel.Debug
            });
            var userid = Convert.ToUInt64(id);
            var guild  = await discord.GetGuildAsync(718945666348351570);

            foreach (var elem in rolestoadd)
            {
                var trimmed = elem.Trim();
                if (guild.Roles.Any(tr => tr.Value.Name.Equals(trimmed)))
                {
                    var roleid = guild.Roles.FirstOrDefault(x => x.Value.Name.ToString() == trimmed).Key;
                    await discord.AddGuildMemberRoleAsync(718945666348351570, userid, roleid, "");
                }
                else
                {
                    var role = await guild.CreateRoleAsync(trimmed, Permissions.SendMessages);

                    var channel = await guild.CreateChannelAsync(trimmed, ChannelType.Text);

                    var voicechannel = await guild.CreateChannelAsync(trimmed, ChannelType.Voice);

                    await discord.ModifyChannelAsync(channel.Id, channel.Name, 0, "", false, 718991556107042817,
                                                     null, 0, 0, "");

                    await discord.ModifyChannelAsync(voicechannel.Id, voicechannel.Name, 0, "", false,
                                                     718945666797404230,
                                                     64000, 0, 0, "");

                    await channel.AddOverwriteAsync(role, Permissions.AccessChannels);

                    await voicechannel.AddOverwriteAsync(role, Permissions.AccessChannels);

                    await channel.AddOverwriteAsync(guild.EveryoneRole, Permissions.None, Permissions.AccessChannels);

                    await voicechannel.AddOverwriteAsync(guild.EveryoneRole, Permissions.None,
                                                         Permissions.AccessChannels);

                    await discord.AddGuildMemberRoleAsync(718945666348351570, userid, role.Id, "");
                }
            }
        }
 public DiscordInactivityRetriever(DiscordRestClient discordClient, HttpClient httpClient, ulong guildId, ulong channelId, ulong idToBeg)
 {
     _httpClient   = httpClient;
     _idToBeg      = idToBeg;
     _purgeChannel = discordClient.GetGuildAsync(guildId).Result.GetTextChannelAsync(channelId).Result;
 }