Ejemplo n.º 1
0
        private async void CheckReminders(Object stateInfo)
        {
            try
            {
                using (var _soraContext = new SoraContext())
                {
                    List <Reminders> rems = new List <Reminders>();
                    rems = _soraContext.Reminders.ToList();
                    bool triggered = false;
                    bool crucked   = false;
                    foreach (var reminder in rems)
                    {
                        if (reminder.Time.CompareTo(DateTime.UtcNow) <= 0)
                        {
                            triggered = true;
                            var userToRemind = _client.GetUser(reminder.UserForeignId);
                            if (userToRemind == null)
                            {
                                triggered = false;
                                crucked   = true;
                                //remove if user is not reachable anymore
                                if (reminder.Time.Add(TimeSpan.FromMinutes(CLEANUP_MINUTES)).CompareTo(DateTime.UtcNow) <= 0)
                                {
                                    _soraContext.Reminders.Remove(reminder);
                                }
                                continue;
                            }
                            try
                            {
                                await(await userToRemind.GetOrCreateDMChannelAsync()).SendMessageAsync("",
                                                                                                       embed: Utility
                                                                                                       .ResultFeedback(Utility.PurpleEmbed, Utility.SuccessLevelEmoji[4], $"**Reminder** ⏰")
                                                                                                       .WithDescription($"{reminder.Message}"));
                            }
                            catch (Exception e)
                            {
                                //Ignore
                            }
                            _soraContext.Reminders.Remove(reminder);
                        }
                    }
                    await _soraContext.SaveChangesAsync();


                    if (crucked)
                    {
                        _timer.Change(TimeSpan.FromSeconds(CRUCKED_SECONDS), TimeSpan.FromSeconds(CRUCKED_SECONDS));
                        Console.WriteLine($"CHANGED TIMER INTERVAL TO *CRUCKED*: {CRUCKED_SECONDS}");
                    }
                    else if (triggered)
                    {
                        ChangeToClosestInterval();
                    }
                }
            }
            catch (Exception e)
            {
                await SentryService.SendMessage(e.ToString());
            }
        }
Ejemplo n.º 2
0
 public async Task InitializeAsync()
 {
     try
     {
         await _weebClient.Authenticate(_token, TokenType.Bearer);
     }
     catch (Exception e)
     {
         await SentryService.SendMessage("COULND'T CONNECT TO WEEB.SH SERVICES");
     }
 }
Ejemplo n.º 3
0
        // Ban user Command
        public async Task <bool> BanUser(ulong id, string reason)
        {
            if (!_bannedUsers.TryAdd(id, true))
            {
                return(false);
            }
            // Add to DB
            using (var soraContext = new SoraContext())
            {
                if (string.IsNullOrWhiteSpace(reason))
                {
                    reason = "";
                }

                soraContext.Bans.Add(new Ban()
                {
                    UserId   = id,
                    BannedAt = DateTime.UtcNow,
                    Reason   = reason
                });
                await soraContext.SaveChangesAsync();
            }
            // notify other shards to ban user
            int port = int.Parse(ConfigService.GetConfigData("port"));

            for (int i = 0; i < Utility.TOTAL_SHARDS; i++)
            {
                if (i == Utility.SHARD_ID)
                {
                    continue;
                }

                try
                {
                    using (var httpClient = new HttpClient())
                        using (var request = new HttpRequestMessage(HttpMethod.Post, $"http://localhost:{(port+i)}/api/SoraApi/BanEvent/"))
                        {
                            string json = JsonConvert.SerializeObject(new { userId = id });
                            request.Content = new StringContent(json);
                            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                            HttpResponseMessage response = await httpClient.SendAsync(request);

                            response.Dispose();
                        }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    await SentryService.SendMessage($"COULDN'T SEND BAN EVENT TO SHARD {i} FOR ID: {id}");
                }
            }
            return(true);
        }
Ejemplo n.º 4
0
        private async Task SendMessage(ulong userId)
        {
            var user = _client.GetUser(userId);

            if (user == null)
            {
                return;
            }
            await(await user.GetOrCreateDMChannelAsync()).SendMessageAsync("", embed: Utility.ResultFeedback(
                                                                               Utility.YellowWarningEmbed, Utility.SuccessLevelEmoji[1], "You have been ratelimited by Sora!").WithDescription(
                                                                               "Please refrain from spamming Sora. Please use him normally or a permanent ban will be issued if repeated often.\n" +
                                                                               $"If you think you did not spam then join [this guild and open a ratelimit appeal]({Utility.DISCORD_INVITE})!"));
            await SentryService.SendMessage(
                $"**USER RATELIMITED**\nUser: {Utility.GiveUsernameDiscrimComb(user)} ({userId})");
        }
Ejemplo n.º 5
0
        // UnBan user Command
        public async Task <bool> UnBanUser(ulong id)
        {
            if (!_bannedUsers.TryRemove(id, out _))
            {
                return(false);
            }
            // remove from DB
            using (var soraContext = new SoraContext())
            {
                soraContext.Bans.Remove(soraContext.Bans.FirstOrDefault(x => x.UserId == id));
                await soraContext.SaveChangesAsync();
            }
            // notify other shards to ban user
            int port = int.Parse(ConfigService.GetConfigData("port"));

            for (int i = 0; i < Utility.TOTAL_SHARDS; i++)
            {
                if (i == Utility.SHARD_ID)
                {
                    continue;
                }

                try
                {
                    using (var httpClient = new HttpClient())
                        using (var request = new HttpRequestMessage(HttpMethod.Post, $"http://localhost:{(port+i)}/api/SoraApi/UnBanEvent/"))
                        {
                            string json = JsonConvert.SerializeObject(new { userId = id });
                            request.Content = new StringContent(json);
                            request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                            HttpResponseMessage response = await httpClient.SendAsync(request);

                            response.Dispose();
                        }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    await SentryService.SendMessage($"COULDN'T SEND UNBAN EVENT TO SHARD {i} FOR ID: {id}");
                }
            }
            return(true);
        }
Ejemplo n.º 6
0
        private async void UpdateStarCounts(Object objectInfo)
        {
            try
            {
                //return if there is nothing to update
                if (_toUpdate.Count == 0)
                {
                    return;
                }
                //otherwise lets update all of the entires
                List <StarMsgUpdateStruct> temp = new List <StarMsgUpdateStruct>(_toUpdate);
                using (SoraContext soraContext = new SoraContext())
                {
                    foreach (var updateStruct in temp)
                    {
                        var guild = _client.GetGuild(updateStruct.GuildId);
                        if (guild == null)
                        {
                            //he was kicked after star or guild moved shards.
                            //remove and update entry
                            _toUpdate.Remove(updateStruct);
                            continue;
                        }
                        var guildDb = Utility.GetOrCreateGuild(updateStruct.GuildId, soraContext);
                        //check if starchannel still exists!
                        var starChannel = guild.GetTextChannel(guildDb.StarChannelId);
                        if (starChannel == null)
                        {
                            //channel doesnt exists anymore
                            //remove update entry
                            _toUpdate.Remove(updateStruct);
                            continue;
                        }
                        //check perms
                        if (await Utility.CheckReadWritePerms(guild, starChannel, false) == false)
                        {
                            //remove update entry
                            _toUpdate.Remove(updateStruct);
                            continue;
                        }
                        //Get Message
                        var starMsg = await CacheService.GetUserMessage(updateStruct.PostedMsgId);

                        //if Msg wasn't cached then there wasn't an update to the count.
                        if (starMsg == null)
                        {
                            //remove update entry
                            _toUpdate.Remove(updateStruct);
                            continue;
                        }
                        int amount;
                        if (!int.TryParse(
                                starMsg.Content.Substring(0, starMsg.Content.IndexOf(" ", StringComparison.Ordinal))
                                .Replace("**", ""), out amount))
                        {
                            //parse failed for some reason
                            //remove update entry
                            _toUpdate.Remove(updateStruct);
                            continue;
                        }
                        //get starmessage
                        var starMessage = guildDb.StarMessages.FirstOrDefault(x => x.PostedMsgId == starMsg.Id);
                        if (starMessage == null)
                        {
                            //failed to get starmessage
                            //remove update entry
                            _toUpdate.Remove(updateStruct);
                            continue;
                        }
                        if (amount == starMessage.StarCount)
                        {
                            //remove update entry
                            _toUpdate.Remove(updateStruct);
                            continue;
                        }
                        try
                        {
                            await starMsg.ModifyAsync(x =>
                            {
                                x.Content = $"**{starMessage.StarCount}**{starMsg.Content.Substring(starMsg.Content.IndexOf(" ", StringComparison.Ordinal))}";
                            });
                        }
                        catch (Discord.Net.HttpException)
                        {
                            //if this was cought the cached message isnt valid anymore so remove it.
                            CacheService.RemoveUserMessage(starMsg.Id);
                            //remove update entry
                            _toUpdate.Remove(updateStruct);
                            continue;
                        }
                        //remove update entry
                        _toUpdate.Remove(updateStruct);
                        await CacheService.SetDiscordUserMessage(starChannel, starMessage.PostedMsgId,
                                                                 TimeSpan.FromHours(1));
                    }
                }
            }
            catch (Exception e)
            {
                await SentryService.SendMessage(e.ToString());
            }
        }
Ejemplo n.º 7
0
        private async Task <ulong> PostStarMessage(SocketTextChannel starChannel, IUserMessage msg)
        {
            string attachmentUrls = "";
            bool   attachMent     = false;
            bool   picAttachment  = false;
            string picAttach      = "";

            if (msg.Attachments.Count > 0)
            {
                attachMent = true;
                if (msg.Attachments.Count == 1)
                {
                    var url = msg.Attachments.ToArray()[0].Url;
                    if (url.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || url.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || url.EndsWith(".gif", StringComparison.OrdinalIgnoreCase))
                    {
                        attachMent    = false;
                        picAttachment = true;
                        picAttach     = url;
                    }
                    else
                    {
                        attachmentUrls = url;
                    }
                }
                else
                {
                    foreach (var messageAttachment in msg.Attachments)
                    {
                        attachmentUrls += $"{messageAttachment.Url} \n";
                    }
                }
            }
            string messageContent = msg.Content ?? "";

            //CHECK FOR 1 IMAGE WITHIN THE VALUE
            if (!attachMent && !picAttachment)
            {
                var mc = Regex.Matches(messageContent, @"(https://[^ \s]+|http://[^ \s]+)([\s]|$)");
                if (mc.Count == 1)
                {
                    var link = mc[0].Value;
                    if (link.EndsWith(".png", StringComparison.OrdinalIgnoreCase) || link.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) || link.EndsWith(".gif", StringComparison.OrdinalIgnoreCase))
                    {
                        picAttachment  = true;
                        picAttach      = link;
                        messageContent = messageContent.Remove(messageContent.IndexOf(link, StringComparison.Ordinal), link.Length);
                    }
                }
            }
            //Finally ADD
            var eb = new EmbedBuilder()
            {
                Color  = Utility.PurpleEmbed,
                Author = new EmbedAuthorBuilder()
                {
                    IconUrl = msg.Author.GetAvatarUrl() ?? Utility.StandardDiscordAvatar,
                    Name    = Utility.GiveUsernameDiscrimComb(msg.Author as SocketUser)
                },
                Timestamp   = DateTime.Now,
                Description = (attachMent ? $"{messageContent}\n{attachmentUrls}" : messageContent)
            };

            if (picAttachment)
            {
                eb.ImageUrl = picAttach;
            }
            try
            {
                var postedMsg = await starChannel.SendMessageAsync($"**1** ⭐ in <#{msg.Channel.Id}> \n", embed : eb);

                return(postedMsg.Id);
            }
            catch (Exception e)
            {
                await SentryService.SendMessage("STARBOARD ERROR\n" + e);
            }
            return(0);
        }
Ejemplo n.º 8
0
        public async Task ClientOnReactionAdded(Cacheable <IUserMessage, ulong> cacheable, ISocketMessageChannel socketMessageChannel, SocketReaction reaction)
        {
            try
            {
                //Reaction doesn't match a star
                if (!reaction.Emote.Name.Equals("⭐"))
                {
                    return;
                }
                //get Message
                var msg = await cacheable.GetOrDownloadAsync();

                //Dont do anything if the msg originates from a bot
                if (msg.Author.IsBot)
                {
                    return;
                }
                //Reaction was a star
                using (SoraContext soraContext = new SoraContext())
                {
                    var guild   = ((SocketGuildChannel)socketMessageChannel).Guild;
                    var guildDb = Utility.GetOrCreateGuild(guild.Id, soraContext);
                    //Either the starboard wasn't set up or the channel doesnt exist anymore.
                    if (guildDb.StarChannelId == 0)
                    {
                        return;
                    }
                    var starChannel = guild.GetTextChannel(guildDb.StarChannelId);
                    if (starChannel == null)
                    {
                        //guildDb.StarChannelId = 0; //Reset the channelID to 0 so in the future we dont have to save anything anymore :D
                        //await soraContext.SaveChangesAsync(); //TODO TEMPORARILY DISABLED DUE TO SOME ERROR
                        return;
                    }
                    //Check if reaction is from author
                    if (msg.Author.Id == reaction.UserId)
                    {
                        return;
                    }
                    //check if it was added once before and if it was added too many times!
                    var starMsg = guildDb.StarMessages.FirstOrDefault(x => x.MessageId == msg.Id);
                    if (starMsg != null && starMsg.HitZeroCount >= 3)
                    {
                        return;
                    }
                    //if it was null create a new one otherwise keep the old one
                    bool wasNull = false;
                    if (starMsg == null)
                    {
                        starMsg = new StarMessage()
                        {
                            GuildForeignId = guild.Id,
                            HitZeroCount   = 0,
                            MessageId      = msg.Id,
                            StarCount      = 0,
                            IsPosted       = false
                        };
                        wasNull = true;
                    }

                    //Add star
                    starMsg.StarCount++;
                    //Check if its enough to post
                    if (starMsg.StarCount >= guildDb.StarMinimum && !starMsg.IsPosted)
                    {
                        //POST
                        starMsg.PostedMsgId = await PostStarMessage(starChannel, msg);

                        if (starMsg.PostedMsgId == 0)
                        {
                            try
                            {
                                await socketMessageChannel.SendMessageAsync("", embed : Utility.ResultFeedback(
                                                                                Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2], "Something failed. Can't add msg to starboard. Serenity#0783 has been notified"));
                            }
                            catch (Exception e)
                            {
                                await SentryService.SendMessage("EVEN FAILED WITH ERROR MESSAGEEEEEEEEEEEEE :C\n" + e);

                                return;
                            }

                            return;
                        }
                        starMsg.IsPosted = true;
                    }

                    //save changes made
                    if (wasNull)
                    {
                        guildDb.StarMessages.Add(starMsg);
                    }
                    await soraContext.SaveChangesAsync();

                    //if it wasnt null and posted add to update
                    if (!wasNull && starMsg.IsPosted)
                    {
                        //add it to the starmsg update cache so we can update the count!
                        _toUpdate.Add(new StarMsgUpdateStruct()
                        {
                            GuildId     = guild.Id,
                            PostedMsgId = starMsg.PostedMsgId
                        });
                    }
                    //check if starpostedmsg == 0
                    if (starMsg.PostedMsgId != 0)
                    {
                        await CacheService.SetDiscordUserMessage(starChannel, starMsg.PostedMsgId, TimeSpan.FromHours(1));
                    }
                }
            }
            catch (Exception e)
            {
                await SentryService.SendMessage(e.ToString());
            }
        }