Beispiel #1
0
        internal static async Task Migration_CreateTextChannels(DiscordRestClient client, RestGuild guild)
        {
            var text1 = await guild.GetDefaultChannelAsync();

            var text2 = await guild.CreateTextChannelAsync("text2");

            var text3 = await guild.CreateTextChannelAsync("text3");

            var text4 = await guild.CreateTextChannelAsync("text4");

            var text5 = await guild.CreateTextChannelAsync("text5");

            // create a channel category
            var cat1 = await guild.CreateCategoryChannelAsync("cat1");

            if (text1 == null)
            {
                // the guild did not have a default channel, so make a new one
                text1 = await guild.CreateTextChannelAsync("default");
            }

            //Modify #general
            await text1.ModifyAsync(x =>
            {
                x.Name       = "text1";
                x.Position   = 1;
                x.Topic      = "Topic1";
                x.CategoryId = cat1.Id;
            });

            await text2.ModifyAsync(x =>
            {
                x.Position   = 2;
                x.CategoryId = cat1.Id;
            });

            await text3.ModifyAsync(x =>
            {
                x.Topic = "Topic2";
            });

            await text4.ModifyAsync(x =>
            {
                x.Position = 3;
                x.Topic    = "Topic2";
            });

            await text5.ModifyAsync(x =>
            {
            });

            CheckTextChannels(guild, text1, text2, text3, text4, text5);
        }
Beispiel #2
0
 async Task OnSocketConnectedAsync()
 {
     SocketGuild = SocketClient.GetGuild(Config.GuildId);
     RestGuild   = await RestClient.GetGuildAsync(Config.GuildId);
 }
Beispiel #3
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));
        }
Beispiel #4
0
        internal static async Task Migration_CreateVoiceChannels(DiscordRestClient client, RestGuild guild)
        {
            var voice1 = await guild.CreateVoiceChannelAsync("voice1");

            var voice2 = await guild.CreateVoiceChannelAsync("voice2");

            var voice3 = await guild.CreateVoiceChannelAsync("voice3");

            var cat2 = await guild.CreateCategoryChannelAsync("cat2");

            await voice1.ModifyAsync(x =>
            {
                x.Bitrate    = 96000;
                x.Position   = 1;
                x.CategoryId = cat2.Id;
            });

            await voice2.ModifyAsync(x =>
            {
                x.UserLimit = null;
            });

            await voice3.ModifyAsync(x =>
            {
                x.Bitrate    = 8000;
                x.Position   = 1;
                x.UserLimit  = 16;
                x.CategoryId = cat2.Id;
            });

            CheckVoiceChannels(voice1, voice2, voice3);
        }
Beispiel #5
0
        public async Task <IActionResult> GuildDetails(ulong Id)
        {
            RestGuild singleGuild = await HttpClientHelper.ClientBot().GetGuildAsync(Id);

            return(PartialView("_GuildDetails", singleGuild));
        }
Beispiel #6
0
 public async Task <IActionResult> Create([FromBody] RestGuild model)
 {
     //TempData[model.ContactName] = "ERROR";
     return(PartialView("_Create", model));
 }
Beispiel #7
0
 internal static Task <IGuildChannel> GetGuildChannel(ulong channelId, RestGuild guild = null)
 {
     return(_discordClient.ChannelsService.GetGuildChannel(channelId, guild));
 }
Beispiel #8
0
        public static async Task CheckTempActs(DiscordSocketClient client, bool debug = false, CancellationToken?ct = null)
        {
            RequestOptions requestOptions = RequestOptions.Default;

            requestOptions.RetryMode = RetryMode.AlwaysRetry;
            try
            {
                currentInfo.checkedGuilds = 0;
                foreach (SocketGuild sockGuild in client.Guilds)
                {
                    ct?.ThrowIfCancellationRequested();
                    currentInfo.checkedMutes = 0;
                    if (currentInfo.checkedGuilds > client.Guilds.Count)
                    {
                        await new LogMessage(LogSeverity.Error, "TempAct", $"Check went past all guilds (at #{currentInfo.checkedGuilds}) but has been stopped. This doesn't seem physically possible.").Log();
                        return;
                    }
                    RestGuild restGuild = await client.Rest.SuperGetRestGuild(sockGuild.Id);

                    if (debug)
                    {
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.Write($"\nChecking {sockGuild.Name} discord ");
                    }
                    TempActionList actions  = sockGuild.LoadFromFile <TempActionList>(false);
                    bool           needSave = false;
                    currentInfo.checkedGuilds++;
                    if (actions != null)
                    {
                        if (actions.tempBans?.Count is not null or 0)
                        {
                            currentInfo.editedBans = new List <TempAct>(actions.tempBans);
                            foreach (TempAct tempBan in actions.tempBans)
                            {
                                try
                                {
                                    RestBan ban = await sockGuild.GetBanAsync(tempBan.User, requestOptions);

                                    if (ban == null)
                                    { //If manual unban
                                        var user = await client.Rest.GetUserAsync(tempBan.User);

                                        currentInfo.editedBans.Remove(tempBan);
                                        user?.TryNotify($"As you might know, you have been manually unbanned in {sockGuild.Name} discord");
                                        //_ = new LogMessage(LogSeverity.Warning, "TempAction", "Tempbanned person isn't banned").Log();
                                        if (user == null)
                                        {
                                            DiscordLogging.LogManualEndTempAct(sockGuild, tempBan.User, "bann", tempBan.DateBanned);
                                        }
                                        else
                                        {
                                            DiscordLogging.LogManualEndTempAct(sockGuild, user, "bann", tempBan.DateBanned);
                                        }
                                    }
                                    else if (DateTime.UtcNow >= tempBan.DateBanned.Add(tempBan.Length))
                                    {
                                        RestUser rUser = ban.User;
                                        await sockGuild.RemoveBanAsync(tempBan.User, requestOptions);

                                        currentInfo.editedBans.Remove(tempBan);
                                        DiscordLogging.LogEndTempAct(sockGuild, rUser, "bann", tempBan.Reason, tempBan.Length);
                                    }
                                }
                                catch (Exception e)
                                {
                                    await new LogMessage(LogSeverity.Error, "TempAct", "Something went wrong unbanning someone, continuing", e).Log();
                                }
                            }

                            //if all tempbans DON'T equal all edited tempbans (basically if there was a change
                            if (currentInfo.editedBans.Count != actions.tempBans.Count)
                            {
                                if (debug)
                                {
                                    Console.Write($"{actions.tempBans.Count - currentInfo.editedBans.Count} tempbans are over, ");
                                }
                                needSave         = true;
                                actions.tempBans = currentInfo.editedBans;
                            }
                            else if (debug)
                            {
                                Console.Write($"tempbans checked, none over, ");
                            }
                        }
                        else if (debug)
                        {
                            Console.Write($"no tempbans, ");
                        }
                        ModerationSettings settings = sockGuild.LoadFromFile <ModerationSettings>();
                        if (settings is not null && sockGuild.GetRole(settings.mutedRole) != null && actions.tempMutes?.Count is not null or 0)
                        {
                            var            mutedRole   = sockGuild.GetRole(settings.mutedRole);
                            List <TempAct> editedMutes = new List <TempAct>(actions.tempMutes);
                            foreach (TempAct tempMute in actions.tempMutes)
                            {
                                currentInfo.checkedMutes++;
                                try
                                {
                                    IGuildUser gUser = sockGuild.GetUser(tempMute.User) ?? await restGuild.SuperGetUser(tempMute.User);

                                    if (gUser != null && !gUser.RoleIds.Contains(settings.mutedRole))
                                    { //User missing muted role, must have been manually unmuted
                                        _ = gUser.TryNotify($"As you might know, you have been manually unmuted in {sockGuild.Name} discord");
                                        editedMutes.Remove(tempMute);
                                        DiscordLogging.LogManualEndTempAct(sockGuild, gUser, "mut", tempMute.DateBanned);
                                        _ = (!editedMutes.Contains(tempMute)).AssertAsync("Tempmute not removed?!");
                                    }
                                    else if (DateTime.UtcNow >= tempMute.DateBanned.Add(tempMute.Length))
                                    { //Normal mute end
                                        if (gUser != null)
                                        {
                                            await gUser.RemoveRoleAsync(mutedRole, requestOptions);
                                        } // if user not in guild || if user doesn't contain muted role (successfully removed?
                                        if (gUser == null || !gUser.RoleIds.Contains(settings.mutedRole))
                                        { //Doesn't remove tempmute if unmuting fails
                                            IUser user = gUser; //Gets user to try to message
                                            user ??= await client.SuperGetUser(tempMute.User);

                                            if (user != null)
                                            { // if possible to message, message and log
                                                DiscordLogging.LogEndTempAct(sockGuild, user, "mut", tempMute.Reason, tempMute.Length);
                                                _ = user.Notify("auto untempmuted", tempMute.Reason, sockGuild, client.CurrentUser);
                                            }
                                            editedMutes.Remove(tempMute);
                                        }
                                        else if (gUser != null)
                                        {
                                            await new LogMessage(LogSeverity.Warning, "TempAct", "User should've had role removed").Log();
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    await new LogMessage(LogSeverity.Error, "TempAct", "Something went wrong unmuting someone, continuing", e).Log();
                                }
                            }

                            //NOTE: Assertions fail if NOT true
                            _ = (currentInfo.checkedMutes == actions.tempMutes.Count).AssertAsync($"Checked incorrect number tempmutes ({currentInfo.checkedMutes}/{actions.tempMutes.Count}) in guild {sockGuild} owned by {sockGuild.Owner}");

                            if (editedMutes.Count != actions.tempMutes.Count)
                            {
                                if (debug)
                                {
                                    Console.Write($"{actions.tempMutes.Count - editedMutes.Count}/{actions.tempMutes.Count} tempmutes are over");
                                }
                                actions.tempMutes = editedMutes;
                                needSave          = true;
                            }
                            else if (debug)
                            {
                                Console.Write($"none of {actions.tempMutes.Count} tempmutes over");
                            }
                        }
                        else if (debug)
                        {
                            Console.Write("no tempmutes to check or no settings");
                        }
                        if (needSave)
                        {
                            actions.SaveToFile();
                        }
                    }
Beispiel #9
0
 public Tests(TestsFixture fixture)
 {
     _client = fixture._client;
     _guild  = fixture._guild;
 }
Beispiel #10
0
        internal static async Task Migration_CreateTextChannels(DiscordRestClient client, RestGuild guild)
        {
            var text1 = await guild.GetDefaultChannelAsync();

            var text2 = await guild.CreateTextChannelAsync("text2");

            var text3 = await guild.CreateTextChannelAsync("text3");

            var text4 = await guild.CreateTextChannelAsync("text4");

            var text5 = await guild.CreateTextChannelAsync("text5");

            //Modify #general
            await text1.ModifyAsync(x =>
            {
                x.Name     = "text1";
                x.Position = 1;
                x.Topic    = "Topic1";
            });

            await text2.ModifyAsync(x =>
            {
                x.Position = 2;
            });

            await text3.ModifyAsync(x =>
            {
                x.Topic = "Topic2";
            });

            await text4.ModifyAsync(x =>
            {
                x.Position = 3;
                x.Topic    = "Topic2";
            });

            await text5.ModifyAsync(x =>
            {
            });

            CheckTextChannels(guild, text1, text2, text3, text4, text5);
        }
        public async Task StreamOnline(List <TwitchUser> userList, StreamStatus streamStatus)
        {
            foreach (TwitchUser t in userList)
            {
                //Really iterating over servers here.
                Task <Server> getServerTask = _context.ServerList.AsQueryable().FirstAsync(s => s.ServerId == t.ServerId);
                RestGuild     guild         = (RestGuild)await _client.GetGuildAsync(ulong.Parse(t.ServerId));

                Task <RestGuildUser> getUserTask = null;
                if (!string.IsNullOrEmpty(t.DiscordUserId))
                {
                    //We don't need this yet so we'll do this later.
                    getUserTask = guild.GetUserAsync(ulong.Parse(t.DiscordUserId));
                }
                Server        server          = await getServerTask;
                string        twitchChannelId = server.TwitchChannel;
                RestGuildUser user            = null;
                if (getUserTask != null)
                {
                    user = await getUserTask;
                }

                if (user != null && !string.IsNullOrEmpty(server?.TwitchLiveRoleId))
                {
                    //We need to update the role
                    IRole twitchLiveRole = guild.GetRole(ulong.Parse(server.TwitchLiveRoleId));
                    await user.AddRoleAsync(twitchLiveRole);
                }
                if (!string.IsNullOrEmpty(twitchChannelId))
                {
                    //We post updates to the channel, so now we need to see if we've already posted.
                    string          streamUrl        = "https://twitch.tv/" + t.ChannelName;
                    DateTimeOffset  streamStartedUTC = streamStatus.started_at;
                    RestTextChannel channel          = await guild.GetTextChannelAsync(ulong.Parse(twitchChannelId));

                    //Find whether or not we've selected a message
                    ulong lastMessageId = 0;
                    bool  sendMessage   = true;
                    while (true)
                    {
                        IAsyncEnumerable <IReadOnlyCollection <RestMessage> > messagesUnflattened =
                            lastMessageId == 0 ? channel.GetMessagesAsync(100) : channel.GetMessagesAsync(lastMessageId, Direction.Before, 100);
                        List <RestMessage> messages = (await messagesUnflattened.FlattenAsync()).ToList();

                        var myMessages = messages.Where(m => m.Author.Id == _client.CurrentUser.Id &&
                                                        m.Timestamp > streamStartedUTC && m.Content.Contains(streamUrl)).ToList();
                        if (myMessages.Any())
                        {
                            //Already sent message. We don't need to send it again
                            sendMessage = false;
                            break;
                        }
                        else
                        {
                            if (messages.Last().Timestamp < streamStartedUTC)
                            {
                                //We're past when the stream started
                                break;
                            }
                        }
                        lastMessageId = messages.Last().Id;
                    }

                    if (sendMessage)
                    {
                        //We still need to send the message
                        string stringToSend = "";
                        if (user != null && String.IsNullOrEmpty(user?.Nickname))
                        {
                            stringToSend += !String.IsNullOrEmpty(user.Nickname) ? user.Nickname : user.Username;
                        }
                        else
                        {
                            stringToSend += t.ChannelName;
                        }
                        stringToSend += " is now live at " + streamUrl;
                        await channel.SendMessageAsync(stringToSend);
                    }
                }
            }
        }