Beispiel #1
0
 public static async Task SendToDms(IUser user, string content = null, EmbedBuilder em = null, ISocketMessageChannel backup = null)
 {
     try
     {
         await user.SendMessageAsync(content, false, em?.Build());
     }
     catch (Exception e)
     {
         Log.LogS("Failed to DM " + user.Id);
         Log.LogS(e);
         backup?.SendMessageAsync(content, false, em?.Build());
     }
 }
Beispiel #2
0
        public static async Task <RestUserMessage> Send(this AbbybotCommandArgs arg, StringBuilder sb, EmbedBuilder eb)
        {
            string s = sb?.ToString();
            Embed  e = eb?.Build();

            return((eb != null || sb != null) ? await arg.channel.SendMessageAsync(s, false, eb.Build()) : null);
        }
Beispiel #3
0
 public Task <RestUserMessage> ReplyAsync(string content         = null, EmbedBuilder embed = null,
                                          RequestOptions options = null)
 {
     if (!BotUser.GetPermissions(Channel).SendMessages)
     {
         return(Task.FromResult((RestUserMessage)null));
     }
     return(Channel.SendMessageAsync(content, false, embed?.Build(), options));
 }
Beispiel #4
0
        public async Task SendMessageAsync()
        {
            ulong      userId = GetArgUInt64(api.UserId);
            SocketUser user   = Discord.Client.GetUser(userId);

            string             content = HasArg(api.Message) ? Args[api.Message] : null;
            SharedDiscordEmbed sde     = HasArg(api.Embed) ? JsonConvert.DeserializeObject <SharedDiscordEmbed>(Args[api.Embed]) : null;
            EmbedBuilder       eb      = sde.ToEmbedBuilder();

            IDMChannel dm = await user.GetOrCreateDMChannelAsync();

            await dm.SendMessageAsync(text : content, embed : eb?.Build());
        }
Beispiel #5
0
 internal async Task SendMessageToDM(string message = null, EmbedBuilder embed = null,
                                     ISocketMessageChannel backup = null)
 {
     try
     {
         await AMYPrototype.Program.clientCopy.GetUser(_id).SendMessageAsync(message, embed: embed?.Build());
     }
     catch (Exception e)
     {
         Log.LogS("Failed to DM " + _id);
         Log.LogS(e);
         if (backup != null)
         {
             await backup.SendMessageAsync(message, embed : embed?.Build());
         }
     }
 }
Beispiel #6
0
        private Task SendResponse(bool commandResult, MemeResultType memeType, string value, string failureMessage)
        {
            var replyMessage = string.Empty;
            var embed        = new EmbedBuilder();

            if (commandResult)
            {
                if (memeType == MemeResultType.Image)
                {
                    embed.ImageUrl = value;
                }
                else
                {
                    replyMessage = value;
                }
            }
            else
            {
                replyMessage = failureMessage;
            }
            return(ReplyAsync(replyMessage, embed: embed?.Build()));
        }
Beispiel #7
0
        public async Task Weather(IUserMessage umsg, string city, string country)
        {
            var channel = (ITextChannel)umsg.Channel;
            city = city.Replace(" ", "");
            country = city.Replace(" ", "");
            string response;
            using (var http = new HttpClient())
                response = await http.GetStringAsync($"http://api.ninetales.us/nadekobot/weather/?city={city}&country={country}").ConfigureAwait(false);

            var obj = JObject.Parse(response)["weather"];

            var embed = new EmbedBuilder()
                .AddField(fb => fb.WithName("🌍 Location").WithValue($"{obj["target"]}").WithIsInline(true))
                .AddField(fb => fb.WithName("📏 Lat,Long").WithValue($"{obj["latitude"]}, {obj["longitude"]}").WithIsInline(true))
                .AddField(fb => fb.WithName("☁ Condition").WithValue($"{obj["condition"]}").WithIsInline(true))
                .AddField(fb => fb.WithName("😓 Humidity").WithValue($"{obj["humidity"]}%").WithIsInline(true))
                .AddField(fb => fb.WithName("💨 Wind Speed").WithValue($"{obj["windspeedk"]}km/h / {obj["windspeedm"]}mph").WithIsInline(true))
                .AddField(fb => fb.WithName("🌡 Temperature").WithValue($"{obj["centigrade"]}°C / {obj["fahrenheit"]}°F").WithIsInline(true))
                .AddField(fb => fb.WithName("🔆 Feels like").WithValue($"{obj["feelscentigrade"]}°C / {obj["feelsfahrenheit"]}°F").WithIsInline(true))
                .AddField(fb => fb.WithName("🌄 Sunrise").WithValue($"{obj["sunrise"]}").WithIsInline(true))
                .AddField(fb => fb.WithName("🌇 Sunset").WithValue($"{obj["sunset"]}").WithIsInline(true))
                .WithColor(NadekoBot.OkColor);
            await channel.EmbedAsync(embed.Build()).ConfigureAwait(false);
        }
Beispiel #8
0
        public async Task HandleCommandAsync(SocketMessage s)
        {
            try
            {
                if (s.Channel.Id == 592463507124125706)
                {
                    t.Stop();
                    t.AutoReset = true;
                    t.Enabled   = true;
                    t.Interval  = 300000;
                    t.Start();
                }

                var msg = s as SocketUserMessage;
                if (msg == null)
                {
                    return;
                }

                var context = new SocketCommandContext(_client, msg);
                if (Commands.giveawayinProg)
                {
                    Commands.checkGiveaway(s);
                }

                int argPos = 0;
                if (msg.Channel.GetType() == typeof(SocketDMChannel))
                {
                    await checkKey(context);
                }
                var ca = msg.Content.ToCharArray();
                if (ca.Length == 0)
                {
                    return;
                }
                if (_service.UsedPrefixes.Contains(ca[0]))
                {
                    new Thread(async() =>
                    {
                        if (msg.Content.StartsWith($"{Global.Preflix}echo"))
                        {
                            await EchoMessage(context); return;
                        }
                        var result = await _service.ExecuteAsync(context);
                        Console.WriteLine(result.Result.ToString());
                        if (result.MultipleResults)
                        {
                            foreach (var r in result.Results)
                            {
                                if (r.Result == CommandStatus.Unknown || r.Result == CommandStatus.Error)
                                {
                                    EmbedBuilder ce = new EmbedBuilder()
                                    {
                                        Title       = "Uh oh... :(",
                                        Description = "Looks like the command didnt work :/ ive dm'ed quin the errors and he should be fixing it soon.",
                                        Color       = Color.Red
                                    };
                                    await msg.Channel.SendMessageAsync("", false, ce.Build());

                                    await _client.GetGuild(Global.SwissGuildId).GetUser(259053800755691520).SendMessageAsync("Command: " + msg.Content);
                                    File.WriteAllText(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "error.txt", r.Exception.ToString());
                                    await _client.GetUser(259053800755691520).SendFileAsync(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "error.txt");

                                    EmbedBuilder b   = new EmbedBuilder();
                                    b.Color          = Color.Red;
                                    b.Description    = $"The following info is the Command error info, `{msg.Author.Username}#{msg.Author.Discriminator}` tried to use the `{msg}` Command in {msg.Channel}: \n \n **COMMAND ERROR REASON**: ```{r.Exception.Message}```";
                                    b.Author         = new EmbedAuthorBuilder();
                                    b.Author.Name    = msg.Author.Username + "#" + msg.Author.Discriminator;
                                    b.Author.IconUrl = msg.Author.GetAvatarUrl();
                                    b.Footer         = new EmbedFooterBuilder();
                                    b.Footer.Text    = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " ZULU";
                                    b.Title          = "Bot Command Error!";
                                    await _client.GetGuild(Global.SwissGuildId).GetTextChannel(Global.DebugChanID).SendMessageAsync("", false, b.Build());
                                    await _client.GetGuild(Global.SwissBotDevGuildID).GetTextChannel(622164033902084145).SendMessageAsync("", false, b.Build());
                                }
                            }
                        }
                        else if (result.Result == CommandStatus.Unknown || result.Result == CommandStatus.Error)
                        {
                            EmbedBuilder ce = new EmbedBuilder()
                            {
                                Title       = "Uh oh... :(",
                                Description = "Looks like the command didnt work :/ ive dm'ed quin the errors and he should be fixing it soon.",
                                Color       = Color.Red
                            };
                            await msg.Channel.SendMessageAsync("", false, ce.Build());

                            await _client.GetGuild(Global.SwissGuildId).GetUser(259053800755691520).SendMessageAsync("Command: " + msg.Content);
                            File.WriteAllText(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "error.txt", result.Exception.ToString());
                            await _client.GetUser(259053800755691520).SendFileAsync(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "error.txt");

                            EmbedBuilder b   = new EmbedBuilder();
                            b.Color          = Color.Red;
                            b.Description    = $"The following info is the Command error info, `{msg.Author.Username}#{msg.Author.Discriminator}` tried to use the `{msg}` Command in {msg.Channel}: \n \n **COMMAND ERROR REASON**: ```{result.Exception.Message}```";
                            b.Author         = new EmbedAuthorBuilder();
                            b.Author.Name    = msg.Author.Username + "#" + msg.Author.Discriminator;
                            b.Author.IconUrl = msg.Author.GetAvatarUrl();
                            b.Footer         = new EmbedFooterBuilder();
                            b.Footer.Text    = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + " ZULU";
                            b.Title          = "Bot Command Error!";
                            await _client.GetGuild(Global.SwissGuildId).GetTextChannel(Global.DebugChanID).SendMessageAsync("", false, b.Build());
                            await _client.GetGuild(Global.SwissBotDevGuildID).GetTextChannel(622164033902084145).SendMessageAsync("", false, b.Build());
                        }
                        await HandleCommandresult(result, msg);
                    }).Start();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Beispiel #9
0
        public async Task EmojiStatsAsync(
            [Summary("The emoji to retrieve information about.")]
            IEmote emoji)
        {
            // TODO: Abstract this as IEmoteEntity instead (actually not entirely sure how this would work, as it comes out of the commands module)
            var asEmote = emoji as Emote;

            var ephemeralEmoji = EphemeralEmoji.FromRawData(emoji.Name, asEmote?.Id, asEmote?.Animated ?? false);
            var guildId        = Context.Guild.Id;

            var emojiStats = await _emojiRepository.GetEmojiStatsAsync(guildId, ephemeralEmoji);

            if (emojiStats == default || emojiStats.Uses == 0)
            {
                await ReplyAsync(embed : new EmbedBuilder()
                                 .WithTitle("Unknown Emoji")
                                 .WithDescription($"The emoji \"{ephemeralEmoji.Name}\" has never been used in this server.")
                                 .WithColor(Color.Red)
                                 .Build());

                return;
            }

            var emojiStats30 = await _emojiRepository.GetEmojiStatsAsync(guildId, ephemeralEmoji, TimeSpan.FromDays(30));

            var guildStats = await _emojiRepository.GetGuildStatsAsync(guildId);

            var emojiFormatted = ((SocketSelfUser)Context.Client.CurrentUser).CanAccessEmoji(ephemeralEmoji)
                    ? ephemeralEmoji.ToString()
                    : "❔";

            var percentUsage = 100 * (double)emojiStats.Uses / guildStats.TotalUses;

            if (double.IsNaN(percentUsage))
            {
                percentUsage = 0;
            }

            var numberOfDays = Math.Clamp((DateTime.Now - guildStats.OldestTimestamp).Days, 1, 30);
            var perDay       = (double)emojiStats30.Uses / numberOfDays;

            var sb = new StringBuilder(emojiFormatted);

            if (ephemeralEmoji.Id != null)
            {
                sb.Append($" (`:{ephemeralEmoji.Name}:`)");
            }

            sb.AppendLine()
            .AppendLine($"• {"use".ToQuantity(emojiStats.Uses)}")
            .AppendLine($"• {percentUsage.ToString("0.0")}% of all emoji uses")
            .AppendLine($"• {perDay.ToString("0.0/day")}");

            if (emojiStats.TopUserId != default)
            {
                sb.AppendLine($"• Top user: {MentionUtils.MentionUser(emojiStats.TopUserId)} ({"use".ToQuantity(emojiStats.TopUserUses)})");
            }

            var embed = new EmbedBuilder()
                        .WithAuthor(Context.Guild.Name, Context.Guild.IconUrl)
                        .WithColor(Color.Blue)
                        .WithDescription(sb.ToString());

            await ReplyAsync(embed : embed.Build());
        }
Beispiel #10
0
 static public async Task sendAlert(ulong guild, string textToSend, EmbedBuilder eb = null)
 {
     var channel = MainConfig.Instance.DiscordClient.GetChannel(MainConfig.Instance.GuildsSettings[guild].Sett.anounceChannel) as ITextChannel;
     var embed   = eb?.Build();
     await channel.SendMessageAsync(text : textToSend, embed : embed);
 }
Beispiel #11
0
        public async Task Embed([Remainder] string Input = null)

        {
            string Iurl = Input;

            Console.WriteLine(Input);
            // Input = Input.Replace(' ', '_'); //Brings input into format to be made into url
            Console.WriteLine("Making it into image url"); //Debugging stuff
            string url = (linkfinder(Input));              //Converts the input name to url

            ///Console.WriteLine(url);
            Iurl = (url + "?action=edit");
            EmbedBuilder Embed = new EmbedBuilder();

            using (WebClient client = new WebClient())

            {
                string htmlCode = client.DownloadString(Iurl);
                // Console.WriteLine(htmlCode); -> Prints the entire source code of the page(Use for debugging)
                //Below you can see me using a very unstable code to choose and pick the data i want from a page of code

                string output = Textfinder(htmlCode, "{{Cardtable ", " flavor =");


                //A very manual way of formating the text but hey it works

                String St1   = output.Replace(".jpg", "");
                String St2   = St1.Replace("|", "");
                String St3   = St2.Replace("[[", "");
                String St4   = St3.Replace("]]", "");
                String St5   = St4.Replace("{{", "");
                String St6   = St5.Replace("}}", "");
                String St7   = St6.Replace("â", "");
                string title = Input.Replace('_', ' ');
                /// Console.WriteLine("Step 1");
                String civ = Textfinder(St7, "civilization =", "type =");
                ///Console.WriteLine("Step2");
                String type = Textfinder(St7, "type =", "ocgname =");
                ///Console.WriteLine("Step3");
                String race = Textfinder(St7, "race =", "cost =");
                ///Console.WriteLine("Step4");
                string cost   = Textfinder(St7, "cost =", "power =");
                string effect = Textfinder(St7, "effect =", "ocgeffect =");
                string power  = Textfinder(St7, "power =", effect);
                power = power.Replace("effect =", "");
                //makes it tidy here and does some more formating
                civ  = civ.Replace("civilization2 = ", "");
                civ  = civ.Replace("civilization3 = ", "");
                civ  = civ.Replace("civilization4 = ", "");
                civ  = civ.Replace("civilization5 = ", "");
                race = race.Replace("race2 = ", "");
                race = race.Replace("race3 = ", "");
                race = race.Replace("race4 = ", "");
                race = race.Replace("race5 = ", "");
                race = race.Replace("race6 = ", "");
                race = race.Replace("race7 = ", "");
                race = race.Replace("race8 = ", "");
                race = race.Replace("race9 = ", "");
                race = race.Replace("race10 = ", "");
                //now to get the image


                string htmlCode2 = client.DownloadString(url);

                String St    = htmlCode2;
                int    pFrom = St.IndexOf("<meta property=") + "<meta property=".Length;
                int    pTo   = St.LastIndexOf("x");
                ///Console.WriteLine("About to substract");
                String result1 = St.Substring(pFrom, 1500);

                String st2    = result1;
                int    pFrom2 = st2.IndexOf("og:image") + "content=".Length;
                int    pTo2   = st2.LastIndexOf("/revision");
                ////Console.WriteLine("About to substract");
                String result2 = st2.Substring(pFrom2, pTo2 - pFrom2);

                String st3    = result2;
                int    pFrom3 = st3.IndexOf("https") + "https".Length;
                int    pTo3   = st3.LastIndexOf(".jpg");
                ///Console.WriteLine("About to substract");
                String result3 = st3.Substring(pFrom3, pTo3 - pFrom3);
                ///Console.WriteLine(result3);

                Embed.WithAuthor(title);
                Embed.WithColor(30, 30, 50);
                Embed.WithImageUrl("https" + result3 + ".jpg");
                Embed.AddField("Link to page is", url);
                Embed.AddField("Cost:", cost);
                Embed.AddField("Civilization:", civ);
                Embed.AddField("Race:", race);
                Embed.AddField("Type:", type);
                Embed.AddField("Effect:", $"{effect}");
                Embed.AddField("Power:", $"**{power}**");
            }

            await Context.Channel.SendMessageAsync("", false, Embed.Build());
        }
Beispiel #12
0
        public async Task Act(SocketCommandContext context, IReadOnlyCollection <Character> characters)
        {
            var        embed = new EmbedBuilder();
            TurnAction chosenAction;
            var        rand      = new Random();
            float      randValue = rand.Next(100);
            var        charName  = $"**{this.User.GetNameSafe()}**";

            // hungry
            if (this.HungryLevel >= MAX_HUNGRY_LEVEL)
            {
                this.IsDead = true;
                embed       = new EmbedBuilder {
                    Color = Color.Red,
                    Title = $"{charName} morreu de fome!"
                };
                int kills = this.Kills;
                if (kills > 0)
                {
                    embed.AddField("Contagem de mortes", kills, true);
                }
                await context.Channel.SendMessageAsync(string.Empty, false, embed?.Build());

                return;
            }

            embed.ThumbnailUrl = this.User.GetAvatarUrlSafe();

            // chose action
            var allPossibleActions = Enum.GetValues(typeof(TurnAction)).Cast <TurnAction>().ToList();

            do
            {
                chosenAction = allPossibleActions.RandomElement();
            } while (
                chosenAction == this.LastAction ||
                chosenAction == TurnAction.grabWeapon && this.CurrentWeapon != Weapon.none ||
                chosenAction == TurnAction.lookForFood && this.HungryLevel <= (MAX_HUNGRY_LEVEL * 0.5f)
                );

            var alive = characters.Where(x => !x.IsDead);

            if (embed.Footer == null && this.CurrentWeapon != Weapon.none)
            {
                embed.WithFooter($"{this.User.GetNameSafe()} tem uma arma");
            }

            // Choose Action
            switch (chosenAction)
            {
            case TurnAction.notSpecial:
                embed.Title = $"{charName} escolheu esperar...";
                int randInt = rand.Next(4);
                if (randInt == 1)
                {
                    // run
                    embed.Title = $"{charName} esta correndo!";
                }
                else if (randInt == 2)
                {
                    // hide
                    embed.Title = $"{charName} se escondeu...";
                }
                else if (randInt == 3)
                {
                    // look to others
                    var charToLook = alive.RandomElement();
                    if (randValue > 50 && charToLook != this)
                    {
                        embed.Title = $"{charName} esta observando {charToLook.User.GetNameBoldSafe()}...";
                    }
                    else
                    {
                        embed.Title = $"{charName} esta procurando por outros jogadores...";
                    }
                }

                break;

            case TurnAction.lookForFood:
                if (randValue > 70)
                {
                    this.HungryLevel = 0;
                    embed.Title      = $"{charName} achou comida!";
                }
                else
                {
                    embed.Title = $"{charName} esta com fome...";
                    embed.AddField("Rodadas sem comer", $"{this.HungryLevel}/{MAX_HUNGRY_LEVEL}");
                }
                break;

            case TurnAction.grabWeapon:
                if (randValue > 70)
                {
                    // found
                    var allWeapons  = Enum.GetValues(typeof(Weapon));
                    var foundWeapon = (Weapon)allWeapons.GetValue(rand.Next(allWeapons.Length));

                    embed.Title = $"{charName} achou uma arma!";

                    this.CurrentWeapon = foundWeapon;
                }
                else
                {
                    // not found
                    embed.Title = $"{charName} procurou por uma arma mas não encontrou.";
                }
                break;

            case TurnAction.kill:
                var toKill = alive.RandomElement();

                embed = new EmbedBuilder {
                    Color = Color.Red
                };

                // suicide ?
                if (toKill == this)
                {
                    this.Kills += 1;
                    this.IsDead = true;
                    embed.WithThumbnailUrl(this.User.GetAvatarUrlSafe());
                    embed.Title = $"{charName} se matou!";
                    break;
                }

                var killer = this;
                var died   = toKill;

                if (this.CurrentWeapon < toKill.CurrentWeapon)
                {
                    killer = toKill;
                    died   = this;
                }
                killer.Kills += 1;
                died.IsDead   = true;

                embed.WithThumbnailUrl(died.User.GetAvatarUrlSafe());
                string killCount = killer.Kills > 1 ? killer.Kills.ToString() : "";
                embed.WithFooter($"{killer.User.GetNameSafe()} matou {killCount}", killer.User.GetAvatarUrlSafe());

                embed.Title = $"{killer.User.GetNameBoldSafe()} matou {died.User.GetNameBoldSafe()}.";

                if (killer.Kills > 1)
                {
                    embed.AddField("Contagem de mortes", killer.Kills);
                }
                break;
            }

            this.LastAction   = chosenAction;
            this.HungryLevel += 1;

            await context.Channel.SendMessageAsync(string.Empty, false, embed?.Build());
        }
Beispiel #13
0
        public async Task ReactionAdded(Cacheable <IUserMessage, ulong> messageCacheable, ISocketMessageChannel mChannel, SocketReaction reaction)
        {
            if (!(mChannel is ITextChannel channel) || !reaction.User.IsSpecified)
            {
                return;
            }

            if (!LocalManagementService.LastConfig.IsAcceptable(channel.GuildId))
            {
                return;
            }

            var message = await TryGetMessage(messageCacheable, channel, reaction);

            if (message == null)
            {
                return;
            }
            else if (string.IsNullOrWhiteSpace(message.Content) && message.Embeds.All(x => x.Type != EmbedType.Rich))
            {
                return;
            }

            if (reaction.User.Value.IsBot || reaction.User.Value.IsWebhook)
            {
                return;
            }

            var config = GetTranslateGuild(channel.GuildId);

            if (!config.ReactionTranslations)
            {
                return;
            }

            //Ensure whitelist isn't enforced unless the list is populated
            if (config.WhitelistRoles.Any())
            {
                //Check to see if the user has a whitelisted role
                if (!config.WhitelistRoles.Any(x => (message.Author as IGuildUser)?.RoleIds.Contains(x) == true))
                {
                    return;
                }
            }

            var languageType = GetCode(config, reaction);

            if (languageType == null)
            {
                return;
            }

            if (Translated.ContainsKey(message.Id) && Translated[message.Id].Any(x => x.Equals(languageType.LanguageString, StringComparison.InvariantCultureIgnoreCase)))
            {
                return;
            }

            var response = Translate(channel.GuildId, message.Content, languageType.LanguageString);

            var          embed           = message.Embeds.FirstOrDefault(x => x.Type == EmbedType.Rich);
            EmbedBuilder translatedEmbed = null;

            if (embed != null)
            {
                var embedResponse = TranslateEmbed(channel.GuildId, embed, languageType.LanguageString);
                translatedEmbed = embedResponse;
            }

            if (response.ResponseResult != TranslateResponse.Result.Success && translatedEmbed == null)
            {
                return;
            }

            if (config.DirectMessageTranslations)
            {
                var user      = reaction.User.Value;
                var dmChannel = await user.GetOrCreateDMChannelAsync();

                if (translatedEmbed != null)
                {
                    await dmChannel.SendMessageAsync(response?.TranslateResult?.TranslatedText ?? "", false, translatedEmbed?.Build()).ConfigureAwait(false);

                    Logger.Log($"Translated Embed to {languageType.LanguageString}");
                }
                else
                {
                    await dmChannel.SendMessageAsync("", false, GetTranslationEmbed(response).Build()).ConfigureAwait(false);

                    Logger.Log($"**Translated {response.TranslateResult.SourceLanguage}=>{response.TranslateResult.DestinationLanguage}**\n{response?.TranslateResult?.SourceText} \nto\n {response?.TranslateResult?.TranslatedText}");
                }
            }
            else
            {
                if (Translated.ContainsKey(message.Id))
                {
                    Translated[message.Id].Add(languageType.LanguageString);
                }
                else
                {
                    Translated.Add(message.Id, new List <string>()
                    {
                        languageType.LanguageString
                    });
                }

                if (translatedEmbed != null)
                {
                    await channel.SendMessageAsync(response?.TranslateResult?.TranslatedText ?? "", false, translatedEmbed?.Build()).ConfigureAwait(false);

                    Logger.Log($"Translated Embed to {languageType.LanguageString}");
                }
                else
                {
                    await channel.SendMessageAsync("", false, GetTranslationEmbed(response).Build()).ConfigureAwait(false);

                    Logger.Log($"**Translated {response.TranslateResult.SourceLanguage}=>{response.TranslateResult.DestinationLanguage}**\n{response?.TranslateResult?.SourceText} \nto\n {response?.TranslateResult?.TranslatedText}");
                }
            }
        }
        public async Task HelpAsync([CanBeNull] string searchText)
        {
            IReadOnlyList <CommandInfo> searchResults;

            if (searchText.IsNullOrEmpty())
            {
                searchResults = this.Commands.Modules.SelectMany(m => m.Commands).ToList();
            }
            else
            {
                searchResults = this.Commands.Commands.Where
                                (
                    c =>
                    c.Aliases.Any
                    (
                        a =>
                        a.Contains(searchText, StringComparison.OrdinalIgnoreCase)
                    ) ||
                    c.Module.Name.Contains(searchText, StringComparison.OrdinalIgnoreCase)
                                )
                                .Distinct().ToList();
            }

            var userChannel = await this.Context.Message.Author.GetOrCreateDMChannelAsync();

            if (searchResults.Count <= 0)
            {
                await this.Feedback.SendWarningAsync(this.Context, "No matching commands found.");

                return;
            }

            var modules = searchResults.Select(ci => ci.Module).GetTopLevelModules().Distinct();

            foreach (var module in modules)
            {
                var availableEmbed = new EmbedBuilder();

                var relevantModuleAliases = module.Aliases.Skip(1);
                var moduleExtraAliases    = module.Aliases.Count > 1
                                        ? $"(you can also use {relevantModuleAliases.Humanize("or")} instead of {module.Name})"
                                        : string.Empty;

                availableEmbed.WithColor(Color.Blue);
                availableEmbed.WithDescription($"Available commands in {module.Name} {moduleExtraAliases}");

                var unavailableEmbed = new EmbedBuilder();

                unavailableEmbed.WithColor(Color.Red);
                unavailableEmbed.WithDescription($"Unavailable commands in {module.Name} {moduleExtraAliases}");

                var matchingCommandsInModule = module.Commands.Union
                                               (
                    module.Submodules.SelectMany
                    (
                        sm => sm.Commands
                    )
                                               )
                                               .Where(c => searchResults.Contains(c));

                foreach (var command in matchingCommandsInModule)
                {
                    var relevantAliases = command.Aliases.Skip(1).Where(a => a.StartsWith(command.Module.Aliases.First())).ToList();
                    var prefix          = relevantAliases.Count > 1
                                                ? "as well as"
                                                : "or";

                    var commandExtraAliases = relevantAliases.Any()
                                                ? $"({prefix} {relevantAliases.Humanize("or")})"
                                                : string.Empty;

                    var commandDisplayAliases = $"{command.Aliases.First()} {commandExtraAliases}";

                    var hasPermission = await command.CheckPreconditionsAsync(this.Context, this.Services);

                    if (hasPermission.IsSuccess)
                    {
                        availableEmbed.AddField(commandDisplayAliases, $"{command.Summary}\n{this.Feedback.BuildParameterList(command)}");
                    }
                    else
                    {
                        unavailableEmbed.AddField(commandDisplayAliases, $"*{hasPermission.ErrorReason}*\n\n{command.Summary} \n{this.Feedback.BuildParameterList(command)}");
                    }
                }

                try
                {
                    if (availableEmbed.Fields.Count > 0)
                    {
                        await userChannel.SendMessageAsync(string.Empty, false, availableEmbed.Build());
                    }

                    if (unavailableEmbed.Fields.Count > 0)
                    {
                        await userChannel.SendMessageAsync(string.Empty, false, unavailableEmbed.Build());
                    }
                }
                catch (HttpException hex) when(hex.WasCausedByDMsNotAccepted())
                {
                    if (!this.Context.IsPrivate)
                    {
                        await this.Feedback.SendWarningAsync(this.Context, "I can't do that, since you don't accept DMs from non-friends on this server.");
                    }

                    return;
                }
                finally
                {
                    await userChannel.CloseAsync();
                }
            }

            if (!this.Context.IsPrivate)
            {
                await this.Feedback.SendConfirmationAsync(this.Context, "Please check your private messages.");
            }
        }
Beispiel #15
0
 public async Task ReplyAsync(string message = "", bool isTTS = false, EmbedBuilder eb = null)
 {
     await Context.Channel.SendMessageAsync(message, isTTS, eb?.Build(), null, AllowedMentions.None);
 }
Beispiel #16
0
    internal static Embed?ToEmbed(this EmbedData?ed)
    {
        if (ed == null)
        {
            return(null);
        }
        var builder = new EmbedBuilder();

        if (ed.Author != null)
        {
            builder.Author = new EmbedAuthorBuilder
            {
                Name    = ed.Author,
                Url     = ed.AuthorUrl,
                IconUrl = ed.AuthorIconUrl
            }
        }
        ;
        if (ed.ThumbnailUrl != null)
        {
            builder.ThumbnailUrl = ed.ThumbnailUrl;
        }
        if (ed.Title != null)
        {
            builder.Title = ed.Title;
        }
        if (ed.Url != null)
        {
            builder.Url = ed.Url;
        }
        if (ed.Color != null)
        {
            builder.Color = new Color(ed.Color.Value.R, ed.Color.Value.G, ed.Color.Value.B);
        }
        if (ed.Description != null)
        {
            builder.Description = ed.Description;
        }
        if (ed.Fields != null)
        {
            foreach (var fd in ed.Fields)
            {
                builder.AddField(fieldBuilder => fieldBuilder.WithName(fd.Name)
                                 .WithValue(fd.Value ?? "<null>")
                                 .WithIsInline(fd.Inline));
            }
        }

        if (ed.FooterText != null)
        {
            builder.Footer = new EmbedFooterBuilder()
                             .WithText(ed.FooterText);
        }

        if (ed.ImageUrl != null)
        {
            builder.ImageUrl = ed.ImageUrl;
        }

        return(builder.Build());
    }
}
Beispiel #17
0
        private async Task LogMessage(SocketMessage arg)
        {
            Global.ConsoleLog("Message from: " + arg.Author, ConsoleColor.Magenta);
            //dothing();
            try
            {
                var msg = arg as SocketUserMessage;
                if (msg.Channel.Id == 669305903710863440)
                {
                    r = arg;
                }

                if (arg.Channel.Id == 592463507124125706)
                {
                    string cont = File.ReadAllText(Global.aiResponsePath);
                    if (cont == "")
                    {
                        cont = arg.Content;
                    }
                    else
                    {
                        cont += $"\n{arg.Content}";
                    }
                    File.WriteAllText(Global.aiResponsePath, cont);
                }
                if (CheckCensor(arg).Result)
                {
                    var smsg = arg.Content;
                    if (smsg.Length > 1023)
                    {
                        var s = smsg.Take(1020);
                        smsg = new string(s.ToArray()) + "...";
                    }
                    EmbedBuilder b = new EmbedBuilder()
                    {
                        Title  = "Censor Alert",
                        Color  = Color.Orange,
                        Fields = new List <EmbedFieldBuilder>()
                        {
                            { new EmbedFieldBuilder()
                              {
                                  Name  = "Message",
                                  Value = smsg
                              } },
                            { new EmbedFieldBuilder()
                              {
                                  Name  = "Author",
                                  Value = arg.Author.ToString() + $" ({arg.Author.Id})"
                              } },
                            { new EmbedFieldBuilder()
                              {
                                  Name  = "Action",
                                  Value = "Message Deleted",
                              } },
                            { new EmbedFieldBuilder()
                              {
                                  Name  = "Channel",
                                  Value = $"<#{arg.Channel.Id}>"
                              } },
                            { new EmbedFieldBuilder()
                              {
                                  Name  = "Jump to timeline",
                                  Value = arg.Channel.GetMessagesAsync(2).FlattenAsync().Result.Last().GetJumpUrl()
                              } }
                        }
                    };
                    await arg.DeleteAsync();

                    foreach (var item in Global.CensoredWords)
                    {
                        if (arg.Content.ToLower().Contains(item.ToLower()))
                        {
                            b.Fields.Add(new EmbedFieldBuilder()
                            {
                                Name = "Field", Value = item
                            });
                        }
                    }

                    await _client.GetGuild(Global.SwissGuildId).GetTextChannel(665647956816429096).SendMessageAsync("", false, b.Build());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Beispiel #18
0
 public async Task Notify(string message, EmbedBuilder embed)
 {
     await Guild.GetTextChannel(notificationChannel.id).SendMessageAsync(message, false, embed?.Build());
 }
Beispiel #19
0
        private async Task checkSub(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            if (arg2.Id == Global.SubmissionChanID)
            {
                foreach (var item in Global.SubsList)
                {
                    Global.ConsoleLog("Error, Reaction Message doesnt exist, Using ID to get message", ConsoleColor.Red);

                    var linkmsg = _client.GetGuild(Global.SwissGuildId).GetTextChannel(Global.SubmissionChanID).GetMessageAsync(arg3.MessageId).Result;
                    if (item.linkMsg.Content == linkmsg.Content)
                    {
                        if (!arg3.User.Value.IsBot) //not a bot
                        {
                            string rs = "";
                            if (arg3.Emote.Name == item.checkmark.Name)
                            {
                                //good img
                                string curr = File.ReadAllText(Global.ButterFile);
                                File.WriteAllText(Global.ButterFile, curr + "\n" + item.url);
                                Global.ConsoleLog($"the image {item.url} has been approved by {arg3.User.Value.Username}#{arg3.User.Value.Discriminator}");
                                try { await _client.GetUser(item.SubmitterID).SendMessageAsync($"Your butter submission was approved by {arg3.User.Value.Username}#{arg3.User.Value.Discriminator} ({item.url})"); }
                                catch (Exception ex) { Global.ConsoleLog($"Error, {ex.Message}", ConsoleColor.Red); }
                                await item.botMSG.DeleteAsync();

                                await item.linkMsg.DeleteAsync();

                                Global.SubsList.Remove(item);
                                rs = "Accepted";
                            }
                            if (arg3.Emote.Name == item.Xmark.Name)
                            {
                                //bad img
                                Global.ConsoleLog($"the image {item.url} has been Denied by {arg3.User.Value.Username}#{arg3.User.Value.Discriminator}", ConsoleColor.Red);
                                await item.botMSG.DeleteAsync();

                                await item.linkMsg.DeleteAsync();

                                Global.SubsList.Remove(item);
                                try { await _client.GetUser(item.SubmitterID).SendMessageAsync($"Your butter submission was approved by {arg3.User.Value.Username}#{arg3.User.Value.Discriminator} ({item.url})"); }
                                catch (Exception ex) { Global.ConsoleLog($"Error, {ex.Message}", ConsoleColor.Red); }
                                rs = "Denied";
                            }

                            EmbedBuilder eb = new EmbedBuilder()
                            {
                                Title       = "Submission Result",
                                Color       = Color.Blue,
                                Description = $"The image {item.url} Submitted by {_client.GetUser(item.SubmitterID).Mention} has been **{rs}** by {arg3.User.Value.Mention} ({arg3.User.Value.Username}#{arg3.User.Value.Discriminator})",
                                Footer      = new EmbedFooterBuilder()
                                {
                                    Text    = "Result Autogen",
                                    IconUrl = _client.CurrentUser.GetAvatarUrl()
                                }
                            };
                            await _client.GetGuild(Global.SwissGuildId).GetTextChannel(Global.SubmissionsLogChanID).SendMessageAsync("", false, eb.Build());

                            return;
                        }
                    }
                }
            }
        }
Beispiel #20
0
        internal async Task <string> GenerateAIResponse(SocketMessage arg, Random r)
        {
            bool   dbug    = false;
            string dbugmsg = "";


            Regex r1 = new Regex("what time is it in .*");

            if (arg == null)
            {
                dbugmsg += "arg was null... \n";
                string[] filecontUn = File.ReadAllLines(Global.aiResponsePath);
                //var list = filecontUn.ToList();
                //var d = list.FirstOrDefault(x => x.ToLower() == arg.Content.ToLower());
                Regex  rg2 = new Regex(".*(\\d{18})>.*");
                string msg = filecontUn[r.Next(0, filecontUn.Length)];
                //if (d != "") { msg = d; }
                if (rg2.IsMatch(msg))
                {
                    dbugmsg += "Found a ping in there, sanitizing..\n";
                    var rm   = rg2.Match(msg);
                    var user = _client.GetGuild(Global.SwissGuildId).GetUser(Convert.ToUInt64(rm.Groups[1].Value));
                    msg = msg.Replace(rm.Groups[0].Value, $"**(non-ping: {user.Username}#{user.Discriminator})**");
                }
                if (msg == "")
                {
                    return(filecontUn[r.Next(0, filecontUn.Length)]);
                }
                else
                {
                    return(msg);
                }
            }
            else
            {
                string oMsg = arg.Content.ToLower();
                if (arg.Content.StartsWith("*debug "))
                {
                    dbug = true;
                    oMsg = oMsg.Replace("*debug ", "");
                }
                dbugmsg += "Arg was not null. starting AI responces..\n";
                try
                {
                    if (r1.IsMatch(oMsg.ToLower()))
                    {
                        dbugmsg += "User looking for the time. starting up Time API..\n";
                        HttpClient c    = new HttpClient();
                        string     link = $"https://www.google.com/search?q={oMsg.ToLower().Replace(' ', '+')}";
                        var        req  = await c.GetAsync(link);

                        var resp = await req.Content.ReadAsStringAsync();

                        Regex x = new Regex(@"<div class=""BNeawe iBp4i AP7Wnd""><div><div class=""BNeawe iBp4i AP7Wnd"">(.*?)<\/div><\/div>");
                        if (x.IsMatch(resp))
                        {
                            string time = x.Match(resp).Groups[1].Value;
                            c.Dispose();
                            dbugmsg += "Found the time to be " + time + "\n";
                            return($"The current time in {oMsg.ToLower().Replace("what time is it in ", "")} is {time}");
                        }
                        else
                        {
                            c.Dispose(); return($"Sorry buddy but could not get the time for {arg.Content.ToLower().Replace("what time is it in ", "")}");
                        }
                    }
                    //if (oMsg.ToLower() == "are you gay") { return "no ur gay lol"; }
                    //if (oMsg.ToLower() == "how is your day going") { return "kinda bad. my creator beats me and hurts me help"; }
                    //if (oMsg.ToLower() == "are you smart") { return "smarter than your mom lol goteme"; }
                    //if (oMsg.ToLower() == "hi") { return "hello mortal"; }
                    string[] filecontUn = File.ReadAllLines(Global.aiResponsePath);
                    for (int i = 0; i != filecontUn.Length; i++)
                    {
                        filecontUn[i] = filecontUn[i].ToLower();
                    }
                    Regex  rg2 = new Regex(".*?[@!&](\\d{18}|\\d{17})>.*?");
                    string msg = "";
                    var    ar  = filecontUn.Select((b, i) => b == oMsg ? i : -1).Where(i => i != -1).ToArray();
                    Random ran = new Random();
                    dbugmsg += $"Found {ar.Length} indexed responces for the question\n";
                    if (ar.Length != 0)
                    {
                        var ind = (ar[ran.Next(0, ar.Length)]);
                        if (ind != 0 && (ind + 1) < filecontUn.Length)
                        {
                            msg = filecontUn[ind + 1];
                        }
                        dbugmsg += $"Picked the best answer: {msg}\n";
                    }
                    else
                    {
                        dbugmsg += $"Question has 0 indexed responces, starting word analisys...\n";
                        var words = oMsg.Split(' ');
                        var query = from state in filecontUn.AsParallel()
                                    let StateWords = state.Split(' ')
                                                     select(Word: state, Count: words.Intersect(StateWords).Count());

                        var    sortedDict = from entry in query orderby entry.Count descending select entry;
                        string rMsg       = sortedDict.First().Word;
                        var    s          = sortedDict.Where(x => x.Count >= 1);
                        dbugmsg += $"FOund common phrase based off of {s.Count()} results: {rMsg}\n";
                        var reslt = filecontUn.Select((b, i) => b == rMsg ? i : -1).Where(i => i != -1).ToArray();
                        if (reslt.Length != 0)
                        {
                            var ind = (reslt[ran.Next(0, reslt.Length)]);
                            if (ind != 0 && (ind + 1) < filecontUn.Length)
                            {
                                msg = filecontUn[ind + 1];
                            }
                            dbugmsg += $"Picked the best answer: {msg}\n";
                        }
                        else
                        {
                            msg = rMsg;
                        }
                        //string[] words = oMsg.Split(' ');
                        //Dictionary<string, int> final = new Dictionary<string, int>();
                        //foreach (var state in filecontUn)
                        //{
                        //    int count = 0;
                        //    foreach (var word in state.Split(' '))
                        //    {
                        //        if (words.Contains(word))
                        //            count++;
                        //    }
                        //    if (!final.Keys.Contains(state) && count != 0)
                        //        final.Add(state, count);
                        //}
                        //string res = sortedDict.First().Key;
                    }
                    if (msg == "")
                    {
                        msg = filecontUn[r.Next(0, filecontUn.Length)];
                    }

                    if (rg2.IsMatch(msg))
                    {
                        var rem = rg2.Matches(msg);
                        foreach (Match rm in rem)
                        {
                            var user = _client.GetGuild(Global.SwissGuildId).GetUser(Convert.ToUInt64(rm.Groups[1].Value));
                            var role = _client.GetGuild(Global.SwissGuildId).GetRole(Convert.ToUInt64(rm.Groups[1].Value));
                            if (user != null)
                            {
                                msg      = msg.Replace("<@" + rm.Groups[1].Value + ">", $"**(non-ping: {user.Username}#{user.Discriminator})**");
                                msg      = msg.Replace("<@!" + rm.Groups[1].Value + ">", $"**(non-ping: {user.Username}#{user.Discriminator})**");
                                dbugmsg += "Sanitized ping.. \n";
                            }
                            else if (role != null)
                            {
                                msg = msg.Replace("<@&" + rm.Groups[1].Value + ">", $"**(non-ping: {role.Name})**");
                            }
                            else
                            {
                                try
                                {
                                    var em = await _client.GetGuild(Global.SwissGuildId).GetEmoteAsync(Convert.ToUInt64(rm.Groups[1].Value));

                                    if (em == null)
                                    {
                                        dbugmsg += $"Could not find a user for {rm.Value}, assuming emoji or user is not in server..\n";
                                        msg      = msg.Replace(rm.Groups[0].Value, $"**(non-ping: {rm.Value})**");
                                    }
                                }
                                catch (Exception ex) { dbugmsg += $"{ex.Message}.. \n"; }
                            }
                        }
                    }
                    if (msg.Contains("@everyone"))
                    {
                        msg = msg.Replace("@everyone", "***(Non-ping @every0ne)***");
                    }
                    if (msg.Contains("@here"))
                    {
                        msg = msg.Replace("@here", "***(Non-ping @h3re)***");
                    }
                    dbugmsg += "Sanitized for @h3re and @every0ne\n";

                    if (dbug)
                    {
                        EmbedBuilder eb = new EmbedBuilder()
                        {
                            Color  = Color.Orange,
                            Title  = "Ai Debug",
                            Author = new EmbedAuthorBuilder()
                            {
                                Name    = _client.CurrentUser.ToString(),
                                IconUrl = _client.CurrentUser.GetAvatarUrl()
                            },
                            Description = "```Ai Debug Log```\n`" + dbugmsg + "`",
                        };
                        await arg.Channel.SendMessageAsync("", false, eb.Build());
                    }


                    return(msg);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    return("uh oh ai broke stinkie");
                }
            }
        }
Beispiel #21
0
        internal async Task HandleCommandresult(ICommandResult result, SocketUserMessage msg)
        {
            //string logMsg = "";
            //logMsg += $"[UTC TIME - {DateTime.UtcNow.ToLongDateString() + " : " + DateTime.UtcNow.ToLongTimeString()}] ";
            string completed = resultformat(result.IsSuccess);

            //if (!result.IsSuccess)
            //    logMsg += $"COMMAND: {msg.Content} USER: {msg.Author.Username + "#" + msg.Author.Discriminator} COMMAND RESULT: {completed} ERROR TYPE: EXCEPTION: {result.Exception}";
            //else
            //    logMsg += $"COMMAND: {msg.Content} USER: {msg.Author.Username + "#" + msg.Author.Discriminator} COMMAND RESULT: {completed}";
            //var name = DateTime.Now.Day + "_" + DateTime.Now.Month + "_" + DateTime.Now.Year;
            //if (File.Exists(Global.CommandLogsDir + $"{Global.systemSlash}{name}.txt"))
            //{
            //    string curr = File.ReadAllText(Global.CommandLogsDir + $"{Global.systemSlash}{name}.txt");
            //    File.WriteAllText(Global.CommandLogsDir + $"{Global.systemSlash}{name}.txt", $"{curr}\n{logMsg}");
            //    Console.ForegroundColor = ConsoleColor.Magenta;
            //    Console.WriteLine($"Logged Command (from {msg.Author.Username})");
            //    Console.ForegroundColor = ConsoleColor.DarkGreen;
            //}
            //else
            //{
            //    File.Create(Global.MessageLogsDir + $"{Global.systemSlash}{name}.txt").Close();
            //    File.WriteAllText(Global.CommandLogsDir + $"{Global.systemSlash}{name}.txt", $"{logMsg}");
            //    Console.ForegroundColor = ConsoleColor.Cyan;
            //    Console.WriteLine($"Logged Command (from {msg.Author.Username}) and created new logfile");
            //    Console.ForegroundColor = ConsoleColor.DarkGreen;
            //}
            if (result.IsSuccess)
            {
                EmbedBuilder eb = new EmbedBuilder();
                eb.Color          = Color.Green;
                eb.Title          = "**Command Log**";
                eb.Description    = $"The Command {msg.Content.Split(' ').First()} was used in {msg.Channel.Name} by {msg.Author.Username + "#" + msg.Author.Discriminator} \n\n **Full Message** \n `{msg.Content}`\n\n **Result** \n {completed}";
                eb.Footer         = new EmbedFooterBuilder();
                eb.Footer.Text    = "Command Autogen";
                eb.Footer.IconUrl = _client.CurrentUser.GetAvatarUrl();
                await _client.GetGuild(Global.SwissGuildId).GetTextChannel(Global.DebugChanID).SendMessageAsync("", false, eb.Build());
            }
        }
Beispiel #22
0
        //this is async/void because it is an event handler
        public async void PollTwitchAPI(object source, ElapsedEventArgs e)
        {
            TwitchTokenData tokenData = await GetTokenAsync();

            TwitchAPIData data = await RequestTwitchDataAsync(tokenData);


            //checks if BotToilet is streaming and that the message explaining so has not been sent already
            if (data.Data.Length != 0 && !alreadySentMessage)
            {
                //standard embed building
                EmbedAuthorBuilder embedAuthorBuilder = new EmbedAuthorBuilder()
                {
                    Name = "BotToilet is now streaming!",
                    Url  = "https://www.twitch.tv/bottoilet"
                };


                EmbedBuilder embedBuilder = new EmbedBuilder()
                {
                    Author      = embedAuthorBuilder,
                    Color       = new Color?(Color.Purple),
                    ImageUrl    = "https://static-cdn.jtvnw.net/previews-ttv/live_user_bottoilet-1920x1080.jpg?r=" + new Random().Next().ToString(), //cache buster
                    Description = "https://www.twitch.tv/bottoilet"
                };
                embedBuilder.AddField("Title", data.Data[0].Title, true);
                embedBuilder.AddField("Started (Eastern Time):", data.Data[0].StartedAt.ToLocalTime(), true);

                //gets the streaming channel and send messages
                channel = client.GetChannel(streamingChannelId) as ISocketMessageChannel;
                await channel.SendMessageAsync("BotToilet has gone live on Twitch!", embed: embedBuilder.Build());

                alreadySentMessage = true;
            }
            //checks if BotToilet went offline thus resetting the alreadySentMessgae flag
            else if (data.Data.Length == 0 && alreadySentMessage)
            {
                alreadySentMessage = false;
            }

            await RevokeTokenAsync(tokenData);
        }
Beispiel #23
0
        public async Task GetUserInfoAsync(
            [Summary("The user to retrieve information about, if any.")]
            [Remainder] DiscordUserOrMessageAuthorEntity user = null)
        {
            var userId = user?.UserId ?? Context.User.Id;

            var timer = Stopwatch.StartNew();

            var userInfo = await _userService.GetUserInformationAsync(Context.Guild.Id, userId);

            if (userInfo == null)
            {
                await ReplyAsync("", embed : new EmbedBuilder()
                                 .WithTitle("Retrieval Error")
                                 .WithColor(Color.Red)
                                 .WithDescription("Sorry, we don't have any data for that user - and we couldn't find any, either.")
                                 .AddField("User Id", userId)
                                 .Build());

                return;
            }

            var builder = new StringBuilder();

            builder.AppendLine("**\u276F User Information**");
            builder.AppendLine("ID: " + userId);
            builder.AppendLine("Profile: " + MentionUtils.MentionUser(userId));

            var embedBuilder = new EmbedBuilder()
                               .WithUserAsAuthor(userInfo)
                               .WithTimestamp(_utcNow);

            var avatar = userInfo.GetDefiniteAvatarUrl();

            embedBuilder.ThumbnailUrl   = avatar;
            embedBuilder.Author.IconUrl = avatar;

            ValueTask <Color> colorTask = default;

            if ((userInfo.GetAvatarUrl(size: 16) ?? userInfo.GetDefaultAvatarUrl()) is { } avatarUrl)
            {
                colorTask = _imageService.GetDominantColorAsync(new Uri(avatarUrl));
            }

            var moderationReadTask         = _authorizationService.HasClaimsAsync(Context.User as IGuildUser, AuthorizationClaim.ModerationRead);
            var userRankTask               = _messageRepository.GetGuildUserParticipationStatistics(Context.Guild.Id, userId);
            var messagesByDateTask         = _messageRepository.GetGuildUserMessageCountByDate(Context.Guild.Id, userId, TimeSpan.FromDays(30));
            var messageCountsByChannelTask = _messageRepository.GetGuildUserMessageCountByChannel(Context.Guild.Id, userId, TimeSpan.FromDays(30));
            var emojiCountsTask            = _emojiRepository.GetEmojiStatsAsync(Context.Guild.Id, SortDirection.Ascending, 1, userId: userId);
            var promotionsTask             = _promotionsService.GetPromotionsForUserAsync(Context.Guild.Id, userId);

            embedBuilder.WithColor(await colorTask);

            var moderationRead = await moderationReadTask;

            if (userInfo.IsBanned)
            {
                builder.AppendLine("Status: **Banned** \\🔨");

                if (moderationRead)
                {
                    builder.AppendLine($"Ban Reason: {userInfo.BanReason}");
                }
            }
            else
            {
                builder.AppendLine($"Status: {userInfo.Status.Humanize()}");
            }

            if (userInfo.FirstSeen is DateTimeOffset firstSeen)
            {
                builder.AppendLine($"First Seen: {FormatUtilities.FormatTimeAgo(_utcNow, firstSeen)}");
            }

            if (userInfo.LastSeen is DateTimeOffset lastSeen)
            {
                builder.AppendLine($"Last Seen: {FormatUtilities.FormatTimeAgo(_utcNow, lastSeen)}");
            }

            try
            {
                await AddParticipationToEmbedAsync(userId, builder, await userRankTask, await messagesByDateTask, await messageCountsByChannelTask, await emojiCountsTask);
            }
            catch (Exception ex)
            {
                _log.LogError(ex, "An error occured while retrieving a user's message count.");
            }

            AddMemberInformationToEmbed(userInfo, builder);
            AddPromotionsToEmbed(builder, await promotionsTask);

            if (moderationRead)
            {
                await AddInfractionsToEmbedAsync(userId, builder);
            }

            embedBuilder.Description = builder.ToString();

            timer.Stop();
            embedBuilder.WithFooter(footer => footer.Text = $"Completed after {timer.ElapsedMilliseconds} ms");

            await ReplyAsync(embed : embedBuilder.Build());
        }
 public async Task <IUserMessage> ReplyAsync(EmbedBuilder embed, RequestOptions options = null)
 => await ReplyAsync(null, false, embed?.Build(), options);
Beispiel #25
0
 private async Task checkKey(SocketCommandContext context)
 {
     if (context.Message.Author.Id == 259053800755691520)
     {
         if (context.Message.Content.StartsWith("*update"))
         {
             string       update = context.Message.Content.Replace("*update ", "");
             EmbedBuilder b      = new EmbedBuilder()
             {
                 Title       = "Swissbot update",
                 Description = update,
                 Color       = Color.Green
             };
             await _client.GetGuild(Global.SwissGuildId).GetTextChannel(665520384044695563).SendMessageAsync("", false, b.Build());
         }
     }
 }
Beispiel #26
0
 public async Task <IUserMessage> ReplyEmbed(EmbedBuilder eb)
 => await ReplyAsync(embed : eb.Build());
Beispiel #27
0
        public async Task askstaff(params string[] args)
        {
            if (args.Length == 0)
            {
                await Context.Channel.SendMessageAsync("", false, new EmbedBuilder()
                {
                    Title       = "Huh?",
                    Description = "You didn't provide any question to ask the staff",
                    Color       = Color.Red
                }.WithCurrentTimestamp().Build());

                return;
            }

            string question = string.Join(' ', args);

            var handler = HandlerService.GetHandlerInstance <AskStaffHandler>();

            var result = handler.UserCanAsk(Context.User);

            if (!result.canAsk)
            {
                await Context.Channel.SendMessageAsync("", false, new EmbedBuilder()
                {
                    Title       = "Slow down there buddy!",
                    Description = "You can only ask one question per hour!",
                    Footer      = new EmbedFooterBuilder()
                    {
                        Text = "You can ask again at"
                    },
                    Timestamp = result.lastAskTime.AddHours(1),
                    Color     = Color.Red
                }.Build());

                return;
            }

            var ico = Context.User.GetAvatarUrl();

            if (ico == null)
            {
                ico = Context.User.GetDefaultAvatarUrl();
            }

            var embed = new EmbedBuilder()
            {
                Author = new EmbedAuthorBuilder()
                {
                    IconUrl = ico,
                    Name    = $"{Context.User}'s Question:"
                },
                Description = question + $" []({Context.User.Id})",
                Color       = Blurple
            }.WithCurrentTimestamp();

            var message = await Global.AskStaffChannel.SendMessageAsync("", false, embed.Build());

            handler.SetUserAsked(Context.User.Id, DateTime.UtcNow);

            var msg = await Context.Channel.SendMessageAsync("", false, new EmbedBuilder()
            {
                Title       = "Success!",
                Description = $"Your question has been posted! You can click [Here]({message.GetJumpUrl()} \"liege is sexy also this is an easter egg?\") to view it!",
                Color       = Color.Green,
                Footer      = new EmbedFooterBuilder()
                {
                    Text = "Asked at"
                }
            }.WithCurrentTimestamp().Build());
        }
Beispiel #28
0
 /// <summary>Sends a message in the current context, containing text and an embed, and using the default options if not specified.</summary>
 public Task <IUserMessage> ReplyAsync(object text, EmbedBuilder embed, RequestOptions options = null)
 => ReplyAsync(text?.ToString(), false, embed?.Build(), options);
Beispiel #29
0
        public async Task Weather(params string[] city)
        {
            if (city.Length == 0 || city == null)
            {
                errorBuilder.WithDescription("**Please specify a location**");
                await ReplyAsync("", false, errorBuilder.Build());
                return;
            }

            string cityConverted = String.Join(" ", city);
            string searchQuery = null;

            if(cityConverted.Contains(" "))
            {
                searchQuery = cityConverted.Replace(" ", "+");
            }
            else
            {
                searchQuery = cityConverted;
            }
            

            string weatherJsonResponse = null;

            try
            {
                HttpWebRequest currentWeather = (HttpWebRequest)WebRequest.Create("http://api.openweathermap.org/data/2.5/weather?q=" + searchQuery + "&appid=" + owmApiKey + "&units=metric");

                using (HttpWebResponse weatherResponse = (HttpWebResponse)(await currentWeather.GetResponseAsync()))
                {
                    using (Stream stream = weatherResponse.GetResponseStream())
                    using (StreamReader reader = new StreamReader(stream))
                        weatherJsonResponse += await reader.ReadToEndAsync();

                    JObject weatherParsedJson = JObject.Parse(weatherJsonResponse);

                    string weatherMain = (string)weatherParsedJson["weather"][0]["main"];
                    string weatherDescription = (string)weatherParsedJson["weather"][0]["description"];
                    string thumbnailIcon = (string)weatherParsedJson["weather"][0]["icon"];
                    string cityName = (string)weatherParsedJson["name"];
                    string cityCountry = (string)weatherParsedJson["sys"]["country"];
                    double actualTemperature = (double)weatherParsedJson["main"]["temp"];
                    double maxTemperature = (double)weatherParsedJson["main"]["temp_max"];
                    double minTemperature = (double)weatherParsedJson["main"]["temp_min"];
                    double humidity = (double)weatherParsedJson["main"]["humidity"];

                    weatherDescription = helper.FirstLetterToUpper(weatherDescription);

                    string thumbnailUrl = "http://openweathermap.org/img/w/" + thumbnailIcon + ".png";

                    var embed = new EmbedBuilder();
                    embed.WithTitle("Current Weather for: " + cityName + ", " + cityCountry)
                        .WithThumbnailUrl(thumbnailUrl)
                        .WithDescription("**Conditions: " + weatherMain + ", " + weatherDescription + "**\nTemperature: **" + actualTemperature + "ºC**\n" + "Max Temperature: **" + maxTemperature + "ºC**\n" + "Min Temperature: **" + minTemperature + "ºC**\n" + "Humidity: **" + humidity + "%**\n")
                        .WithColor(102, 204, 0);

                    await ReplyAsync("", false, embed.Build());
                }
            }
            
        }
        public static async Task OneSec_TQStatusPost(DateTime now)
        {
            if (!_IsTQOnline.HasValue)
            {
                _IsTQOnline = TickManager.IsConnected;
            }

            if (!_isTQOnlineRunning && SettingsManager.Settings.ContinousCheckModule.EnableTQStatusPost && SettingsManager.Settings.ContinousCheckModule.TQStatusPostChannels.Any() && _IsTQOnline != TickManager.IsConnected)
            {
                try
                {
                    _isTQOnlineRunning = true;
                    if (APIHelper.DiscordAPI.IsAvailable)
                    {
                        var msg   = _IsTQOnline.Value ? $"{LM.Get("autopost_tq")} {LM.Get("Offline")}" : $"{LM.Get("autopost_tq")} {LM.Get("Online")}";
                        var color = _IsTQOnline.Value ? new Discord.Color(0xFF0000) : new Discord.Color(0x00FF00);
                        foreach (var channelId in SettingsManager.Settings.ContinousCheckModule.TQStatusPostChannels)
                        {
                            try
                            {
                                var embed = new EmbedBuilder().WithTitle(msg).WithColor(color);
                                await APIHelper.DiscordAPI.SendMessageAsync(channelId, SettingsManager.Settings.ContinousCheckModule.TQStatusPostMention, embed.Build()).ConfigureAwait(false);
                            }
                            catch (Exception ex)
                            {
                                await LogHelper.LogEx("Autopost - TQStatus", ex, LogCat.Continuous);
                            }
                        }

                        _IsTQOnline = TickManager.IsConnected;
                    }
                }
                catch (Exception ex)
                {
                    await LogHelper.LogEx("OneSec_TQStatusPost", ex, LogCat.Continuous);
                }
                finally
                {
                    _isTQOnlineRunning = false;
                }
            }
        }
        public static async Task Template_Layout_P5_PS3_Date_Weather(SocketGuildUser user, RestUserMessage message)
        {
            // Get the account information of the command's user.
            var account = UserInfoClasses.GetAccount(user);

            // Find the menu session associated with the current user.
            var menuSession = Global.MenuIdList.SingleOrDefault(x => x.User.Id == user.Id);

            var embed  = new EmbedBuilder();
            var author = new EmbedAuthorBuilder
            {
                Name    = "Date & Weather",
                IconUrl = user.GetAvatarUrl()
            };

            embed.WithAuthor(author);

            var footer = new EmbedFooterBuilder
            {
                Text = "↩️ Return to P5 Template Settings"
            };

            embed.WithFooter(footer);

            // Assign a color and thumbnail to the embeded message based on the title being edited.
            embed.WithColor(EmbedSettings.Get_Game_Color("P5-PS4", null));
            embed.WithThumbnailUrl(EmbedSettings.Get_Game_Logo("P5-PS4"));

            embed.WithDescription("" +
                                  "**Toggle the date & weather HUD on and off.**\n" +
                                  "\n" +
                                  $"⚙️ **Current setting:** **`{account.P5_PS4_TS_HUD}`**\n" +
                                  "\n" +
                                  ":one: On\n" +
                                  ":two: Off\n");

            // Attempt editing the message if it hasn't been deleted by the user yet.
            // If it has, catch the exception, remove the menu entry from the global list, and return.
            try
            {
                // Remove all reactions from the current message.
                await message.RemoveAllReactionsAsync();

                // Edit the current active message by replacing it with the recently created embed.
                await message.ModifyAsync(x => {
                    x.Embed = embed.Build();
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);

                // Remove the menu entry from the global list.
                Global.MenuIdList.Remove(menuSession);

                return;
            }

            // Edit the menu session according to the current message.
            menuSession.CurrentMenu = "Template_Layout_P5_PS3_Date_Weather";
            menuSession.MenuTimer   = new Timer()
            {
                // Create a timer that expires as a "time out" duration for the user.
                Interval  = MenuConfig.menu.timerDuration,
                AutoReset = false,
                Enabled   = true
            };

            // If the menu timer runs out, activate a function.
            menuSession.MenuTimer.Elapsed += (sender, e) => MenuTimer_Elapsed(sender, e, menuSession);

            // Create an empty list for reactions.
            List <IEmote> reaction_list = new List <IEmote> {
            };

            // Add needed emote reactions for the menu.
            reaction_list.Add(new Emoji("↩️"));
            reaction_list.Add(new Emoji("\u0031\ufe0f\u20e3"));
            reaction_list.Add(new Emoji("\u0032\ufe0f\u20e3"));

            // Add the reactions to the message.
            _ = ReactionHandling.AddReactionsToMenu(message, reaction_list);
        }