// method handling deletion of messages with attachments
        private async Task QueueDeletedMessagesWithAttachments(SocketUserMessage msg, SocketTextChannel channel, SocketTextChannel messageChannel)
        {
            IReadOnlyCollection <IAttachment> attachments = msg.Attachments;

            // create an embed at the start of the message, add author, color, description,
            // and id of deleted message
            var startBuilder = new EmbedBuilder();

            startBuilder.WithAuthor(msg.Author);
            startBuilder.WithColor(Color.Red);
            startBuilder.WithDescription($"**Message with attachments was deleted in {messageChannel.Mention}**");
            startBuilder.Description += $"\n{msg.Content}";
            startBuilder.AddField("Message ID", msg.Id);
            // send the embed
            await channel.SendMessageAsync("", false, startBuilder.Build());

            // create http client instance to get deleted attachments
            using (var client = new HttpClient()){
                // get enumerator of attachments list
                var enumerator = attachments.GetEnumerator();

                Stream attachment;
                string fName;

                // execute as long as there are items in the list
                while (enumerator.MoveNext())
                {
                    // get filename of the attachment
                    fName = enumerator.Current.Filename;

                    // only image attachments can be downloaded, other throw 404 error
                    // if attachment isn't an image just display name, size
                    // and id of original message
                    if (!enumerator.Current.Width.HasValue && !enumerator.Current.Height.HasValue)
                    {
                        await channel.SendMessageAsync($"ID: {msg.Id}, type: binary\nname: {fName}\nsize: {enumerator.Current.Size} bytes");
                    }
                    // if attachment is image download it and resend it as new
                    else
                    {
                        attachment = await client.GetStreamAsync(enumerator.Current.ProxyUrl);

                        await channel.SendFileAsync(attachment, fName, $"ID: {msg.Id}, type: image");
                    }
                    // wait 5 seconds between attachments
                    await Task.Delay(5000);
                }
            }


            // build and display embed signaling the end of all attachments
            var endBuilder = new EmbedBuilder();

            endBuilder.WithColor(Color.Red);
            endBuilder.WithCurrentTimestamp();
            endBuilder.WithDescription($"End of transmission with ID {msg.Id}");
            await channel.SendMessageAsync("", false, endBuilder.Build());
        }
Exemple #2
0
        public async Task CheckEmoteDateUserChannel(string emoteString, IGuildUser user, SocketTextChannel channel)
        {
            bool success = Emote.TryParse(emoteString, out Emote emote);

            if (success)
            {
                var result = DatabaseService.GetEmoteUserChannelData(emote, user.Id, channel.Id);
                if (result != null)
                {
                    await ReplyAsync(result.ToString());
                }
            }
        }
Exemple #3
0
        }                                                      //Necessary evul.


        public CommandArguments(IBotwinderClient <TUser> client, Command <TUser> command, Server <TUser> server, SocketTextChannel channel, SocketMessage message, string trimmedMessage, string[] messageArgs, CommandOptions options = null)
        {
            this.Client         = client;
            this.Command        = command;
            this.CommandOptions = options;
            this.Server         = server;
            this.Channel        = channel;
            this.Message        = message;
            this.TrimmedMessage = trimmedMessage;
            this.MessageArgs    = messageArgs;
        }
Exemple #4
0
 internal static async void UserSentFile(SocketGuildUser user, SocketTextChannel channel)
 {
     await Task.CompletedTask;
 }
Exemple #5
0
        internal static async void LevelUp(UserAccount userAccount, SocketGuildUser user, SocketTextChannel channel = null)
        {
            if (userAccount.LevelNumber < 10 && (userAccount.LevelNumber % 5) > 0)
            {
                channel = (SocketTextChannel)user.Guild.Channels.Where(c => c.Id == 358276942337671178).FirstOrDefault();
            }
            if (channel == null)
            {
                return;
            }
            // the user leveled up
            var embed = new EmbedBuilder();

            embed.WithColor(Colors.Get(userAccount.Element.ToString()));
            embed.WithTitle("LEVEL UP!");
            embed.WithDescription("<:Up_Arrow:571309108289077258> " + userAccount.GsClass + " " + user.Mention + " just leveled up!");
            embed.AddField("LEVEL", userAccount.LevelNumber, true);
            embed.AddField("XP", userAccount.XP, true);
            await channel.SendMessageAsync("", embed : embed.Build());
        }
        private static async void OnPeriodicUpdate(object source, ElapsedEventArgs e)
        {
            if (!Storage.xs.Settings.IsGDriveOn())
            {
                return;
            }

            if (Storage.xs.Settings.IsTradeMonthActive())
            {
                SocketTextChannel channel = Utils.FindChannel(_discord, Storage.xs.Settings.GetWorkingChannel());
                if (channel != null && Storage.xs.Settings.GetTradeDays() > 0)
                {
                    if (DateTime.Now.CompareTo(Storage.xs.Settings.GetTradeEnd(3)) > 0)
                    {
                        string artMissing = Utils.GetMissingArtToStr(Storage.xs.Entries);
                        if (Storage.xs.Settings.IsForceTradeOn() || string.IsNullOrWhiteSpace(artMissing))
                        {
                            await Modules.TradeEventModule.StartEntryWeek(_discord);
                        }
                    }
                    else if (DateTime.Now.CompareTo(Storage.xs.Settings.GetTradeEnd()) > 0)
                    {
                        string artMissing = Utils.GetMissingArtToStr(Storage.xs.Entries);

                        if (!Storage.xs.Settings.HasNotifyFlag(Storage.ApplicationSettings.NofifyFlags.Closing))
                        {
                            Storage.xs.Settings.SetNotifyDone(Storage.ApplicationSettings.NofifyFlags.Closing);

                            if (!string.IsNullOrWhiteSpace(artMissing))
                            {
                                await channel.SendMessageAsync(embed : Utils.EmbedMessage(_discord, string.Format(Properties.Resources.GOOGLE_TRADE_ENDING_NOW, Config.CmdPrefix, "reveal art", "about"), Utils.Emotion.negative));
                            }

                            foreach (var entry in Storage.xs.Entries.GetStorage())
                            {
                                await Utils.SendPartnerResponse(_discord, entry, Storage.xs.Entries.GetTheme(), true /*notify channel*/);
                            }
                        }

                        if (string.IsNullOrWhiteSpace(artMissing))
                        {
                            await Modules.TradeEventModule.StartEntryWeek(_discord);
                        }
                    }
                    else if (DateTime.Now.CompareTo(Storage.xs.Settings.GetTradeEnd(-1)) > 0)
                    {
                        if (!Storage.xs.Settings.HasNotifyFlag(Storage.ApplicationSettings.NofifyFlags.ThirdNotification))
                        {
                            Storage.xs.Settings.SetNotifyDone(Storage.ApplicationSettings.NofifyFlags.ThirdNotification);

                            string message = string.Format(Properties.Resources.GOOGLE_TRADE_ENDING_SOON, "`tomorrow`");

                            await channel.SendMessageAsync(embed : Utils.EmbedMessage(_discord, message, Utils.Emotion.positive));

                            await Utils.NotifySubscribers(_discord, "the art trade will be ending `tomorrow`");
                        }
                    }
                    else if (DateTime.Now.CompareTo(Storage.xs.Settings.GetTradeEnd(-3)) > 0)
                    {
                        if (!Storage.xs.Settings.HasNotifyFlag(Storage.ApplicationSettings.NofifyFlags.SecondNotification))
                        {
                            Storage.xs.Settings.SetNotifyDone(Storage.ApplicationSettings.NofifyFlags.SecondNotification);

                            string message = string.Format(Properties.Resources.GOOGLE_TRADE_ENDING_SOON, "in `3` days");

                            await channel.SendMessageAsync(embed : Utils.EmbedMessage(_discord, message, Utils.Emotion.positive));

                            await Utils.NotifySubscribers(_discord, "the art trade will be ending in `3` days");
                        }
                    }
                    else if (DateTime.Now.CompareTo(Storage.xs.Settings.GetTradeEnd(-7)) > 0)
                    {
                        if (!Storage.xs.Settings.HasNotifyFlag(Storage.ApplicationSettings.NofifyFlags.FirstNotification))
                        {
                            Storage.xs.Settings.SetNotifyDone(Storage.ApplicationSettings.NofifyFlags.FirstNotification);

                            string message = string.Format(Properties.Resources.GOOGLE_TRADE_ENDING_SOON, "in `7` days");

                            await channel.SendMessageAsync(embed : Utils.EmbedMessage(_discord, message, Utils.Emotion.positive));

                            await Utils.NotifySubscribers(_discord, "the art trade will be ending in `7` days");
                        }
                    }
                }
            }

            await UploadGoogleFile(Storage.xs.ENTRIES_PATH);
            await UploadGoogleFile(Storage.xs.SETTINGS_PATH);
        }
Exemple #7
0
        internal static async Task RemoveClassSeries(string series, SocketGuildUser user, SocketTextChannel channel)
        {
            var avatar = EntityConverter.ConvertUser(user);

            if (!avatar.BonusClasses.Contains(series))
            {
                return;
            }

            avatar.BonusClasses.Remove(series);
            UserAccountProvider.StoreUser(avatar);
            var embed = new EmbedBuilder();

            embed.WithColor(Colors.Get("Iodem"));
            embed.WithDescription($"{series} was removed from {user.Mention}.");
            await channel.SendMessageAsync("", false, embed.Build());
        }
Exemple #8
0
        public async Task MuteUser(SocketGuildUser User = null, ulong interval = 0, [Remainder] string reason = null)
        {
            var  x     = ServerList.getServer(Context.Guild);
            bool perms = false;
            var  GUser = (SocketGuildUser)Context.Message.Author;

            if (User == null)
            {
                EmbedBuilder e = Error.avb02(Context.Guild);
                await ReplyAsync("", false, e.Build());
            }
            else if (interval == 0)
            {
                EmbedBuilder e = Error.avb11();
                await ReplyAsync("", false, e.Build());
            }
            else if (x.ServerLogChannel == "avb01")
            {
                EmbedBuilder e = Error.avb01(Context.Guild);
                await ReplyAsync("", false, e.Build());
            }
            else if (reason == null)
            {
                EmbedBuilder e = Error.avb04();
                await ReplyAsync("", false, e.Build());
            }
            else
            {
                var f = ulong.TryParse(x.ServerLogChannel, out ulong res);
                SocketTextChannel log = Context.Guild.GetTextChannel(res);
                if (Context.Message.Author == Context.Guild.Owner)
                {
                    perms = true;
                }
                if (x.MuteUserIDs.Contains(Context.Message.Author.Id))
                {
                    perms = true;
                }
                foreach (SocketRole rolex in GUser.Roles)
                {
                    if (x.MuteRoleIDs.Contains(rolex.Id))
                    {
                        perms = true;
                    }
                }
                switch (perms)
                {
                case true:
                    await User.ModifyAsync(u => u.Mute = true);

                    EmbedBuilder e = Logs.avb13(User, reason, Context.Message.Author, interval);
                    await log.SendMessageAsync("", false, e.Build());

                    x.TimeoutLength.Add(interval);
                    x.TimeoutReason.Add($"{reason}");
                    x.TimeoutUsersID.Add(User.Id);
                    await Timeouts.InstantiateTimer(User, interval, reason, GUser, x.ServerLogChannel, x.ServerID);

                    break;

                case false:
                    EmbedBuilder es = Error.avb03();
                    await ReplyAsync("", false, es.Build());

                    break;
                }
            }
        }
Exemple #9
0
        protected override async Task HandleCommandGuildAsync(GuildCommandContext context)
        {
            if (channel == null)
            {
                ulong channelId = 0;
                switch (channelType)
                {
                case OutputChannelType.debuglogging:
                    channelId = GuildChannelHelper.DebugChannelId;
                    break;

                case OutputChannelType.welcoming:
                    channelId = GuildChannelHelper.WelcomingChannelId;
                    break;

                case OutputChannelType.admincommandlog:
                    channelId = GuildChannelHelper.AdminCommandUsageLogChannelId;
                    break;

                case OutputChannelType.adminnotifications:
                    channelId = GuildChannelHelper.AdminNotificationChannelId;
                    break;

                case OutputChannelType.interactive:
                    channelId = GuildChannelHelper.InteractiveMessagesChannelId;
                    break;

                case OutputChannelType.guildcategory:
                    channelId = GuildChannelHelper.GuildCategoryId;
                    break;
                }

                channel = context.Guild.GetTextChannel(channelId);
                SocketTextChannel textChannel = channel as SocketTextChannel;

                await context.Channel.SendEmbedAsync($"Current setting for `{channelType}` is {(channel == null ? Markdown.InlineCodeBlock(channelId) : (textChannel == null ? channel.Name : textChannel.Mention))}");
            }
            else
            {
                switch (channelType)
                {
                case OutputChannelType.debuglogging:
                    GuildChannelHelper.DebugChannelId = channel.Id;
                    break;

                case OutputChannelType.welcoming:
                    GuildChannelHelper.WelcomingChannelId = channel.Id;
                    break;

                case OutputChannelType.admincommandlog:
                    GuildChannelHelper.AdminCommandUsageLogChannelId = channel.Id;
                    break;

                case OutputChannelType.adminnotifications:
                    GuildChannelHelper.AdminNotificationChannelId = channel.Id;
                    break;

                case OutputChannelType.interactive:
                    GuildChannelHelper.InteractiveMessagesChannelId = channel.Id;
                    break;

                case OutputChannelType.guildcategory:
                    GuildChannelHelper.GuildCategoryId = channel.Id;
                    break;
                }
                await SettingsModel.SaveSettings();

                SocketTextChannel textChannel = channel as SocketTextChannel;

                await context.Channel.SendEmbedAsync($"Set setting for `{channelType}` to {(textChannel == null ? channel.Name : textChannel.Mention)}");
            }
        }
 public async Task AddChannel([Remainder] SocketTextChannel channel) => await AddChannel(channel.Id.ToString());
Exemple #11
0
        public async Task Start()
        {
            Configuration.configure();

            //create client and add what serverity of information to log
            client = new DiscordSocketClient(new DiscordSocketConfig()
            {
                LogLevel            = LogSeverity.Info,
                ExclusiveBulkDelete = false,
            });

            //create template for logged messages
            client.Log += (message) =>
            {
                Console.WriteLine(message.ToString());
                return(Task.CompletedTask);
            };

            //when client is ready, load important information to memory for quick access and set game to help message
            client.Ready += async() =>
            {
                await client.SetGameAsync("Use +help");

                PrefixService.LoadPrefixs(client);
                WelcomeService.LoadWelcomes(client);
                LeavingService.Loadleaving(client);
                XpService.Loadxps(client);

                //start timer for xp module
                XpService.timerStart();

                //if version from data file has changed, reset update time (used to track time since update)
                if (Justibot.Loader.checkUpdate().Value != Justibot.Data.version)
                {
                    Justibot.Saver.addVersion(DateTime.Now, Justibot.Data.version);
                }
            };

            //log the client into discord with the bot token
            await client.LoginAsync(TokenType.Bot, Configuration.config.Token);

            await client.StartAsync();

            //when a user joins a guild, check appropriate permissions and react accordingly
            client.UserJoined += async(user) =>
            {
                //check welcome module
                var results = Justibot.Loader.LoadPerm(user, "WELCOME");
                var guild   = user.Guild as IGuild;
                //if welcome module enabled send message
                if (results.Item1 == true)
                {
                    ulong result2 = results.Item2;
                    //get designated channel for welcome messages
                    SocketTextChannel welcomeChannel = user.Guild.GetChannel(result2) as SocketTextChannel;

                    //if welcome message is available for guild use it, otherwise use default
                    bool check = welcomedict.welcomes.TryGetValue(guild.Id, out string welcome);
                    if (!check)
                    {
                        welcome = "Welcome, **[user]** has joined **[server]!!!** \n" +
                                  "Have a good time!!!";
                    }
                    //fill in placeholder text with appropriate information
                    welcome = welcome.Replace("[user]", user.Username);
                    welcome = welcome.Replace("[server]", guild.Name);

                    //if permission argument is plain send message in plain text otherwise send in embeded message
                    if (results.Item3 == "PLAIN")
                    {
                        await welcomeChannel.SendMessageAsync(welcome);
                    }
                    else
                    {
                        string avatar = user.GetAvatarUrl();
                        if (avatar == null)
                        {
                            avatar = "https://cdn.discordapp.com/embed/avatars/0.png";
                        }
                        Color color = new Color(0, 255, 0);
                        if (avatar.Contains("/a_"))
                        {
                            avatar = $"{avatar.Remove(avatar.Length - 12)}gif?size=128";
                        }

                        var embed = new EmbedBuilder()
                                    .WithColor(color)
                                    .WithTitle($"{Format.Bold($"{client.CurrentUser.Username}:")}")
                                    .WithDescription(welcome)
                                    .WithThumbnailUrl(avatar)
                                    .Build();

                        await welcomeChannel.SendMessageAsync(user.Mention, false, embed);
                    }
                }
                //if joining role is enabled give new user the role
                var joinRoles = Justibot.Loader.LoadPerm(user, "JOINROLE");
                if (joinRoles.Item1 == true)
                {
                    IRole joinerRole = user.Guild.GetRole(joinRoles.Item2) as IRole;
                    await user.AddRoleAsync(joinerRole);
                }
                //if log permission enabled send message to log channel
                var results2 = Justibot.Loader.LoadPerm(user, "LOG");
                if (results2.Item1 == true)
                {
                    ulong             result2    = results2.Item2;
                    SocketTextChannel logChannel = user.Guild.GetChannel(result2) as SocketTextChannel;

                    if (results2.Item3 == "PLAIN")
                    {
                        await logChannel.SendMessageAsync($"{Format.Bold($"{user.Username}")}#{user.Discriminator}, ID:<{user.Id}> has joined the server. \n" +
                                                          $"There are now {user.Guild.MemberCount} members.");
                    }
                    else
                    {
                        string avatar = user.GetAvatarUrl();
                        Color  color  = new Color(0, 255, 0);
                        //if no avatar available use deafult
                        if (avatar == null)
                        {
                            avatar = "https://cdn.discordapp.com/embed/avatars/0.png";
                        }
                        //check if avatar is gif (gif avatars contain /a_ in their URLs
                        if (avatar.Contains("/a_"))
                        {
                            avatar = $"{avatar.Remove(avatar.Length - 12)}gif?size=128";
                        }

                        var embed = new EmbedBuilder()
                                    .WithColor(color)
                                    .WithTitle($"{Format.Bold($"{client.CurrentUser.Username}:")}")
                                    .WithDescription($"{Format.Bold($"{user.Username}")}#{user.Discriminator}, ID:<{user.Id}> has joined the server. \n" +
                                                     $"There are now {user.Guild.MemberCount} members.")
                                    .WithThumbnailUrl(avatar)
                                    .Build();

                        await logChannel.SendMessageAsync("", false, embed);
                    }
                }
                //if bunker mode is enabled on server instantly kick new user
                if (Settings.bunker.Contains(guild.Id))
                {
                    await user.Guild.DefaultChannel.SendMessageAsync($"{Format.Bold($"{user.Username}")} was kicked by bunker mode!");

                    await user.KickAsync("Bunker mode enabled");
                }
            };

            //when user leaves guild check appropriate permissions and act accordingly
            client.UserLeft += async(user) =>
            {
                //check leaving permission
                var results = Justibot.Loader.LoadPerm(user, "LEAVING");
                if (results.Item1 == true)
                {
                    ulong result2 = results.Item2;
                    var   guild   = user.Guild as IGuild;
                    //get channel to send leaving message to
                    SocketTextChannel leaveChannel = user.Guild.GetChannel(result2) as SocketTextChannel;

                    //if leaving message available set it, else use default message
                    bool check = welcomedict.leaves.TryGetValue(guild.Id, out string leave);
                    if (!check)
                    {
                        leave = "**[mention]** has left **[server]**, goodbye.";
                    }
                    //replace placeholder text with appropriate items
                    leave = leave.Replace("[user]", user.Username);
                    leave = leave.Replace("[mention]", user.Mention);
                    leave = leave.Replace("[server]", guild.Name);

                    //if leaving permission argument is plain, send plain text otherwise send as an embed message
                    if (results.Item3 == "PLAIN")
                    {
                        await leaveChannel.SendMessageAsync(leave);
                    }
                    else
                    {
                        string avatar = user.GetAvatarUrl();
                        Color  color  = new Color(255, 0, 0);
                        //if no avatar available use deafult
                        if (avatar == null)
                        {
                            avatar = "https://cdn.discordapp.com/embed/avatars/0.png";
                        }
                        //check if avatar is gif (gif avatars contain /a_ in their URLs
                        if (avatar.Contains("/a_"))
                        {
                            avatar = $"{avatar.Remove(avatar.Length - 12)}gif?size=128";
                        }

                        var embed = new EmbedBuilder()
                                    .WithColor(color)
                                    .WithTitle($"{Format.Bold($"{client.CurrentUser.Username}:")}")
                                    .WithDescription(leave)
                                    .WithThumbnailUrl(avatar)
                                    .Build();

                        await leaveChannel.SendMessageAsync("", false, embed);
                    }
                }

                //if log module is enabled, send message to log channel bassed on argument (plain text or embed)
                var results2 = Justibot.Loader.LoadPerm(user, "LOG");
                if (results2.Item1 == true)
                {
                    ulong             result2        = results2.Item2;
                    var               guild          = user.Guild as IGuild;
                    SocketTextChannel welcomeChannel = user.Guild.GetChannel(result2) as SocketTextChannel;

                    if (results2.Item3 == "PLAIN")
                    {
                        await welcomeChannel.SendMessageAsync($"{Format.Bold($"{user.Username}")}#{user.Discriminator}, ID:<{user.Id}> has left the server. \n" +
                                                              $"There are now {user.Guild.MemberCount} members.");
                    }
                    else
                    {
                        string avatar = user.GetAvatarUrl();
                        Color  color  = new Color(255, 0, 0);
                        //if no avatar available use deafult
                        if (avatar == null)
                        {
                            avatar = "https://cdn.discordapp.com/embed/avatars/0.png";
                        }
                        //check if avatar is gif (gif avatars contain /a_ in their URLs
                        if (avatar.Contains("/a_"))
                        {
                            avatar = $"{avatar.Remove(avatar.Length - 12)}gif?size=128";
                        }

                        var embed = new EmbedBuilder()
                                    .WithColor(color)
                                    .WithTitle($"{Format.Bold($"{client.CurrentUser.Username}:")}")
                                    .WithDescription($"{Format.Bold($"{user.Username}")}#{user.Discriminator}, ID:<{user.Id}> has left the server. \n" +
                                                     $"There are now {user.Guild.MemberCount} members.")
                                    .WithThumbnailUrl(avatar)
                                    .Build();

                        await welcomeChannel.SendMessageAsync("", false, embed);
                    }
                }
            };

            //if user messages a channel the bot can see, check permissions
            client.MessageReceived += async(message) =>
            {
                var guild = (message.Channel as SocketTextChannel)?.Guild;
                var user  = (message.Author as IGuildUser);
                if (guild != null)
                {
                    //if user isnt bot, give xp to user
                    if (user.IsBot == false)
                    {
                        var guild2 = guild as IGuild;
                        XpService.AddXp(user, guild2);
                    }
                    //if message contains a discord invite link, check if use has manage guild permissions
                    if ((message.ToString().ToUpper()).Contains("DISCORD.GG/") && (!(user.IsBot)))
                    {
                        //if user does not have manage guild permission check if advertising module is enabled
                        if (!(user.GuildPermissions.Has(GuildPermission.ManageGuild)) || !(Justibot.Loader.isStaff(user)))
                        {
                            var results = Justibot.Loader.LoadPerm(user, "ADVERTISING");
                            if (results.Item1 == true)
                            {
                                //if module is set to delete, remove message and asks user to not advertise in the server
                                ulong result2 = results.Item2;
                                if (results.Item3 == "DELETE")
                                {
                                    await message.DeleteAsync();

                                    var response = await message.Channel.SendMessageAsync($"{user.Mention} please do not advertise in this server");

                                    respond(response);
                                }
                                //if module is set to repost, send copy of message to advertising channel and ask user to only post advertisements to channel
                                else if (results.Item3 == "REPOST")
                                {
                                    SocketTextChannel advertisingChannel = guild.GetChannel(result2) as SocketTextChannel;
                                    if (message.Channel != advertisingChannel)
                                    {
                                        await advertisingChannel.SendMessageAsync($"{user.Mention} advertised message: \n{message.ToString()}");

                                        await message.DeleteAsync();

                                        var response = await message.Channel.SendMessageAsync($"{user.Mention} please keep advertising to {advertisingChannel.Mention}, your message has been shifted there.");

                                        respond(response);
                                    }
                                }
                            }
                        }
                    }
                }
            };
            //initialize commands and commandhandler
            handler = new CommandHandler();
            await handler.InitCommands(client);

            //prevent application shutdown
            await Task.Delay(-1);
        }
Exemple #12
0
 // Notify everyone that I'm ready to roll
 private async Task LlamaReady()
 {
     SocketTextChannel initChannel = (SocketTextChannel)_client.GetChannel(500863591977713674);
     await initChannel.SendMessageAsync("Let's start shamin llama");
 }
Exemple #13
0
        public async void StartPosting(DA_MainWindow MainWindow)// purge discord channel and start posting
        {
            Public_MainWindow = MainWindow;
            if (Public_MainWindow.ServerID != 0)
            {
                try
                {
                    var bc = new BrushConverter();
                    try
                    {
                        Application.Current.Dispatcher.Invoke((Action)(() => {
                            Public_MainWindow.DiscordBotConnectionStatusLabel.Foreground = (Brush)bc.ConvertFrom("#FFF1F1F1");
                            Public_MainWindow.DiscordBotConnectionStatusLabel.Content = Public_MainWindow.LanguageCollection[6].ToString();//"Connecting...";
                        }));
                        await Public_MainWindow.discord.LoginAsync(TokenType.Bot, Public_MainWindow.Token);

                        await Public_MainWindow.discord.StartAsync();

                        System.Threading.Thread.Sleep(1000);
                    }
                    catch (Exception)
                    {
                        Application.Current.Dispatcher.Invoke((Action)(() => {
                            Public_MainWindow.DiscordBotConnectionStatusLabel.Foreground = (Brush)bc.ConvertFrom("#FFBB3D3D");
                            Public_MainWindow.DiscordBotConnectionStatusLabel.Content = Public_MainWindow.LanguageCollection[7].ToString();//"Connection ERROR!";
                        }));
                    }

                    if (Public_MainWindow.discord.ConnectionState == Discord.ConnectionState.Connected)
                    {
                        var guild = Public_MainWindow.discord.GetGuild(Public_MainWindow.ServerID);
                        SocketTextChannel channel = guild.GetTextChannel(Public_MainWindow.Main_BotChannel_ID);

                        var messages = await channel.GetMessagesAsync(100).FlattenAsync(); //defualt is 100

                        System.Threading.Thread.Sleep(2000);
                        await(channel as SocketTextChannel).DeleteMessagesAsync(messages);
                        var    embed1    = new EmbedBuilder();
                        string ANmessage = "";
                        Application.Current.Dispatcher.Invoke((Action)(() => {
                            string[] pbu = Public_MainWindow.publicbossUrl.Split('|');
                            string[] bnu = Public_MainWindow.CbossNameLabel.Content.ToString().Split('&');

                            if (Public_MainWindow.CbossNameLabel.Content.ToString().Contains("&"))
                            {
                                ANmessage = Public_MainWindow.LanguageCollection[123].ToString() + Environment.NewLine + "[" + bnu[0] + "](" + pbu[0] + ")" + " <---" + Public_MainWindow.LanguageCollection[85].ToString() + Environment.NewLine + "[" + bnu[1] + "](" + pbu[1] + ")" + " <---" + Public_MainWindow.LanguageCollection[85].ToString();
                            }
                            else
                            {
                                ANmessage = Public_MainWindow.LanguageCollection[123].ToString() + Environment.NewLine + "[" + bnu[0] + "](" + pbu[0] + ")" + " <---" + Public_MainWindow.LanguageCollection[85].ToString();
                            }
                            embed1 = new EmbedBuilder
                            {
                                Title = Public_MainWindow.CbossNameLabel.Content.ToString() /* + " <---" + LanguageCollection[87].ToString()*/,
                                ImageUrl = Public_MainWindow.publicNbossimage,
                                Color = Discord.Color.LightGrey,
                                //Url = publicbossUrl,
                                Description = ANmessage
                            };
                        }));
                        //Emoji emj = new Emoji("<:download1:832276391789199430>");
                        //var s = guild.Emotes;
                        //var exampleFooter = new EmbedFooterBuilder().WithText(
                        //      "Reaction 1" + " 0️⃣ " + Environment.NewLine
                        //    + "Reaction 2" + Environment.NewLine
                        //    + "Reaction 3" + Environment.NewLine);
                        //embed1.WithFooter(exampleFooter);


                        var BossImage = await channel.SendMessageAsync("", false, embed1.Build());

                        var AlertChannel = guild.TextChannels.FirstOrDefault(ch => ch.Id == Public_MainWindow.Alert_BotChannel_ID);
                        var Alert_Embed  = new EmbedBuilder
                        {
                            Title        = "YPBBT is Connected" /*+ " <---" + LanguageCollection[87].ToString()*/,
                            ThumbnailUrl = "https://raw.githubusercontent.com/kresmes/BDO-Boss-Timer-Discord-Bot-Yuri-Project-/master/Resources/Images/Connected.png",
                            Color        = Discord.Color.LightGrey,
                            //Url = publicbossUrl
                            Description = "All Notifications Will be Send to this channel"
                        };
                        await AlertChannel.SendMessageAsync("", false, Alert_Embed.Build());

                        Public_MainWindow.bossImageID = BossImage.Id;

                        //var embed = new EmbedBuilder
                        //{
                        //    Title = "Boss Name"
                        //};
                        //embed.AddField("Next Boss in:", "00:00:00", true);
                        //embed.AddField("Night In:", "00:00:00", true);
                        //embed.AddField("Imperial Reset:", "00:00:00", true)
                        //     .WithColor(Color.Blue)
                        //     .WithUrl("https://example.com")
                        //    .Build();
                        //var MainMessage = await channel.SendMessageAsync("", false, embed.Build());

                        string message = "";
                        Application.Current.Dispatcher.Invoke((Action)(() => {
                            string nb = "> ```cs" + Environment.NewLine + "> " + Public_MainWindow.CurrentBossTimeLabel.Content.ToString() + Environment.NewLine + "> " + "```";
                            string nti = "> ```cs" + Environment.NewLine + "> " + Public_MainWindow.NightInBdoTimeLabel.Content.ToString() + Environment.NewLine + "> " + "```";
                            string iri = "> ```cs" + Environment.NewLine + "> " + Public_MainWindow.IRTimeLabel.Content.ToString() + Environment.NewLine + "> " + "```";
                            string br = "> ```cs" + Environment.NewLine + "> " + Public_MainWindow.BRTimeLabel.Content.ToString() + Environment.NewLine + "> " + "```";
                            string itr = "> ```cs" + Environment.NewLine + "> " + Public_MainWindow.ITRITimeLabel.Content.ToString() + Environment.NewLine + "> " + "```";
                            if (Public_MainWindow.CurrentBossTimeLabel.Content.ToString().StartsWith("00:"))
                            {
                                nb = "> ```css" + Environment.NewLine + "> " + Public_MainWindow.CurrentBossTimeLabel.Content.ToString() + Environment.NewLine + "> " + "```";
                            }
                            if (Public_MainWindow.NightInBdoTimeLabel.Content.ToString().StartsWith("00:"))
                            {
                                nti = "> ```css" + Environment.NewLine + "> " + Public_MainWindow.NightInBdoTimeLabel.Content.ToString() + Environment.NewLine + "> " + "```";
                            }
                            if (Public_MainWindow.IRTimeLabel.Content.ToString().StartsWith("00:"))
                            {
                                iri = "> ```css" + Environment.NewLine + "> " + Public_MainWindow.IRTimeLabel.Content.ToString() + Environment.NewLine + "> " + "```";
                            }
                            if (Public_MainWindow.BRTimeLabel.Content.ToString().StartsWith("00:"))
                            {
                                br = "> ```css" + Environment.NewLine + "> " + Public_MainWindow.BRTimeLabel.Content.ToString() + Environment.NewLine + "> " + "```";
                            }
                            if (Public_MainWindow.ITRITimeLabel.Content.ToString().StartsWith("00:"))
                            {
                                itr = "> ```css" + Environment.NewLine + "> " + Public_MainWindow.ITRITimeLabel.Content.ToString() + Environment.NewLine + "> " + "```";
                            }


                            message = "> " + Public_MainWindow.CbossLabel.Content.ToString() + Environment.NewLine
                                      + nb + Environment.NewLine
                                      + "> " + Public_MainWindow.NILabel.Content.ToString() + Environment.NewLine
                                      + nti + Environment.NewLine
                                      + "> " + Public_MainWindow.IRILabel.Content.ToString() + Environment.NewLine
                                      + iri + Environment.NewLine
                                      + "> " + Public_MainWindow.BRILabel.Content.ToString() + Environment.NewLine
                                      + br + Environment.NewLine
                                      + "> " + Public_MainWindow.ITRILabel.Content.ToString() + Environment.NewLine
                                      + itr;
                        }));
                        Public_MainWindow.MainMessage = await channel.SendMessageAsync(message);

                        Public_MainWindow.MainMessageID = Public_MainWindow.MainMessage.Id;
                        Application.Current.Dispatcher.Invoke((Action)(() => {
                            if (Public_MainWindow.DiscordBotConnectionStatusLabel.Content.ToString() == Public_MainWindow.LanguageCollection[6].ToString())
                            {
                                Public_MainWindow.DiscordBotConnectionStatusLabel.Foreground = (Brush)bc.ConvertFrom("#FF669174");
                                Public_MainWindow.DiscordBotConnectionStatusLabel.Content = Public_MainWindow.LanguageCollection[8].ToString();//"Connected";
                            }
                        }));
                        bool DTT_isChecked = false;
                        Application.Current.Dispatcher.Invoke((Action)(() => { DTT_isChecked = Public_MainWindow.DisplayTimeTableSetting.IsChecked.Value; }));

                        if (DTT_isChecked)
                        {
                            var timetablemessage = await channel.SendFileAsync(System.IO.Directory.GetCurrentDirectory() + "/Resources/TimeTable.png", Public_MainWindow.MOTR.ToString().ToUpper() + Public_MainWindow.LanguageCollection[43].ToString());

                            Public_MainWindow.TimtableID = timetablemessage.Id;
                        }

                        if (Public_MainWindow.discord.ConnectionState == Discord.ConnectionState.Connected)
                        {
                            Application.Current.Dispatcher.Invoke((Action)(() => { MainWindow.SelfRollingStartUp(); }));
                        }
                        Public_MainWindow.isposting = 1;
                    }
                }
                catch (Exception s)
                {
                    if (s is Discord.Net.HttpException)
                    {
                        await Public_MainWindow.discord.StopAsync();

                        Application.Current.Dispatcher.Invoke((Action)(() => {
                            ErrorMessageBox emb = new ErrorMessageBox(Public_MainWindow.LanguageCollection[119].ToString(), Public_MainWindow.LanguageCollection[120].ToString(), Public_MainWindow.LanguageCollection[121].ToString(), Public_MainWindow.LanguageCollection[122].ToString());
                            emb.MB_typeOK(Public_MainWindow.LanguageCollection[108].ToString(), s.Message + Environment.NewLine + Environment.NewLine + Public_MainWindow.LanguageCollection[115].ToString(), Public_MainWindow);
                            emb.Show();
                            Public_MainWindow.IsEnabled = false;
                        }));
                    }
                    if (s is System.ArgumentOutOfRangeException)
                    {
                        await Public_MainWindow.discord.StopAsync();

                        Application.Current.Dispatcher.Invoke((Action)(() => {
                            ErrorMessageBox emb = new ErrorMessageBox(Public_MainWindow.LanguageCollection[119].ToString(), Public_MainWindow.LanguageCollection[120].ToString(), Public_MainWindow.LanguageCollection[121].ToString(), Public_MainWindow.LanguageCollection[122].ToString());
                            emb.MB_typeOK(Public_MainWindow.LanguageCollection[108].ToString(), s.Message + Environment.NewLine + Environment.NewLine + Public_MainWindow.LanguageCollection[116].ToString(), Public_MainWindow);
                            emb.Show();
                            Public_MainWindow.IsEnabled = false;
                        }));
                    }
                    if (s is System.NullReferenceException)
                    {
                        Application.Current.Dispatcher.Invoke((Action)(() => {
                            ErrorMessageBox emb = new ErrorMessageBox(Public_MainWindow.LanguageCollection[119].ToString(), Public_MainWindow.LanguageCollection[120].ToString(), Public_MainWindow.LanguageCollection[121].ToString(), Public_MainWindow.LanguageCollection[122].ToString());
                            emb.MB_typeOK(Public_MainWindow.LanguageCollection[113].ToString(), Public_MainWindow.LanguageCollection[124].ToString(), Public_MainWindow);
                            emb.Show();
                            Public_MainWindow.IsEnabled = false;
                        }));
                    }
                    var bc = new BrushConverter();
                    Application.Current.Dispatcher.Invoke((Action)(() => {
                        Public_MainWindow.DiscordBotConnectionStatusLabel.Foreground = (Brush)bc.ConvertFrom("#FFBB3D3D");
                        Public_MainWindow.DiscordBotConnectionStatusLabel.Content = Public_MainWindow.LanguageCollection[7].ToString();
                    }));

                    /*StartPosting();*/
                }
            }
            else
            {
                Application.Current.Dispatcher.Invoke((Action)(() => {
                    ErrorMessageBox emb = new ErrorMessageBox(Public_MainWindow.LanguageCollection[119].ToString(), Public_MainWindow.LanguageCollection[120].ToString(), Public_MainWindow.LanguageCollection[121].ToString(), Public_MainWindow.LanguageCollection[122].ToString());
                    emb.MB_typeOK(Public_MainWindow.LanguageCollection[113].ToString(), Public_MainWindow.LanguageCollection[124].ToString(), Public_MainWindow);
                    emb.Show();
                    Public_MainWindow.IsEnabled = false;
                }));
            }
        }
        public async Task <string> CreateMessage(string template, SocketGuildUser User, SocketTextChannel rulechannel)
        {
            try
            {
                string ap = "";
                if (String.IsNullOrWhiteSpace(template) == false && User != null && rulechannel != null)
                {
                    if (template.Contains("%user%") && template.Contains("%channel%"))
                    {
                        ap = (template.Replace("%user%", User.Mention)).Replace("%channel%", rulechannel.Mention);
                        //ap = ap

                        return(ap);
                    }
                    if (template.Contains("%user%"))
                    {
                        ap = template.Replace("%user%", User.Mention);
                    }

                    if (template.Contains("%channel%"))
                    {
                        ap = template.Replace("%channel%", rulechannel.Mention);
                    }
                }

                return(ap);
            }
            catch (Exception ex)
            {
                CommonTools.ErrorReporting(ex);
                return(null);
            }
        }
Exemple #15
0
        public async Task TopByChannels(int page = 1)
        {
            try
            {
                if (page < 1)
                {
                    await CommandHandeling.ReplyAsync(Context,
                                                      "Boole! Try different page <_<");

                    return;
                }

                var guildAccount        = ServerAccounts.GetServerAccount(Context.Guild);
                var allTextChannelsList = Context.Guild.TextChannels.ToList();

                var knownTextChannelsList = guildAccount.MessagesReceivedStatisctic.ToList();

                const int usersPerPage = 8;

                var lastPage = 1 + allTextChannelsList.Count / (usersPerPage + 1);
                if (page > lastPage)
                {
                    await CommandHandeling.ReplyAsync(Context,
                                                      $"Boole. Last Page is {lastPage}");

                    return;
                }

                guildAccount.MessagesReceivedStatisctic = new ConcurrentDictionary <string, ulong>();
                foreach (var t1 in allTextChannelsList)
                {
                    ulong num = 0;
                    foreach (var t in knownTextChannelsList)
                    {
                        if (t1.Id.ToString() == t.Key)
                        {
                            num = t.Value;
                        }
                    }


                    guildAccount.MessagesReceivedStatisctic.AddOrUpdate(t1.Id.ToString(), num, (key, value) => num);
                    ServerAccounts.SaveServerAccounts();
                }

                var orderedKnownChannels = guildAccount.MessagesReceivedStatisctic
                                           .OrderByDescending(channels => channels.Value).ToList();

                var embB = new EmbedBuilder()
                           .WithTitle("Top By Activity In Text Channels:")
                           .WithFooter(
                    $"Page {page}/{lastPage} ● Say \"topChan 2\" to see second page (you can edit previous message)")
                           .WithDescription(
                    "If `Messages Count: 0` that means, I can't read the channel, or no one using it.\n");

                page--;

                for (var i = 1; i <= usersPerPage && i + usersPerPage * page <= orderedKnownChannels.Count; i++)
                {
                    var num = i - 1 + usersPerPage * page;
                    SocketTextChannel something = null;
                    foreach (var t in allTextChannelsList)
                    {
                        if (orderedKnownChannels[num].Key == t.Id.ToString())
                        {
                            something = Context.Guild.GetTextChannel(t.Id);
                        }
                    }

                    var cat = "error";
                    if (something == null)
                    {
                        continue;
                    }
                    if (something.Category != null)
                    {
                        cat = something.Category.Name;
                    }

                    embB.AddField($"#{i + usersPerPage * page} {something.Name}",
                                  $"**Messages Count:** {orderedKnownChannels[num].Value}\n" +
                                  $"**Average per day:** {orderedKnownChannels[num].Value / 7}\n" +
                                  $"**Members:** {something.Users.Count}\n" +
                                  $"**Created:** {something.CreatedAt.DateTime}\n" +
                                  $"**Category:** {cat}\n" +
                                  $"**IsNsfw:** {something.IsNsfw.ToString()}\n" +
                                  $"**Position:** {something.Position}\n" +
                                  $"**ID:** {something.Id}\n\n**_____**", true);
                }

                await CommandHandeling.ReplyAsync(Context, embB);
            }
            catch
            {
                //   Console.WriteLine(e.Message);
            }
        }
Exemple #16
0
        private async Task <ulong> Update(ulong guildId, ulong channelId, ulong messageId, string header, int minDays, int maxDays)
        {
            SocketTextChannel channel = (SocketTextChannel)Program.DiscordClient.GetChannel(channelId);

            StringBuilder builder = new StringBuilder();

            /*builder.Append("**");
            *  builder.Append(header);
            *  builder.AppendLine("**");
            *  builder.AppendLine();*/

            Dictionary <int, List <(Event, Instant)> > eventSchedule = new Dictionary <int, List <(Event, Instant)> >();

            DateTimeZone zone = DateTimeZoneProviders.Tzdb.GetSystemDefault();

            Dictionary <string, object> filters = new Dictionary <string, object>();

            filters.Add("ServerIdStr", guildId.ToString());

            List <Event> events = await EventsService.EventsDatabase.LoadAll(filters);

            foreach (Event evt in events)
            {
                List <Occurance> occurances = evt.GetNextOccurances();

                foreach (Occurance occurance in occurances)
                {
                    Instant instant = occurance.GetInstant();
                    int     days    = TimeUtils.GetDaysTill(instant, zone);

                    if (!eventSchedule.ContainsKey(days))
                    {
                        eventSchedule.Add(days, new List <(Event, Instant)>());
                    }

                    eventSchedule[days].Add((evt, instant));
                }
            }

            int count = 0;

            for (int i = minDays; i < maxDays; i++)
            {
                if (!eventSchedule.ContainsKey(i))
                {
                    continue;
                }

                List <(Event, Instant)> eventsDay = eventSchedule[i];

                builder.Append("__");
                builder.Append(TimeUtils.GetDayName(i));
                builder.AppendLine("__");

                foreach ((Event evt, Instant occurance) in eventsDay)
                {
                    builder.AppendLine(this.GetEventString(evt, i, occurance));
                    count++;
                }

                builder.AppendLine();
            }

            if (count == 0)
            {
                builder.AppendLine("None");
            }

            EmbedBuilder embedBuilder = new EmbedBuilder();

            embedBuilder.Title       = header;
            embedBuilder.Description = builder.ToString();
            embedBuilder.Color       = Color.Blue;

            RestUserMessage?message = null;

            if (messageId != 0)
            {
                message = (RestUserMessage)await channel.GetMessageAsync(messageId);
            }

            if (message == null)
            {
                message = await channel.SendMessageAsync(null, false, embedBuilder.Build());

                messageId = message.Id;
            }
            else
            {
                await message.ModifyAsync(x =>
                {
                    x.Content = null;
                    x.Embed   = embedBuilder.Build();
                });
            }

            return(messageId);
        }
Exemple #17
0
 private static async void SendExceptionEmbed(Cacheable <IMessage, ulong> cacheable, Exception exception, SocketTextChannel channel)
 {
     var exceptionEmbed = new EmbedBuilder
     {
         Color       = Color.Red,
         Description = $"Error when downloading or posting the attachment.",
         Fields      =
         {
             new EmbedFieldBuilder()
             {
                 IsInline = false, Name = $":x: Exception type ", Value = exception.GetType().FullName
             },
             new EmbedFieldBuilder()
             {
                 IsInline = false, Name = $" Exception message", Value = exception.Message
             }
         },
         ThumbnailUrl = cacheable.Value.Author.GetAvatarUrl(),
         Timestamp    = DateTime.Now
     };
     await channel.Guild.GetTextChannel(Global.Channels["modlog"]).SendMessageAsync(embed: exceptionEmbed.Build());
 }
Exemple #18
0
 public async Task UndoGameAsync(SocketTextChannel lobbyChannel, int gameNumber)
 {
     await UndoGameAsync(gameNumber, lobbyChannel);
 }
Exemple #19
0
        public PurgeTheEnclave(VirtualServer _server) : base(_server, "enclavepurge")
        {
            try
            {
                var chan = server.FileSetup(adminChan);
                if (chan.Count > 0)
                {
                    channel = server.getServer().TextChannels.FirstOrDefault(x => x.Name == chan[0]);
                }
                var   str = server.FileSetup(enclaveRoleFile);
                ulong roleId;
                if (str.Count > 0)
                {
                    if (UInt64.TryParse(str[0], out roleId))
                    {
                        role = server.getServer().Roles.FirstOrDefault(x => x.Id == roleId);
                    }
                }
                watchlist = server.XMlDictSetup <ulong, DateTime>(watchlistPath);
                watchlist.ToList().Select(x =>
                {
                    Console.WriteLine("Watchlist element");
                    TimeSpan y = DateTime.Now.Subtract(x.Value.Add(span));
                    var res    = y.TotalMilliseconds;
                    if (res <= 0)
                    {
                        sendMessage(null, x.Key);
                    }
                    else
                    {
                        var z      = new Timer(res);
                        z.Elapsed += (s, e) => sendMessage((Timer)s, x.Key);
                        z.Start();
                    }
                    return(0);
                });

                server.UserUpdated += (o, e) =>
                {
                    var before = e.Item1;
                    var after  = e.Item2;
                    if (role != null)
                    {
                        try
                        {
                            bool wasEnclave = before.Roles.Contains(role);
                            bool isEnclave  = after.Roles.Contains(role);
                            if (wasEnclave && !isEnclave && watchlist.ContainsKey(after.Id))
                            {
                                Console.WriteLine("no more Enclave for: " + after.Username);
                                watchlist.Remove(after.Id);
                            }
                            else if (!wasEnclave && isEnclave && !watchlist.ContainsKey(after.Id))
                            {
                                Console.WriteLine("now Enclave: " + after.Username);
                                watchlist.Add(after.Id, DateTime.Now);
                                var z = new Timer(span.TotalMilliseconds);
                                z.Elapsed += (s, e2) => sendMessage((Timer)s, after.Id);
                                z.Start();
                            }
                        }
                        catch (Exception excep)
                        {
                            Console.WriteLine(excep);
                        }
                    }
                };

                server.UserLeft += (o, e) =>
                {
                    if (watchlist.ContainsKey(e.Id))
                    {
                        watchlist.Remove(e.Id);
                    }
                };
            }
            catch (Exception excep)
            {
                Console.WriteLine(excep);
            }
        }
Exemple #20
0
 public async Task GameResultAsync(SocketTextChannel lobbyChannel, int gameNumber, string voteState)
 {
     await GameResultAsync(gameNumber, voteState, lobbyChannel);
 }
Exemple #21
0
        private Task OnPresenceUpdated(SocketGuildUser oldUser, SocketGuildUser newUser)
        {
            IGuildUser user = newUser;

            if (user == null)
            {
                // Can't do anything, we don't know what game they were reading.
                return(Task.CompletedTask);
            }

            // TODO: See if there's a way to write this method without a hacky GetGameChannelPairs method
            KeyValuePair <ulong, GameState>[] readingGames = this.gameStateManager.GetGameChannelPairs()
                                                             .Where(kvp => kvp.Value.ReaderId == user.Id)
                                                             .ToArray();

            if (readingGames.Length > 0)
            {
                lock (this.readerRejoinedMapLock)
                {
                    if (!this.readerRejoinedMap.TryGetValue(user, out bool hasRejoined) &&
                        newUser.Status == UserStatus.Offline)
                    {
                        this.readerRejoinedMap[user] = false;
                    }
                    else if (hasRejoined == false && newUser.Status != UserStatus.Offline)
                    {
                        this.readerRejoinedMap[user] = true;
                        return(Task.CompletedTask);
                    }
                    else
                    {
                        return(Task.CompletedTask);
                    }
                }

                // The if-statement is structured so that we can call Task.Delay later without holding onto the lock
                // We should only be here if the first condition was true
                Task t = new Task(async() =>
                {
                    await Task.Delay(this.options.CurrentValue.WaitForRejoinMs);
                    bool rejoined = false;
                    lock (this.readerRejoinedMapLock)
                    {
                        this.readerRejoinedMap.TryGetValue(user, out rejoined);
                        this.readerRejoinedMap.Remove(user);
                    }

                    if (!rejoined)
                    {
                        Task <RestUserMessage>[] sendResetTasks = new Task <RestUserMessage> [readingGames.Length];
                        for (int i = 0; i < readingGames.Length; i++)
                        {
                            KeyValuePair <ulong, GameState> pair = readingGames[i];
                            pair.Value.ClearAll();
                            SocketTextChannel textChannel = newUser.Guild?.GetTextChannel(pair.Key);
                            if (textChannel != null)
                            {
                                this.logger.Verbose(
                                    "Reader left game in guild '{0}' in channel '{1}'. Ending game",
                                    textChannel.Guild.Name,
                                    textChannel.Name);
                                sendResetTasks[i] = (newUser.Guild.GetTextChannel(pair.Key)).SendMessageAsync(
                                    $"Reader {newUser.Nickname ?? newUser.Username} has left. Ending the game.");
                            }
                            else
                            {
                                // There's no channel, so return null
                                sendResetTasks[i] = Task.FromResult <RestUserMessage>(null);
                            }
                        }

                        await Task.WhenAll(sendResetTasks);
                    }
                });

                t.Start();
                // This is a lie, but await seems to block the event handlers from receiving other events, so say that
                // we have completed.
                return(Task.CompletedTask);
            }

            return(Task.CompletedTask);
        }
Exemple #22
0
 public async Task DrawAsync(SocketTextChannel lobbyChannel, int gameNumber, [Remainder] string comment = null)
 {
     await DrawAsync(gameNumber, lobbyChannel, comment);
 }
Exemple #23
0
        internal static async void UserSentMessage(SocketGuildUser user, SocketTextChannel channel)
        {
            if (blackListedChannels.Contains(channel.Id))
            {
                return;
            }

            var userAccount = UserAccounts.GetAccount(user);

            // if the user has a timeout, ignore them
            var  sinceLastXP = DateTime.UtcNow - userAccount.LastXP;
            uint oldLevel    = userAccount.LevelNumber;

            if (sinceLastXP.Minutes >= 2)
            {
                userAccount.LastXP = DateTime.UtcNow;
                userAccount.XP    += (uint)(new Random()).Next(30, 60);
            }

            if ((DateTime.Now.Date != userAccount.ServerStats.LastDayActive.Date))
            {
                userAccount.ServerStats.UniqueDaysActive++;
                userAccount.ServerStats.LastDayActive = DateTime.Now.Date;

                if ((DateTime.Now - user.JoinedAt).Value.TotalDays > 30)
                {
                    await GoldenSun.AwardClassSeries("Hermit Series", user, channel);
                }
            }

            if (channel.Id != userAccount.ServerStats.MostRecentChannel)
            {
                userAccount.ServerStats.MostRecentChannel = channel.Id;
                userAccount.ServerStats.ChannelSwitches  += 2;
                if (userAccount.ServerStats.ChannelSwitches >= 14)
                {
                    await GoldenSun.AwardClassSeries("Air Pilgrim Series", user, channel);
                }
            }
            else
            {
                if (userAccount.ServerStats.ChannelSwitches > 0)
                {
                    userAccount.ServerStats.ChannelSwitches--;
                }
            }

            if (channel.Id == 546760009741107216)
            {
                userAccount.ServerStats.MessagesInColossoTalks++;
                if (userAccount.ServerStats.MessagesInColossoTalks >= 50)
                {
                    await GoldenSun.AwardClassSeries("Swordsman Series", user, channel);
                }
            }

            UserAccounts.SaveAccounts();
            uint newLevel = userAccount.LevelNumber;

            if (oldLevel != newLevel)
            {
                LevelUp(userAccount, user, channel);
            }

            await Task.CompletedTask;
        }
Exemple #24
0
        public async Task GameResultAsync(int gameNumber, string voteState, SocketTextChannel lobbyChannel = null)
        {
            if (lobbyChannel == null)
            {
                lobbyChannel = Context.Channel as SocketTextChannel;
            }

            //Do vote conversion to ensure that the state is a string and not an int (to avoid confusion with team number from old elo version)
            if (int.TryParse(voteState, out var voteNumber))
            {
                await SimpleEmbedAsync("Please supply a result relevant to you rather than the team number. Use the `Results` command to see a list of these.", Color.DarkBlue);

                return;
            }

            if (!Enum.TryParse(voteState, true, out GameResult.Vote.VoteState vote))
            {
                await SimpleEmbedAsync("Your vote was invalid. Please choose a result relevant to you. ie. Win (if you won the game) or Lose (if you lost the game)\nYou can view all possible results using the `Results` command.", Color.Red);

                return;
            }

            var game = Service.GetGame(Context.Guild.Id, lobbyChannel.Id, gameNumber);

            if (game == null)
            {
                await SimpleEmbedAsync("Game not found.", Color.Red);

                return;
            }

            if (game.GameState != GameResult.State.Undecided)
            {
                await SimpleEmbedAsync("You can only vote on the result of undecided games.", Color.Red);

                return;
            }
            else if (game.VoteComplete)
            {
                //Result is undecided but vote has taken place, therefore it wasn't unanimous
                await SimpleEmbedAsync("Vote has already been taken on this game but wasn't unanimous, ask an admin to submit the result.", Color.DarkBlue);

                return;
            }

            if (!game.Team1.Players.Contains(Context.User.Id) && !game.Team2.Players.Contains(Context.User.Id))
            {
                await SimpleEmbedAsync("You are not a player in this game and cannot vote on it's result.", Color.Red);

                return;
            }

            if (game.Votes.ContainsKey(Context.User.Id))
            {
                await SimpleEmbedAsync("You already submitted your vote for this game.", Color.DarkBlue);

                return;
            }

            var userVote = new Vote()
            {
                UserId   = Context.User.Id,
                UserVote = vote
            };

            game.Votes.Add(Context.User.Id, userVote);

            //Ensure votes is greater than half the amount of players.
            if (game.Votes.Count * 2 > game.Team1.Players.Count + game.Team2.Players.Count)
            {
                var drawCount   = game.Votes.Count(x => x.Value.UserVote == Vote.VoteState.Draw);
                var cancelCount = game.Votes.Count(x => x.Value.UserVote == Vote.VoteState.Cancel);

                var team1WinCount = game.Votes
                                    //Get players in team 1 and count wins
                                    .Where(x => game.Team1.Players.Contains(x.Key))
                                    .Count(x => x.Value.UserVote == Vote.VoteState.Win)
                                    +
                                    game.Votes
                                    //Get players in team 2 and count losses
                                    .Where(x => game.Team2.Players.Contains(x.Key))
                                    .Count(x => x.Value.UserVote == Vote.VoteState.Lose);

                var team2WinCount = game.Votes
                                    //Get players in team 2 and count wins
                                    .Where(x => game.Team2.Players.Contains(x.Key))
                                    .Count(x => x.Value.UserVote == Vote.VoteState.Win)
                                    +
                                    game.Votes
                                    //Get players in team 1 and count losses
                                    .Where(x => game.Team1.Players.Contains(x.Key))
                                    .Count(x => x.Value.UserVote == Vote.VoteState.Lose);

                if (team1WinCount == game.Votes.Count)
                {
                    //team1 win
                    Service.SaveGame(game);
                    await GameVoteAsync(gameNumber, TeamSelection.team1, lobbyChannel, "Decided by vote.");
                }
                else if (team2WinCount == game.Votes.Count)
                {
                    //team2 win
                    Service.SaveGame(game);
                    await GameVoteAsync(gameNumber, TeamSelection.team2, lobbyChannel, "Decided by vote.");
                }
                else if (drawCount == game.Votes.Count)
                {
                    //draw
                    Service.SaveGame(game);
                    await DrawAsync(gameNumber, lobbyChannel, "Decided by vote.");
                }
                else if (cancelCount == game.Votes.Count)
                {
                    //cancel
                    Service.SaveGame(game);
                    await CancelAsync(gameNumber, lobbyChannel, "Decided by vote.");
                }
                else
                {
                    //Lock game votes and require admin to decide.
                    //TODO: Show votes by whoever
                    await SimpleEmbedAsync("Vote was not unanimous, game result must be decided by a moderator.", Color.DarkBlue);

                    game.VoteComplete = true;
                    Service.SaveGame(game);
                    return;
                }
            }
            else
            {
                Service.SaveGame(game);
                await SimpleEmbedAsync($"Vote counted as: {vote.ToString()}", Color.Green);
            }
        }
Exemple #25
0
        public async Task Guild_Channel_Updated(SocketChannel oldChannel, SocketChannel newChannel)
        {
            string        eventName = "Guild_Channel_Updated => ";
            StringBuilder logs      = new("-> ");

            if (oldChannel is ISocketMessageChannel)
            {
                SocketTextChannel oldTextChannel = oldChannel as SocketTextChannel;
                SocketTextChannel newTextChannel = newChannel as SocketTextChannel;
                eventName += "(TextChannel)" + oldTextChannel.Guild.Name + "." + oldTextChannel.Name;

                if (oldTextChannel.Name != newTextChannel.Name)
                {
                    logs.Append("(Name) [").Append(oldTextChannel.Name).Append(" => ").Append(newTextChannel.Name).Append(']').Append(breaker);
                }
                if (oldTextChannel.SlowModeInterval != newTextChannel.SlowModeInterval)
                {
                    logs.Append("(SlowModeInterval) [").Append(oldTextChannel.SlowModeInterval).Append(" => ").Append(newTextChannel.SlowModeInterval).Append(']').Append(breaker);
                }
                if (oldTextChannel.Topic != newTextChannel.Topic)
                {
                    logs.Append("(Topic) [").Append(oldTextChannel.Topic).Append(" => ").Append(newTextChannel.Topic).Append(']').Append(breaker);
                }
                if (oldTextChannel.IsNsfw != newTextChannel.IsNsfw)
                {
                    logs.Append("(IsNsfw) [").Append(oldTextChannel.IsNsfw).Append(" => ").Append(newTextChannel.IsNsfw).Append(']').Append(breaker);
                }
                if (oldTextChannel.Position != newTextChannel.Position)
                {
                    logs.Append("(Position) [").Append(oldTextChannel.Position).Append(" => ").Append(newTextChannel.Position).Append(']').Append(breaker);
                }
                if (!logs.ToString().Contains(breaker) && !oldTextChannel.PermissionOverwrites.Equals(newTextChannel.PermissionOverwrites))
                {
                    logs.Append("(PermissionOverwrites) [").Append(GetChangedPermissions(oldChannel, newChannel)).Append(']').Append(breaker);
                }
            }
            else if (oldChannel is ISocketAudioChannel)
            {
                SocketVoiceChannel oldVoiceChannel = oldChannel as SocketVoiceChannel;
                SocketVoiceChannel newVoiceChannel = newChannel as SocketVoiceChannel;
                eventName += "(VoiceChannel)" + oldVoiceChannel.Guild.Name + "." + oldVoiceChannel.Name;

                if (oldVoiceChannel.Name != newVoiceChannel.Name)
                {
                    logs.Append("(Name) [").Append(oldVoiceChannel.Name).Append(" => ").Append(newVoiceChannel.Name).Append(']').Append(breaker);
                }
                if (oldVoiceChannel.Bitrate != newVoiceChannel.Bitrate)
                {
                    logs.Append("(Bitrate) [").Append(oldVoiceChannel.Bitrate).Append(" => ").Append(newVoiceChannel.Bitrate).Append(']').Append(breaker);
                }
                if (oldVoiceChannel.UserLimit != newVoiceChannel.UserLimit)
                {
                    logs.Append("(UserLimit) [").Append(oldVoiceChannel.UserLimit ?? 0).Append(" => ").Append(newVoiceChannel.UserLimit ?? 0).Append(']').Append(breaker);
                }
                if (oldVoiceChannel.Position != newVoiceChannel.Position)
                {
                    logs.Append("(Position) [").Append(oldVoiceChannel.Position).Append(" => ").Append(newVoiceChannel.Position).Append(']').Append(breaker);
                }
                if (!oldVoiceChannel.PermissionOverwrites.Equals(newVoiceChannel.PermissionOverwrites))
                {
                    logs.Append("(PermissionOverwrites) [").Append(GetChangedPermissions(oldChannel, newChannel)).Append(']').Append(breaker);
                }
            }

            string resultLogs = logs.ToString();

            if (resultLogs.EndsWith(breaker))
            {
                resultLogs = resultLogs.Substring(0, resultLogs.Length - breaker.Length);
            }

            await SendLogs(eventName, resultLogs, EmoteManager.Guilds.Prod.Edit);
        }
Exemple #26
0
 public async Task GameAsync(SocketTextChannel lobbyChannel, int gameNumber, TeamSelection winning_team, [Remainder] string comment = null)
 {
     await GameAsync(gameNumber, winning_team, lobbyChannel, comment);
 }
Exemple #27
0
        public async Task CheckEmoteDateUserChannel(string emoteString, IGuildUser user, SocketTextChannel channel, [Remainder] string date)
        {
            bool success    = Emote.TryParse(emoteString, out Emote emote);
            bool dateParsed = DateTime.TryParseExact(date, "MMMM yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime period);

            if (success && dateParsed)
            {
                var result = DatabaseService.GetEmotePeriodUserChannelData(emote, user.Id, channel.Id, period);
                if (result != null)
                {
                    await ReplyAsync(result.ToString());
                }
            }
        }
Exemple #28
0
        public async Task GameAsync(int gameNumber, TeamSelection winning_team, SocketTextChannel lobbyChannel = null, [Remainder] string comment = null)
        {
            if (lobbyChannel == null)
            {
                //If no lobby is provided, assume that it is the current channel.
                lobbyChannel = Context.Channel as SocketTextChannel;
            }

            var lobby = Service.GetLobby(Context.Guild.Id, lobbyChannel.Id);

            if (lobby == null)
            {
                //Reply error not a lobby.
                await SimpleEmbedAsync("Channel is not a lobby.", Color.Red);

                return;
            }

            var game = Service.GetGame(Context.Guild.Id, lobby.ChannelId, gameNumber);

            if (game == null)
            {
                //Reply not valid game number.
                await SimpleEmbedAsync($"Game not found. Most recent game is {lobby.CurrentGameCount}", Color.DarkBlue);

                return;
            }

            if (game.GameState == GameResult.State.Decided || game.GameState == GameResult.State.Draw)
            {
                await SimpleEmbedAsync("Game results cannot currently be overwritten without first running the `undogame` command.", Color.Red);

                return;
            }

            var competition = Service.GetOrCreateCompetition(Context.Guild.Id);

            List <(Player, int, Rank, RankChangeState, Rank)> winList;
            List <(Player, int, Rank, RankChangeState, Rank)> loseList;

            if (winning_team == TeamSelection.team1)
            {
                winList  = UpdateTeamScoresAsync(competition, true, game.Team1.Players);
                loseList = UpdateTeamScoresAsync(competition, false, game.Team2.Players);
            }
            else
            {
                loseList = UpdateTeamScoresAsync(competition, false, game.Team1.Players);
                winList  = UpdateTeamScoresAsync(competition, true, game.Team2.Players);
            }

            var allUsers = new List <(Player, int, Rank, RankChangeState, Rank)>();

            allUsers.AddRange(winList);
            allUsers.AddRange(loseList);

            foreach (var user in allUsers)
            {
                //Ignore user updates if they aren't found in the server.
                var gUser = Context.Guild.GetUser(user.Item1.UserId);
                if (gUser == null)
                {
                    continue;
                }

                await Service.UpdateUserAsync(competition, user.Item1, gUser);
            }

            game.GameState    = GameResult.State.Decided;
            game.ScoreUpdates = allUsers.ToDictionary(x => x.Item1.UserId, y => y.Item2);
            game.WinningTeam  = (int)winning_team;
            game.Comment      = comment;
            game.Submitter    = Context.User.Id;
            Service.SaveGame(game);

            var winField = new EmbedFieldBuilder
            {
                //TODO: Is this necessary to show which team the winning team was?
                Name  = $"Winning Team, Team{(int)winning_team}",
                Value = GetResponseContent(winList).FixLength(1023)
            };
            var loseField = new EmbedFieldBuilder
            {
                Name  = $"Losing Team",
                Value = GetResponseContent(loseList).FixLength(1023)
            };
            var response = new EmbedBuilder
            {
                Fields = new List <EmbedFieldBuilder> {
                    winField, loseField
                },
                //TODO: Remove this if from the vote command
                Title = $"{lobbyChannel.Name} Game: #{gameNumber} Result called by {Context.User.Username}#{Context.User.Discriminator}".FixLength(127)
            };

            if (!string.IsNullOrWhiteSpace(comment))
            {
                response.AddField("Comment", comment.FixLength(1023));
            }

            await AnnounceResultAsync(lobby, response);
        }
Exemple #29
0
 /// <summary>
 /// Called when the bot joins a guild. Sends a message saying the bot is here.
 /// </summary>
 /// <param name="guild">The guild the bot joined.</param>
 private async Task Client_JoinGuild(SocketGuild guild)
 {
     SocketTextChannel channel = guild.DefaultChannel;
     await channel.SendMessageAsync("I am here now! :grinning:");
 }
Exemple #30
0
    public async Task MainAsync()
    {
        //initialize and connect client
        _client      = new DiscordSocketClient();
        _client.Log += Log;

        //get config
        _config = new Config();
        String json_str;

        try {
            json_str = File.ReadAllText("data/config.json");
            _config  = JsonSerializer.Deserialize <Config>(json_str);
        } catch (Exception e) {
            if (e is FileNotFoundException)
            {
                Console.WriteLine("ERROR: data/config.json not found. Creating new config.json file. Please set BotToken field.");
                File.WriteAllText("data/config.json", JsonSerializer.Serialize(_config));
            }
            else if (e is JsonException)
            {
                Console.WriteLine("ERROR: data/config.json: " + e.Message);
            }
            else
            {
                Console.WriteLine("ERROR: exception thrown when trying to load data/config.json: ");
                throw;
            }
            return;
        }

        if (_config.CommandEnabled || _config.RoleEnabled)
        {
            Console.WriteLine("Setting up handler(s) in 4 seconds.");
        }

        //login using generated token
        try {
            await _client.LoginAsync(
                TokenType.Bot,
                _config.BotToken
                );
        } catch {
            Console.WriteLine("ERROR: could not log in. Ensure the BotToken field in data/config.json is valid.");
            return;
        }

        //begin running and wait 4 seconds to allow client to connect
        await _client.StartAsync();

        if (_config.CommandEnabled || _config.RoleEnabled)
        {
            await Task.Delay(4000);
        }

        //set up command handler
        if (_config.CommandEnabled)
        {
            _commandhandler = new CommandHandler(_config);
            if (_commandhandler.LoadCommands() != 0)
            {
                Console.WriteLine("WARN: could not initialize command handler.");
                _commandhandler = null;
            }
            else
            {
                //hook command handler to message received event
                _client.MessageReceived += HandleMessageAsync;
                Console.WriteLine("Command handler ready.");
            }
        }

        //set up role handler
        if (_config.RoleEnabled)
        {
            SocketGuild       foundguild   = null;
            SocketTextChannel foundchannel = null;

            //try to get guilds from client 3 times
            var guilds = _client.Guilds;
            int i      = 0;
            while (guilds.Count <= 0 && i < 2)
            {
                Console.WriteLine("WARN: retrieved 0 guilds from client. Retrying in 4 seconds.");
                await Task.Delay(4000);

                guilds = _client.Guilds;
                i     += 1;
            }

            if (guilds.Count > 0)
            {
                //find guild in config
                foreach (SocketGuild guild in guilds)
                {
                    if (guild.Name == _config.RoleGuild)
                    {
                        foundguild = guild;
                        break;
                    }
                }
                if (foundguild != null)
                {
                    //find channel in config
                    var channels = foundguild.TextChannels;
                    foreach (SocketTextChannel channel in channels)
                    {
                        if (channel.Name == _config.RoleChannel)
                        {
                            foundchannel = channel;
                            break;
                        }
                    }
                }
                //try to initialize role handler
                if (foundguild != null && foundchannel != null)
                {
                    _rolehandler = new RoleHandler(foundguild, foundchannel);
                    if ((await _rolehandler.LoadRoles()) != 0)
                    {
                        Console.WriteLine("WARN: could not initialize role handler.");
                        _rolehandler = null;
                    }
                    else
                    {
                        //give command handler reference to role handler's load method on success
                        _commandhandler.SetLoadRolesFn(_rolehandler.LoadRoles);

                        //hook reaction handler to reaction events
                        _client.ReactionAdded   += HandleReactionAddedAsync;
                        _client.ReactionRemoved += HandleReactionRemovedAsync;
                        Console.WriteLine("Role handler ready.");
                    }
                }
                else
                {
                    Console.WriteLine("WARN: config.json: could not find guild or channel specified in configuration for role handler. Either they do not exist, or client did not connect within 5 seconds.");
                    Console.WriteLine("WARN: could not initialize role handler.");
                }
            }
            else
            {
                Console.WriteLine("WARN: retrieved 0 guilds from client while trying to initialize role handler.");
                Console.WriteLine("WARN: could not initialize role handler.");
            }
        }

        //set up join handler
        if (_config.JoinEnabled)
        {
            SocketGuild       foundguild   = null;
            SocketTextChannel foundchannel = null;

            //try to get guilds from client 3 times
            var guilds = _client.Guilds;
            int i      = 0;
            while (guilds.Count <= 0 && i < 2)
            {
                Console.WriteLine("WARN: retrieved 0 guilds from client. Retrying in 4 seconds.");
                await Task.Delay(4000);

                guilds = _client.Guilds;
                i     += 1;
            }

            if (guilds.Count > 0)
            {
                //find guild in config
                foreach (SocketGuild guild in guilds)
                {
                    if (guild.Name == _config.JoinGuild)
                    {
                        foundguild = guild;
                        break;
                    }
                }
                if (foundguild != null)
                {
                    //find channel in config
                    var channels = foundguild.TextChannels;
                    foreach (SocketTextChannel channel in channels)
                    {
                        if (channel.Name == _config.JoinChannel)
                        {
                            foundchannel = channel;
                            break;
                        }
                    }
                }
                //try to initialize join handler
                if (foundguild != null && foundchannel != null)
                {
                    _joinhandler = new JoinHandler(foundguild, foundchannel);
                    if ((await _joinhandler.LoadJoin()) != 0)
                    {
                        Console.WriteLine("WARN: could not initialize join handler.");
                        _joinhandler = null;
                    }
                    else
                    {
                        //give command handler reference to join handler's load method on success
                        _commandhandler.SetLoadJoinFn(_joinhandler.LoadJoin);

                        //hook reaction handler to join event
                        _client.UserJoined += HandleUserJoinedAsync;
                        Console.WriteLine("Join handler ready.");
                    }
                }
                else
                {
                    Console.WriteLine("WARN: config.json: could not find guild or channel specified in configuration for join handler. Either they do not exist, or client did not connect within 5 seconds.");
                    Console.WriteLine("WARN: could not initialize join handler.");
                }
            }
            else
            {
                Console.WriteLine("WARN: retrieved 0 guilds from client while trying to initialize join handler.");
                Console.WriteLine("WARN: could not initialize join handler.");
            }
        }

        //delay infinitely
        await Task.Delay(-1);
    }