Beispiel #1
0
        public async Task AddAndStartPollAsync(Poll poll)
        {
            DiscordGuild guild = await _discordClient.GetGuildAsync(poll.GuildId);

            DiscordChannel channel     = guild?.GetChannel(poll.ChannelId);
            DiscordMessage pollMessage = await channel.GetMessageAsync(poll.MessageId);

            await pollMessage.PinAsync();

            await _dbContext.Polls.AddAsync(poll);

            await _dbContext.SaveChangesAsync();

            await StartPollAsync(poll);
        }
		public static DiscordChannel GetBotImagesChannel(DiscordGuild guild) => guild.GetChannel(ServersData[guild.Id].BotImagesChannel);
Beispiel #3
0
        public async Task GuildLogger(BaseDiscordClient client, DiscordGuild guild, object eventArgs, LogType logType)
        {
            var guildData = await redis.GetAsync <Guild>(RedisKeyNaming.Guild(guild.Id));

            var logs = guildData.Logs;
            var log  = logs.FirstOrDefault(x => x.LogType == logType);

            if (log != null)
            {
                var logChannel = guild.GetChannel(log.ChannelId);

                if (logChannel != null)
                {
                    var embed = new Embed();

                    switch (eventArgs)
                    {
                    case ChannelCreateEventArgs channelCreateEventArgs:
                        ChannelCreate(client, embed, channelCreateEventArgs);
                        break;

                    case ChannelUpdateEventArgs channelUpdateEventArgs:
                        ChannelUpdate(client, embed, channelUpdateEventArgs);
                        break;

                    case ChannelDeleteEventArgs channelDeleteEventArgs:
                        ChannelDelete(client, guild, logs, channelDeleteEventArgs, guildData, embed);
                        break;

                    case GuildRoleCreateEventArgs guildRoleCreateEventArgs:
                        GuildRoleCreate(client, embed, guildRoleCreateEventArgs);
                        break;

                    case GuildRoleUpdateEventArgs guildRoleUpdateEventArgs:
                        GuildRoleUpdate(client, embed, guildRoleUpdateEventArgs);
                        break;

                    case GuildRoleDeleteEventArgs guildRoleDeleteEventArgs:
                        GuildRoleDelete(client, embed, guildRoleDeleteEventArgs);
                        break;

                    case GuildMemberAddEventArgs memberAddEventArgs:
                        GuildMemberAdd(client, embed, memberAddEventArgs);
                        break;

                    case GuildMemberUpdateEventArgs guildMemberUpdateEventArgs:
                        GuildMemberUpdate(client, embed, guildMemberUpdateEventArgs);
                        break;

                    case GuildMemberRemoveEventArgs guildMemberRemoveEventArgs:
                        GuildMemberRemove(client, embed, guildMemberRemoveEventArgs, logType);
                        break;

                    case GuildBanAddEventArgs guildBanAddEventArgs:
                        GuildBanAdd(client, embed, guildBanAddEventArgs);
                        break;

                    case GuildBanRemoveEventArgs guildBanRemoveEventArgs:
                        // Todo: With or without command
                        break;

                    case InviteCreateEventArgs inviteCreateEventArgs:
                        InviteCreate(client, embed, inviteCreateEventArgs);
                        break;

                    case InviteDeleteEventArgs inviteDeleteEventArgs:
                        InviteDelete(client, embed, inviteDeleteEventArgs);
                        break;

                    case MessageUpdateEventArgs messageUpdateEventArgs:
                        MessageUpdate(client, embed, messageUpdateEventArgs);
                        break;

                    case MessageDeleteEventArgs messageDeleteEventArgs:
                        MessageDelete(client, embed, messageDeleteEventArgs);
                        break;

                    case MessageBulkDeleteEventArgs messageBulkDeleteEventArgs:
                        MessageBulkDelete(client, embed, messageBulkDeleteEventArgs);
                        break;

                    case MessageReactionAddEventArgs messageReactionAddEventArgs:
                        // Why should this be a feature at all?
                        break;

                    case MessageReactionRemoveEventArgs messageReactionRemoveEventArgs:
                        // Why should this be a feature at all?
                        break;

                    case MessageReactionRemoveEmojiEventArgs messageReactionRemoveEmojiEventArgs:
                        // Why should this be a feature at all?
                        break;

                    case MessageReactionsClearEventArgs messageReactionsClearEventArgs:
                        // Why should this be a feature at all?
                        break;

                    case VoiceStateUpdateEventArgs voiceStateUpdateEventArgs:
                    {
                        var before        = voiceStateUpdateEventArgs.Before;
                        var after         = voiceStateUpdateEventArgs.After;
                        var beforeChannel = voiceStateUpdateEventArgs.Before?.Channel;
                        var afterChannel  = voiceStateUpdateEventArgs.After?.Channel;

                        if (beforeChannel != null)
                        {
                            if (afterChannel != null)
                            {
                                if (beforeChannel != afterChannel)
                                {
                                    VoiceStateUpdateMemberSwitched(client, embed, voiceStateUpdateEventArgs, beforeChannel, afterChannel);
                                }
                                else
                                {
                                    VoiceStateUpdateMedia(client, embed, voiceStateUpdateEventArgs, before, after);
                                }

                                embed.Color = DiscordColor.CornflowerBlue;
                            }
                            else
                            {
                                VoiceStateUpdateMemberDisconnected(client, embed, voiceStateUpdateEventArgs, beforeChannel);
                            }
                        }
                        else
                        {
                            VoiceStateUpdateMemberConnected(client, embed, voiceStateUpdateEventArgs, afterChannel);
                        }

                        embed.Thumbnail = voiceStateUpdateEventArgs.User.AvatarUrl;
                        embed.Footer    = new EmbedFooter()
                        {
                            Text = $"Member: {voiceStateUpdateEventArgs.User.GetUsertag()} | {voiceStateUpdateEventArgs.User.Id}"
                        };
                        break;
                    }
                    }

                    if (passInformation)
                    {
                        await logChannel.SendEmbedMessageAsync(embed);
                    }

                    await Task.CompletedTask.ConfigureAwait(true);
                }
                else
                {
                    guildData.Logs.Remove(log);
                    await redis.ReplaceAsync(RedisKeyNaming.Guild(guild.Id), guildData);
                }
            }
        }
Beispiel #4
0
        static async void MainAsync()
        {
            DiscordGuild guild = await discord.GetGuildAsync(705796441989447760);

            DiscordChannel announcments = guild.GetChannel(705803300783521833);
            DiscordChannel lingu        = guild.GetChannel(705803324057714809);
            DiscordChannel general      = guild.GetChannel(705796441989447763);



            string vwd = "/"; // virtual working directory
            bool?  messageModeEnabled = null;

            if (messageModeEnabled != true)
            {
                Console.Write("remote@qwerzen:" + vwd + "$ ");
            }
            string input = Console.ReadLine();

            input = input.Replace(("remote@qwerzen:" + vwd + "$ "), "").ToLower().Trim();
            if (input.StartsWith("new"))
            {
                if (input.EndsWith("announcement"))
                {
                    Console.WriteLine("\n Enter announcment: \n");
                    string text = Console.ReadLine();
                    await discord.SendMessageAsync(announcments, ("@everyone" + text));
                }
            }

            if (input.StartsWith("message"))
            {
                if (input.EndsWith("general"))
                {
                    Console.WriteLine("Enter message: ");
                    await discord.SendMessageAsync(general, Console.ReadLine());
                }

                if (input.EndsWith("lingu"))
                {
                    Console.WriteLine("Enter message: ");
                    await discord.SendMessageAsync(lingu, Console.ReadLine());
                }
            }

            if (input.StartsWith("enter") && input.EndsWith("mode"))
            {
                if (input.Contains("message"))
                {
                    string line;
                    messageModeEnabled = true;
                    while (9 == 9)
                    {
                        Console.Write("general: ");
                        line = Console.ReadLine();
                        if (line == "exit")
                        {
                            messageModeEnabled = false;
                            break;
                        }
                        try
                        {
                            await discord.SendMessageAsync(general, line);
                        }
                        catch (ArgumentException)
                        {
                        }
                    }
                }
            }

            if (input == "terminate connection")
            {
                return;
            }

            MainAsync(); // haha recursion
            return;
        }
Beispiel #5
0
        internal async Task OnReactionAdded(MessageReactionAddEventArgs e)
        {
            if (e.Message.Id != Config.reactionMessage)
            {
                return;
            }

            DiscordGuild  guild  = e.Message.Channel.Guild;
            DiscordMember member = await guild.GetMemberAsync(e.User.Id);

            if (!Config.HasPermission(member, "new") || Database.IsBlacklisted(member.Id))
            {
                return;
            }

            DiscordChannel category      = guild.GetChannel(Config.ticketCategory);
            DiscordChannel ticketChannel = await guild.CreateChannelAsync("ticket", ChannelType.Text, category);

            if (ticketChannel == null)
            {
                return;
            }

            ulong staffID = 0;

            if (Config.randomAssignment)
            {
                staffID = Database.GetRandomActiveStaff(0)?.userID ?? 0;
            }

            long   id       = Database.NewTicket(member.Id, staffID, ticketChannel.Id);
            string ticketID = id.ToString("00000");
            await ticketChannel.ModifyAsync("ticket-" + ticketID);

            await ticketChannel.AddOverwriteAsync(member, Permissions.AccessChannels, Permissions.None);

            await ticketChannel.SendMessageAsync("Hello, " + member.Mention + "!\n" +
                                                 Config.welcomeMessage);

            // Refreshes the channel as changes were made to it above
            ticketChannel = await SupportBoi.GetClient().GetChannelAsync(ticketChannel.Id);

            if (staffID != 0)
            {
                DiscordEmbed assignmentMessage = new DiscordEmbedBuilder
                {
                    Color       = DiscordColor.Green,
                    Description = "Ticket was randomly assigned to <@" + staffID + ">."
                };
                await ticketChannel.SendMessageAsync("", false, assignmentMessage);

                if (Config.assignmentNotifications)
                {
                    DiscordEmbed message = new DiscordEmbedBuilder
                    {
                        Color       = DiscordColor.Green,
                        Description = "You have been randomly assigned to a newly opened support ticket: " +
                                      ticketChannel.Mention
                    };

                    try
                    {
                        DiscordMember staffMember = await guild.GetMemberAsync(staffID);

                        await staffMember.SendMessageAsync("", false, message);
                    }
                    catch (NotFoundException)
                    {
                    }
                    catch (UnauthorizedException)
                    {
                    }
                }
            }

            // Log it if the log channel exists
            DiscordChannel logChannel = guild.GetChannel(Config.logChannel);

            if (logChannel != null)
            {
                DiscordEmbed logMessage = new DiscordEmbedBuilder
                {
                    Color       = DiscordColor.Green,
                    Description = "Ticket " + ticketChannel.Mention + " opened by " + member.Mention + ".\n",
                    Footer      = new DiscordEmbedBuilder.EmbedFooter {
                        Text = "Ticket " + ticketID
                    }
                };
                await logChannel.SendMessageAsync("", false, logMessage);
            }

            // Adds the ticket to the google sheets document if enabled
            Sheets.AddTicketQueued(member, ticketChannel, id.ToString(), staffID.ToString(),
                                   Database.TryGetStaff(staffID, out Database.StaffMember staffMemberEntry)
                                        ? staffMemberEntry.userID.ToString()
                                        : null);
        }
        public async Task ModMail(CommandContext ctx,
                                  [Description("The name of the server that you want to open the Mod Mail with. *Spaces are replaced with `-`*")] string serverName = null)
        {
            if (ctx.Guild is null)
            {
                if (serverName == null)
                {
                    serverName = "no server!";
                }
                var ModMailServers = DB.DBLists.ServerSettings.Where(w => w.ModMailID != 0);
                Dictionary <DiscordGuild, string> GuildNameDict = new();
                StringBuilder GuildNameString = new();
                GuildNameString.AppendLine("The mod-mail is only available on certain servers, here are the server names you can use:");
                foreach (var item in ModMailServers)
                {
                    DiscordGuild Guild = await Program.Client.GetGuildAsync((ulong)item.ID_Server);

                    GuildNameDict.Add(Guild, Guild.Name.Replace(' ', '-').ToLower());
                    GuildNameString.AppendLine($"`{Guild.Name.Replace(' ', '-').ToLower()}`");
                }
                GuildNameString.AppendLine($"To start a modmail write `{Program.CFGJson.CommandPrefix}modmail server-name-here`");
                if (!GuildNameDict.Values.Contains(serverName.Replace(' ', '-').ToLower()))
                {
                    await ctx.RespondAsync(GuildNameString.ToString());
                }
                else
                {
                    DiscordGuild Guild       = GuildNameDict.FirstOrDefault(w => w.Value.ToLower() == serverName.ToLower()).Key;
                    bool         serverCheck = true;
                    try
                    {
                        await Guild.GetMemberAsync(ctx.User.Id);
                    }
                    catch
                    {
                        await ctx.RespondAsync("You are not in this server. If you think this is an error, please make sure you are set as online and are in fact in the server.");

                        serverCheck = false;
                    }
                    if (serverCheck && DB.DBLists.ModMail.FirstOrDefault(w => w.User_ID == ctx.User.Id && w.IsActive) == null)
                    {
                        Random     r        = new();
                        string     colorID  = string.Format("#{0:X6}", r.Next(0x1000000));
                        DB.ModMail newEntry = new()
                        {
                            Server_ID   = Guild.Id,
                            User_ID     = ctx.User.Id,
                            LastMSGTime = DateTime.Now,
                            ColorHex    = colorID,
                            IsActive    = true,
                            HasChatted  = false
                        };

                        DBLists.InsertModMail(newEntry);
                        await ctx.RespondAsync($"**----------------------------------------------------**\n" +
                                               $"Modmail entry **open** with `{serverName.ToLower()}`. Continue to write as you would normaly ;)\n*Mod Mail will time out in {Automation.ModMail.TimeoutMinutes} minutes after last message is sent.*");

                        DiscordChannel      MMChannel      = Guild.GetChannel((ulong)ModMailServers.FirstOrDefault(w => w.ID_Server == Guild.Id).ModMailID);
                        DiscordEmbedBuilder ModeratorEmbed = new()
                        {
                            Author = new DiscordEmbedBuilder.EmbedAuthor
                            {
                                Name    = $"{ctx.User.Username} ({ctx.User.Id})",
                                IconUrl = ctx.User.AvatarUrl
                            },
                            Title = $"[NEW] Mod Mail created by {ctx.User.Username}.",
                            Color = new DiscordColor(colorID)
                        };
                        await MMChannel.SendMessageAsync(embed : ModeratorEmbed);

                        Program.Client.Logger.LogInformation(CustomLogEvents.ModMail, $"New Mod Mail entry created by {ctx.User.Username}({ctx.User.Id}) for {serverName}");
                    }
                    else
                    {
                        await ctx.RespondAsync("Seems like you already have an active session ongoing, please close the previous one to start a new one.");
                    }
                }
            }
            else
            {
                await ctx.RespondAsync($"{ctx.Member.Mention}, You can only open a mod mail in Live bot Direct Messages");
            }
        }
Beispiel #7
0
        private async Task StartPollAsync(Poll poll)
        {
            DiscordGuild guild = await _discordClient.GetGuildAsync(poll.GuildId);

            DiscordChannel channel     = guild?.GetChannel(poll.ChannelId);
            DiscordMember  pollCreator = await guild.GetMemberAsync(poll.CreatorId);

            DiscordMessage pollMessage = await channel.GetMessageAsync(poll.MessageId);

            pollMessage = await pollMessage.ModifyAsync(x => x.AddComponents(PollMessageUpdater.BuildAnswerButtons(poll.PossibleAnswers)));

            var pollMessageUpdater = PollMessageUpdater.Create(pollMessage);

            TimeSpan pollDuration      = poll.EndTimeUTC - DateTime.UtcNow;
            var      cancelTokenSource = new CancellationTokenSource();

            cancelTokenSource.CancelAfter(pollDuration);

            while (!cancelTokenSource.IsCancellationRequested)
            {
                var btnClick = await pollMessage.WaitForButtonAsync(cancelTokenSource.Token);

                if (!btnClick.TimedOut)
                {
                    var user     = btnClick.Result.User;
                    var answerId = btnClick.Result.Id;

                    var answer = poll.PossibleAnswers.First(x => x.Id == answerId);

                    answer.UpdateCount(user.Id);
                    _dbContext.Update(poll);
                    await _dbContext.SaveChangesAsync(cancelTokenSource.Token);

                    await btnClick.Result.Interaction.CreateResponseAsync(InteractionResponseType.UpdateMessage);

                    await pollMessageUpdater.UpdateAnswers(poll.PossibleAnswers);
                }
            }

            var pollResult = poll.PossibleAnswers
                             .Select(r => (Emoji: r.Emoji, Count: r.Count))
                             .ToList();

            await pollMessageUpdater.SetAsEnded(poll.EndTimeUTC);

            await pollMessage.UnpinAsync();

            if (!pollResult.Any(r => r.Count > 0))
            {
                await channel.SendMessageAsync($"No one participated in the poll {poll.Question} :(");

                return;
            }

            Dictionary <DiscordEmoji, string> emojiMapping = GetEmojiMapping(poll.PossibleAnswers.Select(x => x.Value).ToList());
            int totalVotes      = pollResult.Sum(r => r.Count);
            var pollResultEmbed = new DiscordEmbedBuilder()
                                  .WithTitle($"Poll results: {poll.Question}")
                                  .WithColor(DiscordColor.Azure)
                                  .WithDescription(
                $"**{pollCreator.Mention}{(pollCreator.DisplayName.EndsWith('s') ? "'" : "'s")} poll ended. Here are the results:**\n\n" +
                string.Join("\n", emojiMapping
                            .Select(ans =>
                                    new { Answer = ans.Value, Votes = pollResult.Single(r => r.Emoji == ans.Key).Count })
                            .Select(ans =>
                                    $"**{ans.Answer}**: {"vote".ToQuantity(ans.Votes)} ({100.0 * ans.Votes / totalVotes:F1} %)"))
                );
            await channel.SendMessageAsync(embed : pollResultEmbed.Build());

            _dbContext.Polls.Remove(poll);
            await _dbContext.SaveChangesAsync();
        }
		public static DiscordChannel GetUncensorChannel(DiscordGuild guild) => guild.GetChannel(ServersData[guild.Id].UncensorChannel);
Beispiel #9
0
        public DiscordChannel GetLogChannelForGuild(IDiscordClient client, DiscordGuild guild)
        {
            var gcfg = this.GetGuildConfig(guild.Id);

            return(gcfg.LoggingEnabled ? guild.GetChannel(gcfg.LogChannelId) : null);
        }
Beispiel #10
0
        public static async Task WarnUserAsync(DiscordUser user, DiscordUser admin, DiscordGuild server, DiscordChannel channel, string reason, bool automsg)
        {
            DB.ServerRanks    WarnedUserStats = DB.DBLists.ServerRanks.FirstOrDefault(f => server.Id == f.Server_ID && user.Id == f.User_ID);
            DB.ServerSettings ServerSettings  = DB.DBLists.ServerSettings.FirstOrDefault(f => server.Id == f.ID_Server);

            if (WarnedUserStats == null)
            {
                AddUserToServerRanks(user, server);
            }

            DiscordMember member = null;

            try
            {
                member = await server.GetMemberAsync(user.Id);
            }
            catch (Exception)
            {
                await channel.SendMessageAsync($"{user.Username} is no longer in the server.");
            }

            string              modinfo = "";
            StringBuilder       SB = new();
            decimal             uid = user.Id, aid = admin.Id;
            bool                kick = false, ban = false;
            DiscordEmbedBuilder embed;

            if (ServerSettings.WKB_Log != 0)
            {
                DiscordChannel modlog = server.GetChannel(Convert.ToUInt64(ServerSettings.WKB_Log));
                if (WarnedUserStats is null) // creates new entry in DB (Followers set to default value)
                {
                    DB.ServerRanks newEntry = new()
                    {
                        Server_ID     = server.Id,
                        Ban_Count     = 0,
                        Kick_Count    = 0,
                        Warning_Level = 1,
                        User_ID       = user.Id
                    };
                    DB.DBLists.InsertServerRanks(newEntry);
                    WarnedUserStats = newEntry;
                }
                else
                {
                    WarnedUserStats.Warning_Level++;
                    if (WarnedUserStats.Followers <= 1000 * WarnedUserStats.Warning_Level)
                    {
                        WarnedUserStats.Followers = 0;
                    }
                    else
                    {
                        WarnedUserStats.Followers -= (1000 * WarnedUserStats.Warning_Level);
                    }
                    DB.DBLists.UpdateServerRanks(WarnedUserStats);
                }

                DB.Warnings newWarning = new()
                {
                    Reason    = reason,
                    Active    = true,
                    Date      = DateTime.Now.ToString("yyyy-MM-dd"),
                    Admin_ID  = aid,
                    User_ID   = uid,
                    Server_ID = server.Id,
                    Type      = "warning"
                };
                DB.DBLists.InsertWarnings(newWarning);

                int warning_count = DB.DBLists.Warnings.Count(w => w.User_ID == user.Id && w.Server_ID == server.Id && w.Type == "warning");

                SB.AppendLine($"You have been warned by <@{admin.Id}>.\n**Warning Reason:**\t{reason}\n**Warning Level:** {WarnedUserStats.Warning_Level}\n**Server:** {server.Name}");
                embed = new DiscordEmbedBuilder
                {
                    Color  = new DiscordColor(0xf90707),
                    Author = new DiscordEmbedBuilder.EmbedAuthor
                    {
                        IconUrl = user.AvatarUrl,
                        Name    = $"{user.Username} ({user.Id})"
                    },
                    Description = $"**Warned user:**\t{user.Mention}\n**Warning level:**\t {WarnedUserStats.Warning_Level}\t**Warning count:**\t {warning_count}\n**Warned by**\t{admin.Username}\n**Reason:** {reason}"
                };
                if (WarnedUserStats.Warning_Level > 4)
                {
                    SB.AppendLine($"You have been banned from **{server.Name}** by {admin.Mention} for exceeding the warning level threshold(4).");
                    ban = true;
                }
                else if (WarnedUserStats.Warning_Level > 2 && WarnedUserStats.Warning_Level < 5)
                {
                    SB.AppendLine($"You have been kicked from **{server.Name}** by {admin.Mention} for exceeding the warning level threshold(2).");
                    kick = true;
                }

                if (automsg)
                {
                    SB.Append("*This warning is given out by a bot, contact an admin if you think this is a mistake*");
                }
                else
                {
                    SB.Append($"*(This is an automated message, use the `{Program.CFGJson.CommandPrefix}modmail` feature if you want to report a mistake.)*");
                }

                try
                {
                    await member.SendMessageAsync(SB.ToString());
                }
                catch
                {
                    modinfo = $":exclamation:{user.Mention} could not be contacted via DM. Reason not sent";
                }

                if (kick && member != null)
                {
                    await member.RemoveAsync("Exceeded warning limit!");
                }
                if (ban && user != null)
                {
                    await server.BanMemberAsync(user.Id, 0, "Exceeded warning limit!");
                }

                await modlog.SendMessageAsync(modinfo, embed : embed);

                DiscordMessage info = await channel.SendMessageAsync($"{user.Username}, Has been warned!");

                await Task.Delay(10000).ContinueWith(t => info.DeleteAsync());
            }
            else
            {
                await channel.SendMessageAsync("This server has not set up this feature!");
            }
        }
Beispiel #11
0
        private async Task UpdateGuildStats(DiscordGuild guild)
        {
            if (!_whConfig.Servers.ContainsKey(guild.Id))
            {
                return;
            }

            var server             = _whConfig.Servers[guild.Id];
            var memberCountChannel = guild.GetChannel(server.MemberCountChannelId);

            if (memberCountChannel == null)
            {
                _logger.Error($"Failed to find member count channel with id {server.MemberCountChannelId}");
                return;
            }
            var botCountChannel = guild.GetChannel(server.BotCountChannelId);

            if (botCountChannel == null)
            {
                _logger.Error($"Failed to find bot count channel with id {server.BotCountChannelId}");
                return;
            }
            var roleCountChannel = guild.GetChannel(server.RoleCountChannelId);

            if (roleCountChannel == null)
            {
                _logger.Error($"Failed to find role count channel with id {server.RoleCountChannelId}");
                return;
            }
            var channelCountChannel = guild.GetChannel(server.ChannelCountChannelId);

            if (channelCountChannel == null)
            {
                _logger.Error($"Failed to find channel count channel with id {server.ChannelCountChannelId}");
                return;
            }

            await memberCountChannel.ModifyAsync($"Member Count: {guild.MemberCount:N0}");

            await botCountChannel.ModifyAsync($"Bot Count: {guild.Members.Where(x => x.IsBot).ToList().Count:N0}");

            await roleCountChannel.ModifyAsync($"Role Count: {guild.Roles.Count:N0}");

            await channelCountChannel.ModifyAsync($"Channel Count: {guild.Channels.Count:N0}");

            foreach (var item in server.MemberRoles)
            {
                var roleChannelId = item.Key;
                var roleConfig    = item.Value;
                var roleChannel   = guild.GetChannel(roleChannelId);
                if (roleChannel == null)
                {
                    _logger.Error($"Failed to find role channel with id {roleChannelId}");
                    continue;
                }
                var total = 0;
                foreach (var roleId in roleConfig.RoleIds)
                {
                    var role = guild.GetRole(roleId);
                    if (role == null)
                    {
                        _logger.Error($"Failed to find role with id {roleId}");
                        continue;
                    }
                    total += GetMemberRoleCount(role.Id, guild.Members.ToList());
                }
                await roleChannel.ModifyAsync($"{roleConfig.Text}: {total:N0}");
            }
        }
        public async Task AnnounceUpdates()
        {
            if (!this.bot.Started)
            {
                return;
            }

            try
            {
                List <ChapterUpdateBucket> buckets = await this.GetUpdatedChapterBucketList();

                foreach (ChapterUpdateBucket bucket in buckets)
                {
                    if (bucket.Novel.AssociatedGuildNovelRegistrations.Any())
                    {
                        foreach (GuildNovelRegistration registration in bucket.Novel.AssociatedGuildNovelRegistrations)
                        {
                            DiscordClient client = this.bot.ShardedClient.GetShard(registration.GuildId);
                            DiscordGuild  guild  = await client.GetGuildAsync(registration.GuildId);

                            DiscordMember clientMember = await guild.GetMemberAsync(client.CurrentUser.Id);

                            DiscordChannel channel = !registration.IsDm ?
                                                     guild.GetChannel((ulong)registration.AnnouncementChannelId) :
                                                     await(await guild.GetMemberAsync((ulong)registration.MemberId)).CreateDmChannelAsync();
                            DiscordRole?role          = registration.RoleId == null ? null : guild.Roles[(ulong)registration.RoleId];
                            string      mentionString = GenerateMentionString(registration, role);
                            try
                            {
                                foreach (DiscordEmbed embed in bucket.AnnouncementEmbeds)
                                {
                                    await channel.SendMessageAsync(content : mentionString, embed : embed);
                                }
                            }
                            catch (ServerErrorException)
                            {
                                await this.mediator.Send(new GuildNovelRegistrations.Delete(registration));
                            }
                        }
                    }
                }

                await this.UpdateAllNovelInfos(buckets);
            }
            catch (Exception e)
            {
                DiscordEmbedBuilder embedException = new DiscordEmbedBuilder()
                                                     .WithTitle("Exception occured in Announcement Service");

                if (e.Message is not null)
                {
                    embedException.WithDescription(e.Message);
                }

                if (e.StackTrace is not null)
                {
                    embedException.AddField("Stack Trace", e.StackTrace.Substring(0, e.StackTrace.Length < 500 ? e.StackTrace.Length : 500));
                }

                await this.bot.BotDeveloper.SendMessageAsync(embed : embedException);
            }
        }
Beispiel #13
0
        public static async Task LogFleetDeletionAsync(DiscordClient client, DiscordGuild guild, DiscordChannel fleetCategory)
        {
            client.Logger.LogInformation(BotLoggerEvents.Event, $"Удаление рейда {fleetCategory.Name} - {fleetCategory.Id}");

            var embed = new DiscordEmbedBuilder
            {
                Title       = $"{fleetCategory.Name} удалён",
                Description = $"`{fleetCategory.Id}`",
                Color       = DiscordColor.IndianRed
            };

            var channels = "";

            foreach (var channel in fleetCategory.Children.OrderBy(x => x.Position).OrderBy(x => x.Type))
            {
                channels += $"**{channel.Name}** \t\t `{channel.Id}` \n";
            }
            embed.AddField("Каналы", channels);

            embed.WithTimestamp(DateTime.Now);

            await guild.GetChannel(Bot.BotSettings.FleetLogChannel).SendMessageAsync(embed: embed.Build());

            var fleetLogCategory = guild.GetChannel(Bot.BotSettings.FleetLogCategory);

            //Move new text channels to log
            var textChannels = fleetCategory.Children.Where(x => x.Type == ChannelType.Text);

            foreach (var channel in textChannels)
            {
                var lastPosition = fleetLogCategory.Children.OrderBy(x => x.Position).LastOrDefault().Position;

                await channel.ModifyAsync(x =>
                {
                    x.Name   = $"{DateTime.Now:dd} {channel.Name}";
                    x.Parent = guild.GetChannel(Bot.BotSettings.FleetLogCategory);
                    x.Topic  = DateTime.Now.ToString();
                });

                await channel.ModifyPositionAsync(lastPosition + 1);

                new Task(async() =>
                {
                    channel.PermissionOverwrites.ToList().ForEach(async x =>
                    {
                        await x.DeleteAsync();
                        await Task.Delay(400);
                    });

                    //Sync with category permissions
                    foreach (var permission in guild.GetChannel(Bot.BotSettings.FleetLogCategory).PermissionOverwrites)
                    {
                        if (permission.Type == OverwriteType.Role)
                        {
                            await channel.AddOverwriteAsync(await permission.GetRoleAsync(), permission.Allowed, permission.Denied);
                        }
                        else
                        {
                            await channel.AddOverwriteAsync(await permission.GetMemberAsync(), permission.Allowed, permission.Denied);
                        }

                        await Task.Delay(400);
                    }
                }
                         ).Start();
            }

            //Delete old fleet text channels
            var oldChannels = guild.GetChannel(Bot.BotSettings.FleetLogCategory).Children
                              .Where(x =>
            {
                try
                {
                    return((DateTime.Now - DateTime.Parse(x.Topic)).TotalHours > 36);
                }
                catch (ArgumentNullException)
                {
                    return(false);
                }
                catch (FormatException)
                {
                    return(false);
                }
            });

            foreach (var oldChannel in oldChannels)
            {
                await oldChannel.DeleteAsync();
            }
        }
Beispiel #14
0
 public DiscordChannel ToDiscord(DiscordGuild guild)
 {
     return(guild.GetChannel(VoiceChannelId));
 }
		public static DiscordChannel GetAnnountmentsChannel(DiscordGuild guild) => guild.GetChannel(ServersData[guild.Id].AnnountmentsChannel);
		public static DiscordChannel GetTeamFindingChannel(DiscordGuild guild) => guild.GetChannel(ServersData[guild.Id].TeamFindingChannel);
Beispiel #17
0
 public static async Task Stream_Notification(object Client, PresenceUpdateEventArgs e)
 {
     _ = Task.Run(async() =>
     {
         if (e.User != null)
         {
             DiscordGuild guild = e.User.Presence.Guild;
             DB.StreamNotifications StreamNotification = DB.DBLists.StreamNotifications.FirstOrDefault(w => w.Server_ID == guild.Id);
             DiscordChannel channel = guild.GetChannel(Convert.ToUInt64(StreamNotification.Channel_ID));
             if (Program.ServerIdList.Contains(guild.Id))
             {
                 LiveStreamer streamer = new()
                 {
                     User  = e.User,
                     Time  = DateTime.Now,
                     Guild = guild
                 };
                 int ItemIndex;
                 try
                 {
                     ItemIndex = LiveStreamerList.FindIndex(a => a.User.Id == e.User.Id &&
                                                            a.Guild.Id == e.User.Presence.Guild.Id);
                 }
                 catch (Exception)
                 {
                     ItemIndex = -1;
                 }
                 if (ItemIndex >= 0 &&
                     e.User.Presence.Activities.FirstOrDefault(w => w.Name.ToLower() == "twitch" || w.Name.ToLower() == "youtube") == null)
                 {
                     //removes user from list
                     if (LiveStreamerList[ItemIndex].Time.AddHours(StreamCheckDelay) < DateTime.Now &&
                         e.User.Presence.Activities.FirstOrDefault(w => w.Name.ToLower() == "twitch" || w.Name.ToLower() == "youtube") == LiveStreamerList[ItemIndex].User.Presence.Activities.FirstOrDefault(w => w.Name.ToLower() == "twitch" || w.Name.ToLower() == "youtube"))
                     {
                         LiveStreamerList.RemoveAt(ItemIndex);
                     }
                 }
                 else if (ItemIndex == -1 &&
                          e.User.Presence.Activities.FirstOrDefault(w => w.Name.ToLower() == "twitch" || w.Name.ToLower() == "youtube") != null &&
                          e.User.Presence.Activities.FirstOrDefault(w => w.Name.ToLower() == "twitch" || w.Name.ToLower() == "youtube").ActivityType.Equals(ActivityType.Streaming))
                 {
                     DiscordMember StreamMember = await guild.GetMemberAsync(e.User.Id);
                     bool role          = false, game = false;
                     string gameTitle   = e.User.Presence.Activities.FirstOrDefault(w => w.Name.ToLower() == "twitch" || w.Name.ToLower() == "youtube").RichPresence.State;
                     string streamTitle = e.User.Presence.Activities.FirstOrDefault(w => w.Name.ToLower() == "twitch" || w.Name.ToLower() == "youtube").RichPresence.Details;
                     string streamURL   = e.User.Presence.Activities.FirstOrDefault(w => w.Name.ToLower() == "twitch" || w.Name.ToLower() == "youtube").StreamUrl;
                     if (StreamNotification.Roles_ID != null)
                     {
                         foreach (DiscordRole urole in StreamMember.Roles)
                         {
                             foreach (decimal roleid in StreamNotification.Roles_ID)
                             {
                                 if (urole.Id == roleid)
                                 {
                                     role = true;
                                     break;
                                 }
                             }
                         }
                     }
                     else if (StreamNotification.Roles_ID == null)
                     {
                         role = true;
                     }
                     if (StreamNotification.Games != null)
                     {
                         foreach (string ugame in StreamNotification.Games)
                         {
                             try
                             {
                                 if (gameTitle == ugame)
                                 {
                                     game = true;
                                     break;
                                 }
                             }
                             catch { game = false; }
                         }
                     }
                     else if (StreamNotification.Games == null)
                     {
                         game = true;
                     }
                     if (game && role)
                     {
                         DiscordEmbedBuilder embed = new()
                         {
                             Color  = new DiscordColor(0x6441A5),
                             Author = new DiscordEmbedBuilder.EmbedAuthor
                             {
                                 IconUrl = e.User.AvatarUrl,
                                 Name    = "STREAM",
                                 Url     = streamURL
                             },
                             Description = $"**Streamer:**\n {e.User.Mention}\n\n" +
                                           $"**Game:**\n{gameTitle}\n\n" +
                                           $"**Stream title:**\n{streamTitle}\n\n" +
                                           $"**Stream Link:**\n{streamURL}",
                             Thumbnail = new DiscordEmbedBuilder.EmbedThumbnail
                             {
                                 Url = e.User.AvatarUrl
                             },
                             Title = $"Check out {e.User.Username} is now Streaming!"
                         };
                         await channel.SendMessageAsync(embed: embed);
                         //adds user to list
                         LiveStreamerList.Add(streamer);
                     }
                 }
             }
         }
     });
     await Task.Delay(1);
 }
Beispiel #18
0
        public static async Task Setup()
        {
            MainGuild = await Bot._client.GetGuildAsync(442678942428561422);

            StoryTime = MainGuild.GetChannel(444573263532916767);
        }
Beispiel #19
0
        public static DiscordEmbed ToDiscordEmbed(this GuildConfig gcfg, DiscordGuild guild, LocalizationService lcs, bool update = false)
        {
            var emb = new LocalizedEmbedBuilder(lcs, guild.Id);

            emb.WithLocalizedTitle(DiscordEventType.GuildUpdated, update ? "evt-cfg-update" : "str-guild-cfg");
            emb.WithThumbnail(guild.IconUrl);

            emb.AddLocalizedTitleField("str-prefix", gcfg.Prefix ?? lcs.GetString(guild.Id, "str-default"), inline: true);
            emb.AddLocalizedTitleField("str-silent", gcfg.ReactionResponse, inline: true);
            emb.AddLocalizedTitleField("str-cmd-suggestions", gcfg.SuggestionsEnabled, inline: true);

            if (gcfg.LoggingEnabled)
            {
                DiscordChannel?logchn = guild.GetChannel(gcfg.LogChannelId);
                if (logchn is null)
                {
                    emb.AddLocalizedField("str-logging", "err-log-404", inline: true);
                }
                else
                {
                    emb.AddLocalizedField("str-logging", "fmt-logs", inline: true, contentArgs: new[] { logchn.Mention });
                }
            }
            else
            {
                emb.AddLocalizedField("str-logging", "str-off", inline: true);
            }

            emb.AddLocalizedField("str-backup", gcfg.BackupEnabled ? "str-enabled" : "str-disabled", inline: true);

            if (gcfg.WelcomeChannelId != default)
            {
                DiscordChannel?wchn = guild.GetChannel(gcfg.WelcomeChannelId);
                if (wchn is null)
                {
                    emb.AddLocalizedField("str-memupd-w", "err-memupd-w-404", inline: true);
                }
                else
                {
                    emb.AddLocalizedField("str-memupd-w", "fmt-memupd", inline: true, contentArgs: new[] {
                        wchn.Mention,
                        Formatter.Strip(gcfg.WelcomeMessage ?? lcs.GetString(guild.Id, "str-default"))
                    });
                }
            }
            else
            {
                emb.AddLocalizedField("str-memupd-w", "str-off", inline: true);
            }

            if (gcfg.LeaveChannelId != default)
            {
                DiscordChannel?lchn = guild.GetChannel(gcfg.LeaveChannelId);
                if (lchn is null)
                {
                    emb.AddLocalizedField("str-memupd-l", "err-memupd-l-404", inline: true);
                }
                else
                {
                    emb.AddLocalizedField("str-memupd-l", "fmt-memupd", inline: true, contentArgs: new[] {
                        lchn.Mention,
                        Formatter.Strip(gcfg.LeaveMessage ?? lcs.GetString(guild.Id, "str-default"))
                    });
                }
            }
            else
            {
                emb.AddLocalizedField("str-memupd-l", "str-off", inline: true);
            }

            emb.AddLocalizedTitleField("str-ratelimit", gcfg.RatelimitSettings.ToEmbedFieldString(guild.Id, lcs), inline: true);
            emb.AddLocalizedTitleField("str-antispam", gcfg.AntispamSettings.ToEmbedFieldString(guild.Id, lcs), inline: true);
            emb.AddLocalizedTitleField("str-antiflood", gcfg.AntifloodSettings.ToEmbedFieldString(guild.Id, lcs), inline: true);
            emb.AddLocalizedTitleField("str-instantleave", gcfg.AntiInstantLeaveSettings.ToEmbedFieldString(guild.Id, lcs), inline: true);

            if (gcfg.MuteRoleId != default)
            {
                DiscordRole?muteRole = guild.GetRole(gcfg.MuteRoleId);
                if (muteRole is null)
                {
                    emb.AddLocalizedField("str-muterole", "err-muterole-404", inline: true);
                }
                else
                {
                    emb.AddLocalizedTitleField("str-muterole", muteRole.Name, inline: true);
                }
            }
            else
            {
                emb.AddLocalizedField("str-muterole", "str-none", inline: true);
            }

            emb.AddLocalizedTitleField("str-lf", gcfg.LinkfilterSettings.ToEmbedFieldString(guild.Id, lcs), inline: true);

            return(emb.Build());
        }
Beispiel #20
0
        public static async Task UpdateLeaderboard(DiscordGuild guild)
        {
            var channel = guild.GetChannel(Bot.BotSettings.InvitesLeaderboardChannel);

            //Фильтруем топ 10 за последний месяц
            var currentMonthInviters = InviterList.Inviters.ToList()
                                       .OrderByDescending(x => x.Value.CurrentMonthActiveCount).ToList()
                                       .FindAll(x =>
            {
                if (!x.Value.Active)
                {
                    return(false);
                }
                //guild.GetMemberAsync(x.Key);
                return(true);
            })
                                       .Take(10).ToDictionary(x => x.Key, x => x.Value);

            var embed = new DiscordEmbedBuilder
            {
                Color = new DiscordColor("#FF0066"),
                Title = $"Топ рефералов за {DateTime.Now.ToString("MMMM", new CultureInfo("ru-RU"))}",
            };

            int i = 1;

            foreach (var el in currentMonthInviters)
            {
                if (el.Value.CurrentMonthActiveCount > 0)
                {
                    var userString = "";
                    try
                    {
                        var user = await guild.GetMemberAsync(el.Key);

                        userString = $"{user.Username}#{user.Discriminator}";
                    }
                    catch (NotFoundException)
                    {
                        //Пользователь не найден
                        userString = $"Пользователь покинул сервер";
                    }

                    var place = i switch
                    {
                        1 => "🥇",
                        2 => "🥈",
                        3 => "🥉",
                        _ => $"{i}."
                    };

                    embed.AddField(
                        $"{place} {userString}",
                        $"пригласил {el.Value.CurrentMonthActiveCount} пользователей");
                    i++;
                }
            }

            embed.WithFooter("Чтобы попасть в топ, создайте собственную ссылку приглашения");

            //Публикуем и проверяем на уже существующую таблицу топ 10
            var messages = await channel.GetMessagesAsync();

            ulong messageId = 0;

            if (messages.Count > 0)
            {
                messageId = messages.ToList().Where(x => (x.Author.Id == guild.CurrentMember.Id)).First().Id;
            }

            if (messageId == 0)
            {
                await channel.SendMessageAsync(embed : embed.Build());
            }
            else
            {
                await channel.GetMessageAsync(messageId).Result.ModifyAsync(embed: embed.Build());
            }

            //Проверка только в первый день месяца
            //if(DateTime.Now.Day == 1)
            //await CheckAndUpdateTopInvitersAsync(guild); //TODO: Revork this
        }
Beispiel #21
0
 public DiscordChannel?GetChannelCreator(DiscordGuild guild)
 {
     return(ChannelCreatorId is null ? null : guild.GetChannel(ChannelCreatorId.Value));
 }
Beispiel #22
0
        /// <summary>
        /// Gets all channels, members in them and set's up event handlers
        /// </summary>
        /// <param name="guild"></param>
        /// <returns></returns>
        internal async Task Initialize(DiscordGuild guild)
        {
            //DebugLogWriteLine($"Initiating {guild} GuildTask... ");
            //Init guild
            Guild   = guild;
            GuildId = guild.Id;
            SecretRoomOverwriteBuilder = new DiscordOverwriteBuilder();
            SecretRoomOverwriteBuilder.For(Guild.EveryoneRole);
            SecretRoomOverwriteBuilder.Deny(Permissions.AccessChannels);
            //PersonalChannelOverwriteBuilder = new DiscordOverwriteBuilder();
            //PersonalChannelOverwriteBuilder.Allow(Permissions.AccessChannels);

            LogChannel = guild.GetChannel(LogChannelId);
            if (LogChannel != null)
            {
                LogMessage = await LogChannel.SendMessageAsync($"Begin of log {DateTime.Now.ToString()}\n");
            }

            //Init RootCategory
            Guild.Channels.TryGetValue(DateCategoryId, out DiscordChannel cat);
            if (cat == null)
            {
                string m = $"Initialize failed. No Category found on + {DateCategoryId}";
                //DebugLogWriteLine(m);
                throw new Exception(m);
            }
            DateRootCategory = cat;
            Guild.Channels.TryGetValue(DateSecretCategoryId, out DiscordChannel secCat);
            DateSecretCategory = secCat;

            //DebugLogWrite("Initiating voice channels... ");
            //VoiceChannels
            DateVoiceLobbies.Clear();
            SecretRooms.Clear();
            DateVoiceLobbies.AddRange(GetVoiceLobbies());
            SecretRooms.AddRange(GetSecretRooms());
            await VoiceChannelsInitAsync().ConfigureAwait(false);

            if (DateVoiceLobbies.Count == 0 || DateVoiceLobbies.All(c => c.Users.Count() > 0))
            {
                await AddLastEmptyVoiceLobby().ConfigureAwait(false);
            }

            //DebugLogWrite("Initiating Emojis... ");
            //GetEmojis
            MaleEmoji   = DiscordEmoji.FromUnicode(DateBot.Instance.Client, MaleEmojiId);
            FemaleEmoji = DiscordEmoji.FromUnicode(DateBot.Instance.Client, FemaleEmojiId);
            OptionEmojis.Clear();
            OptionEmojis.AddRange(OptionEmojiIds.Select(id => DiscordEmoji.FromUnicode(DateBot.Instance.Client, id)));
            LikeEmoji       = DiscordEmoji.FromUnicode(DateBot.Instance.Client, LikeEmojiId);
            DisLikeEmoji    = DiscordEmoji.FromUnicode(DateBot.Instance.Client, DisLikeEmojiId);
            TimeEmoji       = DiscordEmoji.FromUnicode(DateBot.Instance.Client, TimeEmojiId);
            CancelLikeEmoji = DiscordEmoji.FromUnicode(DateBot.Instance.Client, CancelLikeEmojiId);

            //DebugLogWrite("Initiating Users in lobbies... ");
            //Check and add users in lobbies
            foreach (var u in UsersInLobbies.ToArray())
            {
                AddOrGetUserState(u).LastEnteredLobbyTime = DateTime.Now;
            }

            //DebugLogWrite("Initiating Welcome message... ");
            //Check for welcome message TODO add option emojis
            DateTextChannel = Guild.GetChannel(DateTextChannelId);
            await WelcomeMessageInit().ConfigureAwait(false);

            _ = PrivateControlsMessageInit().ConfigureAwait(false);

            //UpdateTimer = new Timer(TimeSpan.FromSeconds(30).TotalMilliseconds) { AutoReset = true };
            //UpdateTimer.Elapsed += UpdateTimer_Elapsed;
            //UpdateTimer.Start();

            //DebugLogWrite("finished");
            InitTask    = null;
            Initialized = true;

            if (UsersInLobbies.Count > 0)
            {
                TryStartMatchingTask();
            }
        }
        public static async Task <DiscordChannel> GetLeaveChannelAsync(this DBService db, DiscordGuild guild)
        {
            ulong cid = (ulong)await db.GetValueInternalAsync <long>(guild.Id, "leave_cid");

            return(cid != 0 ? guild.GetChannel(cid) : null);
        }
Beispiel #24
0
        internal async Task OnReactionAdded(DiscordClient client, MessageReactionAddEventArgs e)
        {
            if (e.Message.Id != Config.reactionMessage)
            {
                return;
            }

            DiscordGuild  guild  = e.Message.Channel.Guild;
            DiscordMember member = await guild.GetMemberAsync(e.User.Id);

            if (!Config.HasPermission(member, "new") || Database.IsBlacklisted(member.Id))
            {
                return;
            }
            if (reactionTicketCooldowns.ContainsKey(member.Id))
            {
                if (reactionTicketCooldowns[member.Id] > DateTime.Now)
                {
                    return;                                                                    // cooldown has not expired
                }
                else
                {
                    reactionTicketCooldowns.Remove(member.Id);                  // cooldown exists but has expired, delete it
                }
            }


            DiscordChannel category      = guild.GetChannel(Config.ticketCategory);
            DiscordChannel ticketChannel = await guild.CreateChannelAsync("ticket", ChannelType.Text, category);

            if (ticketChannel == null)
            {
                return;
            }

            ulong staffID = 0;

            if (Config.randomAssignment)
            {
                staffID = Database.GetRandomActiveStaff(0)?.userID ?? 0;
            }

            long id = Database.NewTicket(member.Id, staffID, ticketChannel.Id);

            reactionTicketCooldowns.Add(member.Id, DateTime.Now.AddSeconds(10));             // add a cooldown which expires in 10 seconds
            string ticketID = id.ToString("00000");

            await ticketChannel.ModifyAsync(model => model.Name = "ticket-" + ticketID);

            await ticketChannel.AddOverwriteAsync(member, Permissions.AccessChannels, Permissions.None);

            await ticketChannel.SendMessageAsync("Hello, " + member.Mention + "!\n" + Config.welcomeMessage);

            // Remove user's reaction
            await e.Message.DeleteReactionAsync(e.Emoji, e.User);

            // Refreshes the channel as changes were made to it above
            ticketChannel = await SupportBoi.GetClient().GetChannelAsync(ticketChannel.Id);

            if (staffID != 0)
            {
                DiscordEmbed assignmentMessage = new DiscordEmbedBuilder
                {
                    Color       = DiscordColor.Green,
                    Description = "Ticket was randomly assigned to <@" + staffID + ">."
                };
                await ticketChannel.SendMessageAsync(assignmentMessage);

                if (Config.assignmentNotifications)
                {
                    DiscordEmbed message = new DiscordEmbedBuilder
                    {
                        Color       = DiscordColor.Green,
                        Description = "You have been randomly assigned to a newly opened support ticket: " +
                                      ticketChannel.Mention
                    };

                    try
                    {
                        DiscordMember staffMember = await guild.GetMemberAsync(staffID);

                        await staffMember.SendMessageAsync(message);
                    }
                    catch (NotFoundException)
                    {
                    }
                    catch (UnauthorizedException)
                    {
                    }
                }
            }

            // Log it if the log channel exists
            DiscordChannel logChannel = guild.GetChannel(Config.logChannel);

            if (logChannel != null)
            {
                DiscordEmbed logMessage = new DiscordEmbedBuilder
                {
                    Color       = DiscordColor.Green,
                    Description = "Ticket " + ticketChannel.Mention + " opened by " + member.Mention + ".\n",
                    Footer      = new DiscordEmbedBuilder.EmbedFooter {
                        Text = "Ticket " + ticketID
                    }
                };
                await logChannel.SendMessageAsync(logMessage);
            }
        }
		public static DiscordChannel GetVoiceChannelCategory(DiscordGuild guild) => guild.GetChannel(ServersData[guild.Id].VoiceChannelCategory);
        public static Task Discord_Ready(DiscordClient dc, DSharpPlus.EventArgs.ReadyEventArgs args)
        {
            _ = Task.Run(async() => {
                dc.Logger.LogInformation("Looking for Reminders");
                var output = await SQLC.GetReminders();

                if (output.Any())
                {
                    foreach (var item in output)
                    {
                        long ID         = item.ID;
                        long ChannelID  = item.ChannelID;
                        long Date       = item.Date;
                        string Reminder = item.Reminder;

                        try {
                            DiscordGuild Guild     = await dc.GetGuildAsync(GuildID);
                            DiscordMember member   = await Guild.GetMemberAsync((ulong)ID);
                            DiscordChannel channel = Guild.GetChannel((ulong)ChannelID);
                            DateTime dateTime      = DateTime.FromBinary(Date);

                            if (dateTime < DateTime.Now)
                            {
                                await SQLC.DeleteRemindersWithDate(Date);
                                await channel.SendMessageAsync($":alarm_clock:, {member.Mention} you wanted me to remind you the following but I'm Late:\n\n{Reminder}");
                                continue;
                            }

                            _ = Task.Run(async() => {
                                await Task.Delay((int)dateTime.Subtract(DateTime.Now).TotalMilliseconds);

                                DiscordGuild Guild     = await dc.GetGuildAsync(GuildID);
                                DiscordMember member   = await Guild.GetMemberAsync((ulong)ID);
                                DiscordChannel channel = Guild.GetChannel((ulong)ChannelID);

                                await channel.SendMessageAsync($":alarm_clock:, {member.Mention} you wanted me to remind you the following:\n\n{Reminder}");

                                await SQLC.DeleteRemindersWithDate(Date);
                            });
                        } catch (Exception) {
                            await SQLC.DeleteRemindersWithDate(Date);
                            continue;
                        }
                    }
                    dc.Logger.LogInformation("Found Reminders and started them");
                }
                else
                {
                    dc.Logger.LogInformation("No Reminders found");
                }

                dc.Logger.LogInformation("Looking for muted Members");
                output = await SQLC.GetTempmutes();
                if (output.Any())
                {
                    foreach (var item in output)
                    {
                        long ID   = item.ID;
                        long Date = item.Date;

                        try {
                            DiscordGuild Guild    = await dc.GetGuildAsync(GuildID);
                            DiscordRole MutedRole = Guild.GetRole(Program.MutedRole);
                            DiscordMember member  = await Guild.GetMemberAsync((ulong)ID);
                            DateTime dateTime     = DateTime.FromBinary(Date);

                            if (dateTime < DateTime.Now)
                            {
                                await SQLC.DeleteTempmutesWithID(ID);
                                await member.RevokeRoleAsync(MutedRole);
                                continue;
                            }

                            _ = Task.Run(async() => {
                                try {
                                    await Task.Delay((int)dateTime.Subtract(DateTime.Now).TotalMilliseconds);

                                    DiscordGuild Guild    = await dc.GetGuildAsync(GuildID);
                                    DiscordRole MutedRole = Guild.GetRole(Program.MutedRole);
                                    DiscordMember member  = await Guild.GetMemberAsync((ulong)ID);

                                    var PS   = await SQLC.GetPlayer(member.Id);
                                    PS.Muted = false;
                                    await PS.Save();

                                    await member.RevokeRoleAsync(MutedRole);
                                    await SQLC.DeleteTempmutesWithID(ID);
                                } catch (Exception) {
                                    dc.Logger.LogInformation($"Failed the Tempmute process for {member.Username + member.Discriminator}");
                                }
                            });
                        } catch (Exception) {
                            await SQLC.DeleteTempmutesWithID(ID);
                            continue;
                        }
                    }
                    dc.Logger.LogInformation("Found muted Members and starting them");
                }
                else
                {
                    dc.Logger.LogInformation("No muted Members found");
                }

                while (true)
                {
                    foreach (var Status in Statuses)
                    {
                        DiscordActivity activity = new DiscordActivity {
                            ActivityType = ActivityType.Playing,
                            Name         = Status
                        };
                        await dc.UpdateStatusAsync(activity, UserStatus.DoNotDisturb);
                        dc.Logger.LogInformation("Status Update");
                        await Task.Delay(120000);
                    }
                }
            });
            return(Task.CompletedTask);
        }
Beispiel #27
0
        public DiscordListener()
        {
            client = Config.DiscordSocketClient = new DiscordClient(new DiscordConfiguration {
                Token    = Config.DiscordToken,
                LogLevel = LogLevel.Debug
            });
            client.DebugLogger.LogMessageReceived += (sender, args) => {
                switch (args.Level)
                {
                case LogLevel.Debug:
                    Logger.Debug(args.Message);
                    break;

                case LogLevel.Info:
                    Logger.Info(args.Message);
                    break;

                case LogLevel.Warning:
                    Logger.Warn(args.Message);
                    break;

                case LogLevel.Error:
                    Logger.Error(args.Message);
                    break;

                case LogLevel.Critical:
                    Logger.Fatal(args.Message);
                    break;

                default: throw new ArgumentOutOfRangeException();
                }
            };
            client.MessageCreated += OnNewMessage;
            client.Ready          += OnClientOnReady;
            client.ClientErrored  += OnClientError;
            client.SocketErrored  += OnSocketError;
            Task.Run(async() => {
                try{
                    await client.ConnectAsync();
                }
                catch (Exception e) {
                    Logger.Error(e);
                }
            });
            titanusTimer.Elapsed += async(sender, args) => {
                DiscordGuild  guild   = client.Guilds[215943758527594496];
                DiscordMember titanus = await guild.GetMemberAsync(376087025234870272);

                //DiscordMember titanus = await guild.GetMemberAsync(131494148350935040); // Test
                if (titanus.Presence == null)
                {
                    return;                     // Discord sometimes doesn't return the Presence so just return if null
                }

                if (titanus.Presence.Status == UserStatus.Offline)
                {
                    if (!titanusDown)
                    {
                        await guild?.GetChannel(215943758527594496)?.SendMessageAsync("<@206237974105554944> Titanus is down");

                        //await guild?.GetChannel(215943758527594496)?.SendMessageAsync("Down message"); // Test
                        titanusDown = true;
                    }
                }
                else
                {
                    titanusDown = false;
                }
            };
        }