Exemple #1
0
        public async Task <bool> JoinCmd(CommandMessage message)
        {
            if (this.musicPlayer != null)
            {
                IVoiceState voiceState = message.Author as IVoiceState;
                if (voiceState.VoiceChannel != null)
                {
                    return(await this.musicPlayer.JoinAudio(message.Guild, voiceState.VoiceChannel));
                }
                else
                {
                    Discord.Rest.RestUserMessage responseMessage = await message.Channel.SendMessageAsync("You need to join a voice channel first, _kupo!_", messageReference : message.MessageReference);

                    await Task.Delay(3000);

                    // Delete response command
                    await responseMessage.DeleteAsync();
                }
            }

            // Delete calling command
            await message.Message.DeleteAsync();

            return(false);
        }
        private async Task <ulong> LodgeTransactionTask(DataBaseHandlingService db, CommandHandlingService CommandService, StockMarketService marketService, int hours, int mins)
        {
            EmbedFieldBuilder typeField    = new EmbedFieldBuilder().WithIsInline(true).WithName("Type:").WithValue($"Industry Auction");
            EmbedFieldBuilder companyField = new EmbedFieldBuilder().WithIsInline(true).WithName("ID:").WithValue(industryID);
            EmbedFieldBuilder amountField  = new EmbedFieldBuilder().WithIsInline(true).WithName("Type:").WithValue((string)await db.GetFieldAsync(industryID, "Type", "industries"));
            EmbedFieldBuilder priceField   = new EmbedFieldBuilder().WithIsInline(true).WithName("Price:").WithValue("$" + price);

            EmbedBuilder emb = new EmbedBuilder().WithTitle("Stock Market Offer").WithDescription($"Use the command `&bid [ticker] {id.ToString()} [price]` to accept this offer.").WithFooter($"Transaction ID: {id.ToString()}").AddField(typeField).AddField(companyField).AddField(amountField).AddField(priceField).WithColor(Color.Green);

            Discord.Rest.RestUserMessage message = await CommandService.PostEmbedTask((string)await db.GetFieldAsync("MarketChannel", "channel", "system"), emb.Build());

            DateTime now       = DateTime.UtcNow;
            DateTime scheduled = now.AddHours(hours).AddMinutes(mins);

            plannedEnd = scheduled;
            JobDataMap map = new JobDataMap();

            map.Add("market", marketService);
            map.Add("auction", this);
            map.Add("command", CommandService);
            map.Add("db", db);
            IJobDetail job     = JobBuilder.Create <Job>().SetJobData(map).Build();
            ITrigger   trigger = TriggerBuilder.Create().WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromMilliseconds(1)).WithRepeatCount(1)).StartAt(plannedEnd).Build();
            await CommandService.scheduler.ScheduleJob(job, trigger);

            return(message.Id);
        }
Exemple #3
0
        public async Task HelpList()
        {
            await Context.Message.AddReactionAsync(Emote.Parse("<:ThinkRadiance:567800282797309957>"));

            if (Global.HelpHandler.Item1 != null)
            {
                try
                {
                    await Global.HelpHandler.Item1.DeleteAsync();
                }
                catch { }
            }

            EmbedBuilder builder = new EmbedBuilder();

            builder
            .WithTitle(Text("help_header").ToString())
            .WithColor(Color.DarkBlue)
            .AddField(Text("help_titles")[0].ToString(), Text("help")[0].ToString())
            .WithFooter(Text("help_page") + "1/" + (Text("help").AllNodes.Count() - 1).ToString());

            Discord.Rest.RestUserMessage a = await Context.Channel.SendMessageAsync("", false, builder.Build());

            await a.AddReactionAsync(new Emoji("◀"));

            await a.AddReactionAsync(new Emoji("▶"));

            Global.HelpHandler = (a, 0);
        }
        public async Task StartAsync([Summary("Event type")] string type, [Summary("Note for the DKP Log")][Remainder] string note)
        {
            if (Program.AttendanceEvent.active)
            {
                await ReplyAsync($"Unable to start event, another event is still running: {Program.AttendanceEvent.type} {Program.AttendanceEvent.note}");

                return;
            }

            string[] types = Config.Global.Commands.Attendance.ValidAttendanceTypes;
            bool     valid = false;

            foreach (string validType in types)
            {
                if (type == validType)
                {
                    valid = true;
                    break;
                }
            }

            if (!valid)
            {
                await ReplyAsync($"I don't recognize attendance type {type}");

                return;
            }

            Discord.Rest.RestUserMessage message = await Context.Channel.SendMessageAsync($"<@&{Config.Global.Commands.Attendance.MemberRole}> Attendance tracking for {type} {note} has begun, click the check mark to be counted!");

            Program.AttendanceEvent = new SAttendanceEvent(type, note, message.Id);
            await message.AddReactionAsync(new Emoji(Config.Global.Commands.Attendance.HereEmoji));

            await message.PinAsync();
        }
 public static RaceAnnouncer.Schema.Models.Announcement Convert(
     this Discord.Rest.RestUserMessage message
     , RaceAnnouncer.Schema.Models.Tracker tracker
     , RaceAnnouncer.Schema.Models.Race race
     , RaceAnnouncer.Schema.Models.Channel channel)
 => new Schema.Models.Announcement(
     channel
     , tracker
     , race,
     message.Id);
        public async Task Purge(int amount = 10, [Remainder] string reason = "No reason given")
        {
            SocketGuildUser checkUser = Context.User as SocketGuildUser;

            if (!checkUser.GuildPermissions.KickMembers && !checkUser.GuildPermissions.Administrator) //Make sure user issuing command is admin
            {
                await Context.Channel.SendMessageAsync($"{Context.User.Mention}, you cannot purge messages on this server, this requires the kick permission.");

                return;
            }

            //Make sure the amount is less than 51
            if (amount > 50)
            {
                await Context.Channel.SendMessageAsync($"{Context.User.Mention}, purging amount is limited to 50 due to rate limitations.");

                return;
            }

            if (amount < 1)
            {
                await Context.Channel.SendMessageAsync($"{Context.User.Mention}, please make sure you are purging at least 1 message.");

                return;
            }

            //Include the purge command in the count
            amount += 1;

            try
            {
                IEnumerable <IMessage> allMessages = await this.Context.Channel.GetMessagesAsync(amount).FlattenAsync();

                await(Context.Channel as SocketTextChannel).DeleteMessagesAsync(allMessages);
                Discord.Rest.RestUserMessage message = await Context.Channel.SendMessageAsync($"{Context.User.Mention}, {amount - 1} messages have been purged. Deleting this message in five seconds.");

                System.Timers.Timer timer = new Timer(5000);
                // Hook up the Elapsed event for the timer.
                timer.Elapsed  += (s, e) => (Context.Channel as SocketTextChannel).DeleteMessageAsync(message);
                timer.AutoReset = false;
                timer.Enabled   = true;

                //Channel to send the mod logs in
                await ModLog.PostInModLog(Context.Guild, "Purge", Context.User, null, reason);
            }
            catch (Exception e)
            {
                await Context.Channel.SendMessageAsync($"{Context.User.Mention}, I do not have the \"Manage Messages\" permission.");

                Console.WriteLine(e.Message);
            }
        }
Exemple #7
0
        async Task PreGame()
        {
            var messages = await channel.GetMessagesAsync().FlattenAsync();

            await channel.DeleteMessagesAsync(messages);

            int preGameMinutes = 3;
            int preGameSeconds = 0;

            const string messageContent = "**DM to join bideo gam**";

            message = await channel.SendMessageAsync(messageContent, false, new EmbedBuilder().WithFooter("Created by Jeff and .jpg.\nView our code here: https://github.com/drB-dotjpg/DiscordUnoBot").Build());

            do
            {
                bool twoOrMore = players.Count >= 2;

                string time = twoOrMore ? $"`{preGameMinutes.ToString("00")}:{preGameSeconds.ToString("00")}`" : "`Waiting for two or more players`";

                string playersDisplay = "";
                foreach (Player player in players)
                {
                    playersDisplay += "`" + player.name + "` ";
                }
                playersDisplay = players.Count != 0 ? playersDisplay.Trim() : "`No players`";

                await message.ModifyAsync(x => x.Content = $"{messageContent}\n" +
                                          $"> Time remaining: {time}\n" +
                                          $"> Players: {playersDisplay}");

                if (twoOrMore)
                {
                    preGameSeconds--;
                }
                if (preGameSeconds < 0 && preGameMinutes > 0)
                {
                    preGameMinutes--;
                    preGameSeconds += 59;
                }
                await Task.Delay(1000);
            } while (preGameSeconds > 0 || preGameMinutes > 0);

            foreach (Player player in players)
            {
                for (int i = 0; i < 6; i++)
                {
                    player.Cards.Add(GenerateCard());
                }
            }
            Shuffle(players);
            await InGame();
        }
        private async Task <ulong> LodgeTransactionTask(DataBaseHandlingService db, CommandHandlingService CommandService)
        {
            EmbedFieldBuilder typeField    = new EmbedFieldBuilder().WithIsInline(true).WithName("Type:").WithValue($"Looking to {type} industry");
            EmbedFieldBuilder companyField = new EmbedFieldBuilder().WithIsInline(true).WithName("ID:").WithValue(industryID);
            EmbedFieldBuilder amountField  = new EmbedFieldBuilder().WithIsInline(true).WithName("Type:").WithValue(db.GetFieldAsync(industryID, "type", "industry").ToString());
            EmbedFieldBuilder priceField   = new EmbedFieldBuilder().WithIsInline(true).WithName("Price:").WithValue("$" + price);

            EmbedBuilder emb = new EmbedBuilder().WithTitle("Stock Market Offer").WithDescription($"Use the command `&accept {id.ToString()}` to accept this offer.").WithFooter($"Transaction ID: {id.ToString()}").AddField(typeField).AddField(companyField).AddField(amountField).AddField(priceField).WithColor(Color.Green);

            Discord.Rest.RestUserMessage message = await CommandService.PostEmbedTask((string)await db.GetFieldAsync("MarketChannel", "channel", "system"), emb.Build());

            return(message.Id);
        }
Exemple #9
0
        public async Task SendSearchResponseAsync(SocketCommandContext context, string[] toSend, SearchSession session)
        {
            var msg = new Discord.Rest.RestUserMessage[10];

            for (int index = 0; index < toSend.Length; index++)
            {
                if (toSend[index] != null)
                {
                    msg[index] = await context.Channel.SendMessageAsync(toSend[index]);
                }
            }

            session.Messages = msg;
            await _session.TryAddSession(session);
        }
Exemple #10
0
 public async void AddReactionsAsync(List <string> Reactions, Discord.Rest.RestUserMessage Message)
 {
     foreach (var Reaction in Reactions)
     {
         if (Reaction != "" && Reaction != null)
         {
             if (Reaction.Contains("<:") && Reaction.Contains(":") && Reaction.Contains(">"))
             {
                 await Message.AddReactionAsync(Emote.Parse(Reaction));
             }
             else
             {
                 await Message.AddReactionAsync(new Emoji(Reaction));
             }
         }
     }
 }
Exemple #11
0
        public void HandleChildReaction(TicketChild child, SocketReaction reaction, Discord.Rest.RestUserMessage message)
        {
            var user = reaction.User.Value as SocketGuildUser;

            if (child.State == TicketState.Locked && reaction.UserId == child.UserId)
            {
                if (!user.GuildPermissions.Administrator && !user.Roles.Any(g => TicketManager.GetGuild(child.ParentGuildId).PermittedRoles.Contains(g.Id)))
                {
                    message.RemoveReactionAsync(reaction.Emote, reaction.User.Value);
                    return;
                }
            }

            if (message.Id == child.MainMessageId)
            {
                switch (child.State)
                {
                case TicketState.Open:
                    TicketManager.ChangeChildState(TicketState.Locked, DiscordClient, user, child);
                    break;

                case TicketState.Locked:
                    TicketManager.ChangeChildState(TicketState.Open, DiscordClient, user, child);
                    break;
                }
            }

            else
            {
                switch (reaction.Emote.Name)
                {
                case "⛔":
                    TicketManager.DeleteChild(DiscordClient, child);
                    break;

                case "📑":
                    TicketManager.DeleteChildWithTranscript(DiscordClient, child);
                    break;

                case "🔓":
                    TicketManager.ChangeChildState(TicketState.Open, DiscordClient, user, child);
                    break;
                }
            }
        }
Exemple #12
0
        public static async Task <bool> GetHelp(CommandMessage message, Permissions permissions)
        {
            int   page  = 0;
            Embed embed = GetHelp(message.Guild, permissions, 0, out page);

            Discord.Rest.RestUserMessage helpWindow = await message.Channel.SendMessageAsync(null, false, embed, messageReference : message.MessageReference);

            // Add window to list
            activeHelpEmbeds.Add(helpWindow.Id, new ActiveHelp(message.Author.Id, 0));

            // Add reactions
            await helpWindow.AddReactionsAsync(HelpEmotes.ToArray());

            // Begin the clean up task if it's not already running
            if (activeHelpWindowTask == null || !activeHelpWindowTask.Status.Equals(TaskStatus.Running))
            {
                activeHelpWindowTask = Task.Run(async() => await ClearReactionsAfterDelay(message.Channel));
            }

            return(true);
        }
Exemple #13
0
        /// <summary>
        /// Sends a new admin task
        /// </summary>
        /// <param name="taskTitle">Title of the task</param>
        /// <param name="taskDescription">Further information</param>
        public static async Task <AdminTaskInteractiveMessage> CreateAdminTaskMessage(string taskTitle, string taskDescription)
        {
            if (GuildChannelHelper.TryGetChannel(GuildChannelHelper.AdminNotificationChannelId, out SocketTextChannel channel))
            {
                EmbedBuilder embed = new EmbedBuilder()
                {
                    Title       = taskTitle,
                    Description = taskDescription,
                    Color       = Red,
                    Footer      = Footer
                };
                Discord.Rest.RestUserMessage message = await channel.SendEmbedAsync(embed);

                AdminTaskInteractiveMessage result = new AdminTaskInteractiveMessage(message as IUserMessage, taskTitle);
                await message.AddReactionsAsync(new IEmote[] { UnicodeEmoteService.Checkmark, UnicodeEmoteService.Cross });

                return(result);
            }
            else
            {
                return(null);
            }
        }
Exemple #14
0
        public async Task WhoIs(CommandMessage message, string user)
        {
            // Get guild users by name
            List <IGuildUser> matchedUsers = await UserService.GetUsersByNickName(message.Guild, user);

            if (matchedUsers.Count() == 1)
            {
                User userEntry = await UserService.GetUser(matchedUsers.FirstOrDefault());

                await this.PostWhoIsResponse(message, userEntry);
            }
            else
            {
                Discord.Rest.RestUserMessage response = await message.Channel.SendMessageAsync("I'm sorry, I'm not sure who you mean. Try mentioning them, _kupo!_", messageReference : message.MessageReference);

                // Wait, then delete both messages
                await Task.Delay(2000);

                await message.Channel.DeleteMessageAsync(response.Id);

                await message.Channel.DeleteMessageAsync(message.Id);
            }
        }
Exemple #15
0
            public async Task mySR()
            {
                Discord.Rest.RestUserMessage msg = await Context.Channel.SendMessageAsync("Hold please...");

                Person person = Data.Data.GetUser(Context.User.Id);

                if (person.BattleTag == String.Empty)
                {
                    await msg.ModifyAsync(con => con.Content = "I'm afraid I do not know your battle tag!");
                }
                else
                {
                    Player player = await Utilities.Overwatch.GetPlayer(person.BattleTag);

                    if (player.IsProfilePrivate)
                    {
                        await msg.ModifyAsync(con => con.Content = "Your profile seems to be private. Change it to public and then close the game to use this command.");
                    }
                    else
                    {
                        await msg.ModifyAsync(con => con.Content = "Your SR is: " + player.CompetitiveRank);
                    }
                }
            }
Exemple #16
0
        public async Task ytDownloadVid(string videoURL, string filetype = "mp3")
        {
            DateTime timerStart = DateTime.Now;
            var      embed      = new EmbedBuilder()
                                  .WithThumbnailUrl(config["icons:loading_url"])
                                  .WithTitle(config["strings:start_get_video"])
                                  .WithColor(Color.Blue);

            var loadingMessage = await Context.Channel.SendMessageAsync(embed : embed.Build());

            Uri videoURI = new Uri(videoURL, UriKind.Absolute);
            var id       = YoutubeClient.ParseVideoId(videoURI.ToString());
            // TODO: Add proper URI error handling.
            //if (videoURI.Host != )
            //    throw new ArgumentException("Address provided is not a YouTube URI.");
            var ytClient   = new YoutubeClient();
            var ytMetadata = await ytClient.GetVideoAsync(id);

            if (ytMetadata.Duration > new TimeSpan(1, 0, 0))
            {
                embed.WithColor(Color.Red)
                .WithThumbnailUrl(config["icons:error_url"])
                .WithTitle(config["strings:max_duration_exceeded_title"])
                .WithDescription(config["strings:max_duration_exceeded_desc"]);
                await loadingMessage.ModifyAsync(msg => msg.Embed = embed.Build());

                return;
            }

            var ytStreamMetadataSet = await ytClient.GetVideoMediaStreamInfosAsync(id);

            var ytStreamMetadata = ytStreamMetadataSet.Audio.WithHighestBitrate();

            var ytStreamTask = ytClient.GetMediaStreamAsync(ytStreamMetadata);
            var ytStream     = await ytStreamTask;

            if (config.GetValue <bool>("debug", false))
            {
                if (ytStreamTask.IsCompletedSuccessfully)
                {
                    Console.WriteLine($"Successfully got stream data for video id \"{ytMetadata.Id}\"");
                }
                else
                {
                    Console.WriteLine($"Failed to get stream data for video id \"{ytMetadata.Id}\"");
                }
            }

            var encodedStream = new MemoryStream();

            using (Process ffmpeg = new Process
            {
                StartInfo =
                {
                    FileName               = config["ffmpeg_location"],
                    Arguments              = $"-i - -f {filetype} pipe:1",
                    RedirectStandardInput  = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    UseShellExecute        = false,
                    CreateNoWindow         = true,
                },
                EnableRaisingEvents = true
            })
            {
                Exception ffmpegException = null;

                if (config.GetValue <bool>("debug", false))
                {
                    ffmpeg.ErrorDataReceived += (sender, eventArgs) => Console.WriteLine(eventArgs.Data);
                }

                ffmpeg.Start();
                ffmpeg.BeginErrorReadLine();
                var inputTask = Task.Run(() =>
                {
                    try
                    {
                        ytStream.CopyTo(ffmpeg.StandardInput.BaseStream);
                        ffmpeg.StandardInput.Close();
                    }
                    catch (IOException e)
                    {
                        ffmpegException = e;
                    }
                });
                var outputTask = ffmpeg.StandardOutput.BaseStream.CopyToAsync(encodedStream);

                Task.WaitAll(inputTask, outputTask);
                if (ffmpegException != null)
                {
                    embed.WithColor(Color.Red)
                    .WithThumbnailUrl(config["icons:error_url"])
                    .WithTitle(config["strings:ffmpeg_exception_title"])
                    .WithDescription(config["strings:ffmpeg_exception_description"])
                    .WithFields(
                        new EmbedFieldBuilder()
                        .WithName("*Stack Traceback:*")
                        .WithValue(Format.Sanitize(ffmpegException.StackTrace))
                        .WithIsInline(false)
                        );
                    await loadingMessage.ModifyAsync(msg => msg.Embed = embed.Build());

                    return;
                }

                ffmpeg.WaitForExit();

                //var fileExt = MimeGuesser.GuessExtension(encodedStream);
            }

            Discord.Rest.RestUserMessage finishedMessage = null;

            if (encodedStream.Length < 0x800000)
            {
                if (config.GetValue <bool>("debug", false))
                {
                    Console.WriteLine("Uploading transcoded file to Discord.");
                }
                encodedStream.Position = 0;
                finishedMessage        = await Context.Channel.SendFileAsync(
                    encodedStream, $"{ytMetadata.Title}.{filetype}",
                    embed : buildYtEmbed(ytMetadata)
                    );
            }
            else
            {
                if (config.GetValue <bool>("debug", false))
                {
                    Console.WriteLine("Uploading transcoded file to alternate host.");
                }
                embed.WithTitle(config["strings:file_too_large_title"])
                .WithDescription(config["strings:file_too_large_description"]);
                await loadingMessage.ModifyAsync(msg => msg.Embed = embed.Build());

                var newName = String.Join(
                    "_",
                    ytMetadata.Title.Split(Path.GetInvalidFileNameChars(),
                                           StringSplitOptions.RemoveEmptyEntries)
                    ).TrimEnd('.');

                using (HttpClient client = new HttpClient {
                    BaseAddress = new Uri(config["http_put_url"])
                })
                {
                    using (var response = client.PutAsync($"{newName}.{filetype}", new StreamContent(encodedStream)))
                    {
                        /*
                         * DateTime lastUpdate = DateTime.Now;
                         * while (response.Status == TaskStatus.Running)
                         * {
                         *  if (DateTime.Now.Subtract(lastUpdate).TotalSeconds > 3)
                         *  {
                         *      await loadingMessage.ModifyAsync(
                         *          msg => msg.Content = $"Uploading to an alternate host...\nPlease allow time for this to finish.\n{}% uploaded..."
                         *          );
                         *      lastUpdate = DateTime.Now;
                         *  }
                         * }
                         */

                        if (response.Result.IsSuccessStatusCode)
                        {
                            finishedMessage = await Context.Channel.SendMessageAsync(
                                embed : buildYtEmbed(
                                    ytMetadata,
                                    new EmbedFieldBuilder()
                                    .WithName(config["strings:external_download_title"])
                                    .WithValue(String.Format(config["strings:external_download_description"], await response.Result.Content.ReadAsStringAsync()))
                                    )
                                );
                        }
                    }
                }
            }

            embed.WithColor(Color.Green)
            .WithThumbnailUrl(config["icons:success_url"])
            .WithTitle(config["strings:finished_message_description"])
            .WithDescription(
                $"[{config["strings:finished_message_link"]}](https://discordapp.com/channels/{Context.Guild.Id}/{Context.Channel.Id}/{finishedMessage.Id})"
                );

            if (config.GetValue <bool>("debug", false))
            {
                Console.WriteLine($"Successfully handled video id \"{ytMetadata.Id}\" in {DateTime.Now.Subtract(timerStart).Seconds} seconds.");
            }

            await loadingMessage.ModifyAsync(msg => msg.Embed = embed.Build());

            Task.WaitAll(ytStream.DisposeAsync().AsTask(), encodedStream.DisposeAsync().AsTask());
        }
Exemple #17
0
        private async Task <string> ChInfo([Remainder] string text, Discord.Rest.RestUserMessage msg)
        {
            List <ch_info> ch     = new List <ch_info>();
            var            info   = new ch_info();
            var            client = new WebClient();

            string pageSourceCode = client.DownloadString(string.Format("https://gbf.wiki/index.php?title=Special:Search&profile=default&fulltext=Search&search={0}", text));

            System.Text.RegularExpressions.MatchCollection mc = System.Text.RegularExpressions.Regex.Matches(pageSourceCode, "<div class=(.*?)><a href=\"(.*?)\" title=\"(.*?)\" data-serp-pos=\"(.*?)\">");
            if (mc.Count > 0)
            {
                foreach (System.Text.RegularExpressions.Match match in mc)
                {
                    info.name = match.Groups[3].Value;
                    info.page = match.Groups[2].Value;
                    ch.Add(info);
                }
            }
            else
            {
                return("f");
            }

            int index;

            if (ch.Count > 1 && ch != null)
            {
                var eb = new EmbedBuilder()
                {
                    Color = new Color(4, 97, 247),
                    Title = "Enter the index of character u wanna see.",
                };
                string vids  = "";
                int    count = 1;
                foreach (var v in ch)
                {
                    vids += $"**{count}.** {v.name}\n";
                    count++;
                }
                eb.Description = vids;
                var del = await Context.Channel.SendMessageAsync("", false, eb.Build());

                var response = await _interactive.WaitForMessage(Context.User, Context.Channel, TimeSpan.FromSeconds(20));

                await del.DeleteAsync();

                if (response == null)
                {
                    await msg.ModifyAsync(x =>
                    {
                        x.Content = $":no_entry_sign: Answer timed out {Context.User.Mention} (≧д≦ヾ)";
                    });

                    return("f2");
                }
                if (!Int32.TryParse(response.Content, out index))
                {
                    await msg.ModifyAsync(x =>
                    {
                        x.Content = $":no_entry_sign: Only add the Index";
                    });

                    return("f2");
                }
                if (index > (ch.Count) || index < 1)
                {
                    await msg.ModifyAsync(x =>
                    {
                        x.Content = $":no_entry_sign: Invalid Number";
                    });

                    return("f2");
                }
            }
            else
            {
                index = 1;
            }
            return($"https://gbf.wiki" + ch[index - 1].page);
        }
Exemple #18
0
        public async Task <string> GetYtURLAsync(SocketCommandContext Context, string name, InteractiveService interactive, Discord.Rest.RestUserMessage msg)
        {
            // this.GetType().ToString()
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey          = "AIzaSyCBXGF_M-o0HYYPYTh8LZWCPGAZfp97j4o",
                ApplicationName = "SoraBot"
            });

            var searchListRequest = youtubeService.Search.List("snippet");
            var search            = System.Net.WebUtility.UrlEncode(name);

            searchListRequest.Q          = search;
            searchListRequest.MaxResults = 10;

            var searchListResponse = await searchListRequest.ExecuteAsync();

            List <string> videos = new List <string>();
            List <Google.Apis.YouTube.v3.Data.SearchResult> videosR = new List <Google.Apis.YouTube.v3.Data.SearchResult>();

            foreach (var searchResult in searchListResponse.Items)
            {
                switch (searchResult.Id.Kind)
                {
                case "youtube#video":
                {
                    videos.Add(String.Format("{0}", searchResult.Snippet.Title));
                    videosR.Add(searchResult);
                    break;
                }
                }
            }
            int indexx = 0;

            if (videos.Count > 1)
            {
                var eb = new EmbedBuilder()
                {
                    Color = new Color(4, 97, 247),
                    Title = "Enter the Index of the YT video you want to add."
                };
                string vids  = "";
                int    count = 1;
                foreach (var v in videos)
                {
                    vids  += "**{count}.** {v}" + Constants.vbLf;
                    count += 1;
                }
                eb.Description = vids;
                var del = await Context.Channel.SendMessageAsync("", embed : eb);

                await del.DeleteAsync();

                if (indexx > (videos.Count) || indexx < 1)
                {
                    await msg.ModifyAsync(x =>
                    {
                        x.Content = ":no_entry_sign: Invalid Number";
                    });

                    return("f2");
                }
            }
            else
            {
                indexx = 1;
            }
            // await Context.Channel.SendMessageAsync(String.Format("Videos: \n{0}\n", String.Join("\n", videos)));

            return("https://www.youtube.com/watch?v={videosR[index-1].Id.VideoId}");
        }
Exemple #19
0
        public async Task <string> GetYtURL(SocketCommandContext Context, string name, InteractiveService interactive, Discord.Rest.RestUserMessage msg)
        {
            try
            {
                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    ApiKey          = ytApiKey,
                    ApplicationName = "RankoKanzaki"
                });

                List <string> videos = new List <string>();

                int i     = 1;
                var items = new VideoSearch();

                List <string> urls = new List <string>();
                foreach (var item in items.SearchQuery(name, 1))
                {
                    byte[] bytes = System.Text.Encoding.Default.GetBytes(item.Title);
                    string value = System.Text.Encoding.UTF8.GetString(bytes);

                    videos.Add(string.Format("{0})", value));
                    urls.Add(string.Format("{0})", item.Url));

                    i++;
                }
                int index;
                if (videos.Count > 1)
                {
                    var eb = new EmbedBuilder()
                    {
                        Color = new Color(4, 97, 247),
                        Title = "Enter the Index of the YT video you want to add.",
                    };
                    string vids  = "";
                    int    count = 1;
                    foreach (var v in videos)
                    {
                        vids += $"**{count}.** {v}\n";
                        count++;
                    }
                    eb.Description = vids;
                    var del = await Context.Channel.SendMessageAsync("", false, eb.Build());

                    var response = await interactive.WaitForMessage(Context.User, Context.Channel, TimeSpan.FromSeconds(20));

                    await del.DeleteAsync();

                    if (response == null)
                    {
                        await msg.ModifyAsync(x =>
                        {
                            x.Content = $":no_entry_sign: Answer timed out {Context.User.Mention} (≧д≦ヾ)";
                        });

                        return("f2");
                    }
                    if (!Int32.TryParse(response.Content, out index))
                    {
                        await msg.ModifyAsync(x =>
                        {
                            x.Content = $":no_entry_sign: Only add the Index";
                        });

                        return("f2");
                    }
                    if (index > (videos.Count) || index < 1)
                    {
                        await msg.ModifyAsync(x =>
                        {
                            x.Content = $":no_entry_sign: Invalid Number";
                        });

                        return("f2");
                    }
                }
                else
                {
                    index = 1;
                }
                return(urls[index - 1]);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            return("f");
        }
 static async Task QueueDelete(AbbybotCommandArgs aca, int autoDeleteTime, Discord.Rest.RestUserMessage abbybotMessage)
 {
     await aca.Send(abbybotMessage, aca.originalMessage, RequestType.Delete, DateTime.Now.AddSeconds(autoDeleteTime));
 }
Exemple #21
0
        private async Task <string> AniInfo([Remainder] string text, Discord.Rest.RestUserMessage msg, AnilistType type)
        {
            var client          = new GraphQLClient("https://graphql.anilist.co");
            List <animeinfo> ch = new List <animeinfo>();
            var    info         = new animeinfo();
            string stype        = "";

            if (type == AnilistType.ANIME)
            {
                stype = "ANIME";
            }
            else
            {
                stype = "MANGA";
            }
            var request = new GraphQLRequest
            {
                Query     = @"
query($id: Int, $page: Int, $perPage: Int, $search: String) {
                    Page(page: $page, perPage: $perPage) {
                        pageInfo {
                          total
                          currentPage
                          lastPage
                          hasNextPage
                          perPage
                        }
                        media(type: " + stype + @", id: $id, search: $search, isAdult: false) {
                            id
                            title {
                                romaji
                            }
                            siteUrl 
                        }
                    }
                }
",
                Variables = new
                {
                    search  = text,
                    page    = 1,
                    perPage = 20
                }
            };

            var response = await client.PostAsync(request);

            if (response.Data.Page.pageInfo.total.ToObject <int>() > 0)
            {
                if (response.Data.Page.pageInfo.total.ToObject <int>() > response.Data.Page.pageInfo.perPage.ToObject <int>())
                {
                    for (int i = 0; i < 20; i++)
                    {
                        info.id      = response.Data.Page.media[i].id;
                        info.romaji  = response.Data.Page.media[i].title.romaji;
                        info.siteURL = response.Data.Page.media[i].siteUrl;
                        ch.Add(info);
                    }
                }
                else
                {
                    for (int i = 0; i < response.Data.Page.pageInfo.total.ToObject <int>(); i++)
                    {
                        info.id      = response.Data.Page.media[i].id;
                        info.romaji  = response.Data.Page.media[i].title.romaji;
                        info.siteURL = response.Data.Page.media[i].siteUrl;
                        ch.Add(info);
                    }
                }
            }
            else
            {
                return("f");
            }

            int index;

            if (ch.Count > 1 && ch != null)
            {
                var eb = new EmbedBuilder()
                {
                    Color = new Color(4, 97, 247),
                    Title = "Enter the index of character u wanna see.",
                };
                string vids  = "";
                int    count = 1;
                foreach (var v in ch)
                {
                    vids += $"**{count}.** {v.romaji}\n";
                    count++;
                }
                eb.Description = vids;
                var del = await Context.Channel.SendMessageAsync("", false, eb.Build());

                var response2 = await _interactive.WaitForMessage(Context.User, Context.Channel, TimeSpan.FromSeconds(20));

                await del.DeleteAsync();

                if (response2 == null)
                {
                    await msg.ModifyAsync(x =>
                    {
                        x.Content = $":no_entry_sign: Answer timed out {Context.User.Mention} (≧д≦ヾ)";
                    });

                    return("f2");
                }
                if (!Int32.TryParse(response2.Content, out index))
                {
                    await msg.ModifyAsync(x =>
                    {
                        x.Content = $":no_entry_sign: Only add the Index";
                    });

                    return("f2");
                }
                if (index > (ch.Count) || index < 1)
                {
                    await msg.ModifyAsync(x =>
                    {
                        x.Content = $":no_entry_sign: Invalid Number";
                    });

                    return("f2");
                }
            }
            else
            {
                index = 1;
            }
            return(ch[index - 1].siteURL);
        }
Exemple #22
0
        public override async Task OnExecuteFromDiscord(SocketGuild guild, SocketUser user, SocketTextChannel channel, SocketMessage messageobject, string fullmessage, string arguments_string, List <string> arguments)
        {
            int           page  = 0;
            List <string> pages = new List <string>();

            Emoji em1 = new Emoji("\u23EE");
            Emoji em2 = new Emoji("\u23ED");

            String             currentPage = "```A list of known command categories:";
            List <CmdCategory> categories  = new List <CmdCategory>();

            foreach (CmdCategory cat in Bot.GetBot().CmdCategories)
            {
                if (arguments.Count != 0)
                {
                    if (cat.name.ToLower() != arguments[0].ToLower())
                    {
                        continue;
                    }
                }
                if (!categories.Contains(cat))
                {
                    categories.Add(cat);
                }
            }
            foreach (CmdCategory cat in Bot.GetBot().CmdCategories)
            {
                if (arguments.Count != 0)
                {
                    if (!cat.name.ToLower().StartsWith(arguments[0].ToLower()))
                    {
                        continue;
                    }
                }
                if (!categories.Contains(cat))
                {
                    categories.Add(cat);
                }
            }
            foreach (CmdCategory cat in Bot.GetBot().CmdCategories)
            {
                if (arguments.Count != 0)
                {
                    if (!cat.name.ToLower().Contains(arguments[0].ToLower()))
                    {
                        continue;
                    }
                }
                if (!categories.Contains(cat))
                {
                    categories.Add(cat);
                }
            }
            foreach (CmdCategory cat in Bot.GetBot().CmdCategories)
            {
                if (arguments.Count != 0)
                {
                    if (!cat.description.ToLower().StartsWith(arguments[0].ToLower()))
                    {
                        continue;
                    }
                }
                if (!categories.Contains(cat))
                {
                    categories.Add(cat);
                }
            }
            foreach (CmdCategory cat in Bot.GetBot().CmdCategories)
            {
                if (arguments.Count != 0)
                {
                    if (!cat.description.ToLower().Contains(arguments[0].ToLower()))
                    {
                        continue;
                    }
                }
                if (!categories.Contains(cat))
                {
                    categories.Add(cat);
                }
            }

            foreach (CmdCategory cat in categories)
            {
                if (currentPage.Length + 3 >= 2000)
                {
                    currentPage += "```";
                    pages.Add(currentPage);
                    currentPage = "```A list of known command categories (page " + pages.Count + "):";
                }
                currentPage += ("\n - " + cat.name + " - " + cat.description);
            }
            if (currentPage.Length != ("```A list of known command categories (page " + pages.Count + "):").Length)
            {
                currentPage += "```";
                pages.Add(currentPage);
            }

            Discord.Rest.RestUserMessage message = await channel.SendMessageAsync(pages[page]);

            Func <Cacheable <IUserMessage, ulong>, ISocketMessageChannel, SocketReaction, Task> handler = new Func <Cacheable <IUserMessage, ulong>, ISocketMessageChannel, SocketReaction, Task>((arg1, arg2, arg3) =>
            {
                if (arg3.MessageId == message.Id && arg3.Channel.Id == message.Channel.Id)
                {
                    if (arg3.Emote.Name == em1.Name)
                    {
                        bool changed = false;
                        var v        = message.GetReactionUsersAsync(em1, int.MaxValue).GetAsyncEnumerator();
                        while (true)
                        {
                            if (v.Current != null)
                            {
                                foreach (IUser usr in v.Current)
                                {
                                    if (!usr.Id.Equals(Bot.GetBot().client.CurrentUser.Id))
                                    {
                                        message.RemoveReactionAsync(em1, usr).GetAwaiter().GetResult();
                                        changed = true;
                                    }
                                }
                            }
                            if (!v.MoveNextAsync().GetAwaiter().GetResult())
                            {
                                break;
                            }
                        }
                        if (changed)
                        {
                            page--;

                            var oldmsg = message;
                            message    = channel.SendMessageAsync(pages[page]).GetAwaiter().GetResult();
                            oldmsg.DeleteAsync().GetAwaiter().GetResult();

                            if (page != 0)
                            {
                                message.AddReactionAsync(em1).GetAwaiter().GetResult();
                            }
                            if (page != pages.Count - 1)
                            {
                                message.AddReactionAsync(em2).GetAwaiter().GetResult();
                            }
                        }
                    }
                    if (arg3.Emote.Name == em2.Name)
                    {
                        bool changed = false;
                        var v        = message.GetReactionUsersAsync(em2, int.MaxValue).GetAsyncEnumerator();
                        while (true)
                        {
                            if (v.Current != null)
                            {
                                foreach (IUser usr in v.Current)
                                {
                                    if (!usr.Id.Equals(Bot.GetBot().client.CurrentUser.Id))
                                    {
                                        message.RemoveReactionAsync(em1, usr).GetAwaiter().GetResult();
                                        changed = true;
                                    }
                                }
                            }
                            if (!v.MoveNextAsync().GetAwaiter().GetResult())
                            {
                                break;
                            }
                        }
                        if (changed)
                        {
                            page++;

                            var oldmsg = message;
                            message    = channel.SendMessageAsync(pages[page]).GetAwaiter().GetResult();
                            oldmsg.DeleteAsync().GetAwaiter().GetResult();

                            if (page != 0)
                            {
                                message.AddReactionAsync(em1).GetAwaiter().GetResult();
                            }
                            if (page != pages.Count - 1)
                            {
                                message.AddReactionAsync(em2).GetAwaiter().GetResult();
                            }
                        }
                    }
                }
                return(null);
            });

            Bot.GetBot().client.ReactionAdded += handler;
            Bot.GetBot().client.MessageDeleted += (arg11, arg22) =>
            {
                if (arg11.Id == message.Id)
                {
                    Bot.GetBot().client.ReactionAdded -= handler;
                }
                return(null);
            };

            if (pages.Count != 1)
            {
                if (page != pages.Count)
                {
                    await message.AddReactionAsync(em2);
                }
            }
        }
Exemple #23
0
        public async Task FlipAsync([Remainder] string input)
        {
            int    delay    = 15;
            string emote    = null;
            int    bet      = 0;
            string side     = null;
            var    userInfo = (IGuildUser)Context.User;
            string userName = null;

            Discord.Rest.RestUserMessage mainMessage = null;
            Embed embedBuilt = null;

            if (userInfo.Nickname != null)
            {
                userName = userInfo.Nickname;
            }
            else
            {
                userName = Context.User.Username;
            }

            var footer = new EmbedFooterBuilder
            {
                Text = "Cody by Ayla / Alsekwolf#0001"
            };
            var author = new EmbedAuthorBuilder
            {
                IconUrl = Context.User.GetAvatarUrl(),
                Name    = $"{userName} entered a game of coin flip."
            };
            var embed = new EmbedBuilder
            {
                Author    = author,
                Color     = Color.Magenta,
                Footer    = footer,
                Timestamp = DateTimeOffset.Now
            };

            if (!Services.CommandDelay.IncomingRequest(Context.User.Id.ToString(), delay))
            {
                string activeUser = _activeUsers.FirstOrDefault(s => s == Context.User.Id.ToString());
                if (activeUser == null)
                {
                    _activeUsers.Add(Context.User.Id.ToString());
                }
                if (activeUser != null)
                {
                    await Context.Message.DeleteAsync();

                    return;
                }

                embed.WithDescription(
                    $"please wait longer between *investing*. \nYour bet will be sent when the delay is up. \nReact with the stop emote to cancel.");
                embedBuilt  = embed.Build();
                mainMessage = await Context.Channel.SendMessageAsync(embed : embedBuilt);

                if (Emote.TryParse(StopEmote, out var stopEmoteParsed))
                {
                    await mainMessage.AddReactionAsync(stopEmoteParsed);
                }

                Services.CommandDelay.User tempUser = Services.CommandDelay.Users.FirstOrDefault(User => User.Username == Context.User.Id.ToString());
                try
                {
                    while ((DateTime.Now - tempUser.LastRequest).TotalSeconds <= delay)
                    {
                        await Task.Delay(1000);
                    }

                    int count = 0;
                    foreach (string y in _activeUsers.FindAll(x => x == Context.User.Id.ToString()))  // returns the value of all hits}
                    {
                        _activeUsers.Remove(y);
                        count++;
                    }

                    var userList = await mainMessage.GetReactionUsersAsync(stopEmoteParsed, int.MaxValue).FlattenAsync();

                    if (userList.Any(u => u.Id == Context.User.Id))
                    {
                        return;
                    }
                    await mainMessage.RemoveAllReactionsAsync();
                }
                catch (Exception e)
                {
                    Console.WriteLine("DelayCommand error: " + e.Message);
                    throw;
                }
            }

            var SQL      = new SQLFunctions.Main();
            var userData = SQL.LoadUserData(Context.User);

            if (input.ContainsAny(" "))
            {
                var splitInput = input.Split(' ');
                if (splitInput[0].All(char.IsDigit))
                {
                    bet  = Int32.Parse(splitInput[0]);
                    side = splitInput[1];
                }
                if (splitInput[1].All(char.IsDigit))
                {
                    bet  = Int32.Parse(splitInput[1]);
                    side = splitInput[0];
                }
                if (splitInput[0].ContainsAny("all"))
                {
                    bet  = userData.cash;
                    side = splitInput[1];
                }
                if (splitInput[1].ContainsAny("all"))
                {
                    bet  = userData.cash;
                    side = splitInput[0];
                }
                if (side.ContainsAny("head", "heads", "h"))
                {
                    side = "heads";
                }
                if (side.ContainsAny("tail", "tailss", "t"))
                {
                    side = "tails";
                }
            }
            else
            {
                if (input.All(char.IsDigit))
                {
                    bet  = Int32.Parse(input);
                    side = "heads";
                }

                if (input.ContainsAny("all"))
                {
                    bet  = userData.cash;
                    side = "heads";
                }
            }

            if (bet == 0)
            {
                embed.WithDescription($"You can't bet 0, that's not how this works!!'");
                embedBuilt = embed.Build();

                if (mainMessage != null)
                {
                    await mainMessage.ModifyAsync(msg => msg.Embed = embedBuilt);
                }
                else
                {
                    await Context.Channel.SendMessageAsync(embed : embedBuilt);
                }
                return;
            }
            if (side == null)
            {
                embed.WithDescription($"something went wrong, please try again.");
                embedBuilt = embed.Build();

                if (mainMessage != null)
                {
                    await mainMessage.ModifyAsync(msg => msg.Embed = embedBuilt);
                }
                else
                {
                    await Context.Channel.SendMessageAsync(embed : embedBuilt);
                }
                return;
            }

            if (userData.cash >= bet)
            {
                embed.WithAuthor($"{userName} spent ${bet} and chose {side}", Context.User.GetAvatarUrl());
                embed.WithDescription($"The coin spins.... {FlipEmote}");
                embedBuilt = embed.Build();

                if (mainMessage != null)
                {
                    await mainMessage.ModifyAsync(msg => msg.Embed = embedBuilt);
                }
                else
                {
                    mainMessage = await Context.Channel.SendMessageAsync(embed : embedBuilt);
                }

                await Task.Delay(2250);

                int randomNumber = RandomNumber.Between(0, 100);
                if (randomNumber > 50)
                {
                    if (side == "heads")
                    {
                        emote = TailsEmote;
                    }
                    else
                    {
                        emote = HeadsEmote;
                    }

                    embed.WithDescription($"The coin spins.... {emote} and **{userName}** lost it all... :c");
                    embedBuilt = embed.Build();

                    await mainMessage.ModifyAsync(msg => msg.Embed = embedBuilt);

                    userData.cash = userData.cash - bet;
                    SQL.SaveUserData(Context.User, userData);
                }

                if (randomNumber < 50)
                {
                    if (side == "heads")
                    {
                        emote = HeadsEmote;
                    }
                    else
                    {
                        emote = TailsEmote;
                    }
                    embed.WithDescription($"The coin spins.... {emote} and **{userName}** won **${bet}** c:");
                    embedBuilt = embed.Build();

                    await mainMessage.ModifyAsync(msg => msg.Embed = embedBuilt);

                    userData.cash = userData.cash + bet;
                    SQL.SaveUserData(Context.User, userData);
                }
            }
            else
            {
                embed.WithDescription($"you probably don't have enough cash. \nYou currently have **${userData.cash}**");
                embedBuilt = embed.Build();

                if (mainMessage != null)
                {
                    await mainMessage.ModifyAsync(msg => msg.Embed = embedBuilt);
                }
                else
                {
                    await Context.Channel.SendMessageAsync(embed : embedBuilt);
                }
            }
        }
Exemple #24
0
        public async Task Blackjack([Remainder] string Input = null)
        {
            SocketUser contUser = Context.User;
            UserData   ud       = ExtensionMethods.FindPerson(contUser.Id);

            if (Input == null)
            {
                await Context.Channel.SendMessageAsync(string.Concat("You forgot to place a bet! Bet some pudding will ya? Minimum bet is 10. Maximum bet is (25 + amount of cards owned (from the nepbot card collection game!)) * your non-RP level which for you is: ", _math.TotalBet(ud.NonLevel, ud).ToString()));

                return;
            }

            if (Input.ToLower() == "help")
            {
                EmbedBuilder eb = new EmbedBuilder();
                eb.AddField("Play Blackjack", "enter the amount you wish to bet after blackjack. The maximum amount you can bet is (25 + amount of cards owned (from the nepbot card collection game!)) * your ooc chat level!");
                eb.AddField("Hit", "Draw a card.");
                eb.AddField("Stand", "Finish your turn with the cards you already have.");
                await Context.Channel.SendMessageAsync("", false, eb.Build());

                //await Context.Channel.SendMessageAsync(string.Concat("Type !nep play blackjack (bet amt). Type !nep hit to draw a card and !nep stand to not draw a card. You win double your bet amt! Max bet amount is 25 * your non-RP chat level! If you bet higher than your maximum it will automatically adjust to your max.", "Maximum bet is 25 * your non - RP level which for you is: ", _math.TotalBet(ud.NonLevel).ToString()));
                return;
            }
            BlackjackGame gameChecker  = null;
            int           listLocation = 0;

            foreach (BlackjackGame b in bjg)
            {
                if (Context.User.Id == b._playerID)
                {
                    gameChecker = b;
                    break;
                }
                listLocation++;
            }
            if (gameChecker != null)
            {
                await Context.Channel.SendMessageAsync("You're already playing blackjack! One game at a time folks! ~nepu");

                return;
            }
            try
            {
                if (ulong.Parse(Input) < 10)
                {
                    await Context.Channel.SendMessageAsync("10 puddings is the minimum bet! Please bet a minimum of 10 puddings before I eat them all!");

                    return;
                }
            }
            catch (Exception)
            {
            }
            ulong betAmt = ulong.Parse(Input);

            if (!_math.CanBet(betAmt, ud.Pudding) || betAmt > _math.TotalBet(ud.NonLevel, ud))
            {
                await Context.Channel.SendMessageAsync(string.Concat("Aww you only have ", ud.Pudding.ToString(), ". Minimum bet is 10. Maximum bet is (25 + amount of cards owned (from the nepbot card collection game!)) * your non-RP level which is: ", _math.TotalBet(ud.NonLevel, ud).ToString()));

                return;
            }

            GraphicsMethods gm    = new GraphicsMethods();
            BlackjackGame   agame = new BlackjackGame(Context.User.Id, betAmt);

            if (agame.DealerBlackjack)
            {
                EndBlackjack(Context.User.Id, agame.TotalBet, false);
                await Context.Channel.SendFileAsync(gm.CardLayout(agame._playerHand, agame._dealerHand, Context.User.Username), string.Concat("[Dealer:] ", agame.DealerTotal, " [Player:] ", agame.PlayerTotal, " [Bet Amt:] ", agame.TotalBet));

                await Context.Channel.SendMessageAsync(string.Concat($"{ExtensionMethods.NeptuneEmojis(true)} Yay I won!! Ahem suck to be you! Your {agame.TotalBet} belongs to me now! You have ", ud.Pudding, " pudding left!"));

                return;
            }
            bjg.Add(agame);
            Discord.Rest.RestUserMessage k = await Context.Channel.SendFileAsync(gm.CardLayout(agame._playerHand, agame._dealerHand, Context.User.Username), string.Concat("[Neptune's Hand:] ", agame.DealerTotal, " [Player:] ", agame.PlayerTotal, " [Bet Amt:] ", agame.TotalBet));

            agame.HandMsg = k;
        }
Exemple #25
0
        public void HandleSetupMessage(GuildEngine guildE, SetupMessage setupMessage, SocketReaction reaction, Discord.Rest.RestUserMessage message)
        {
            var user   = reaction.User.Value as SocketGuildUser;
            var ticket = GetTicket(guildE.Id, setupMessage.TicketId);

            if (ticket == null)
            {
                return;
            }

            message.RemoveReactionAsync(reaction.Emote, user);

            if (ticket.ActiveChildChannels.Values.Any(x => x.UserId == user.Id))
            {
                return;
            }

            TicketManager.CreateNewChild(DiscordClient, user, ticket);
        }
Exemple #26
0
        public async Task <string> GetYtURL(SocketCommandContext Context, string name, InteractiveService interactive, Discord.Rest.RestUserMessage msg)
        {
            try
            {
                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    ApiKey          = ytApiKey,
                    ApplicationName = "SoraBot" //this.GetType().ToString()
                });

                var searchListRequest = youtubeService.Search.List("snippet");
                var search            = System.Net.WebUtility.UrlEncode(name);
                searchListRequest.Q          = search;
                searchListRequest.MaxResults = 10;

                var searchListResponse = await searchListRequest.ExecuteAsync();

                List <string> videos = new List <string>();
                List <Google.Apis.YouTube.v3.Data.SearchResult> videosR = new List <Google.Apis.YouTube.v3.Data.SearchResult>();

                foreach (var searchResult in searchListResponse.Items)
                {
                    switch (searchResult.Id.Kind)
                    {
                    case "youtube#video":
                        videos.Add(String.Format("{0}", searchResult.Snippet.Title));
                        videosR.Add(searchResult);
                        break;
                    }
                }
                int index;
                if (videos.Count > 1)
                {
                    var eb = new EmbedBuilder()
                    {
                        Color = new Color(4, 97, 247),
                        Title = "Enter the Index of the YT video you want to add.",
                    };
                    string vids  = "";
                    int    count = 1;
                    foreach (var v in videos)
                    {
                        vids += $"**{count}.** {v}\n";
                        count++;
                    }
                    eb.Description = vids;
                    var del = await Context.Channel.SendMessageAsync("", embed : eb);

                    var response = await interactive.WaitForMessage(Context.User, Context.Channel, TimeSpan.FromSeconds(20));

                    await del.DeleteAsync();

                    if (response == null)
                    {
                        await msg.ModifyAsync(x =>
                        {
                            x.Content = $":no_entry_sign: Answer timed out {Context.User.Mention} (≧д≦ヾ)";
                        });

                        return("f2");
                    }
                    if (!Int32.TryParse(response.Content, out index))
                    {
                        await msg.ModifyAsync(x =>
                        {
                            x.Content = $":no_entry_sign: Only add the Index";
                        });

                        return("f2");
                    }
                    if (index > (videos.Count) || index < 1)
                    {
                        await msg.ModifyAsync(x =>
                        {
                            x.Content = $":no_entry_sign: Invalid Number";
                        });

                        return("f2");
                    }
                }
                else
                {
                    index = 1;
                }
                return($"https://www.youtube.com/watch?v={videosR[index-1].Id.VideoId}");
                //await Context.Channel.SendMessageAsync(String.Format("Videos: \n{0}\n", String.Join("\n", videos)));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                await SentryService.SendError(e, Context);
            }
            return("f");
        }
Exemple #27
0
        public async Task <EmbedBuilder> EvaluateAsync(ShardedCommandContext context, string code)
        {
            Discord.Rest.RestUserMessage msg = await context.Channel.SendMessageAsync("Working...");

            code = code.Replace("“", "\"").Replace("‘", "\'").Replace("”", "\"").Replace("’", "\'").Trim('`');
            if (code.Length > 2 && code.Substring(0, 2) == "cs")
            {
                code = code.Substring(2);
            }

            IEnumerable <Assembly> assemblies = GetAssemblies();

            var sb = new StringBuilder();

            var globals = new Globals
            {
                _client   = _client,
                _context  = context,
                _guild    = context.Guild,
                _channel  = context.Channel,
                _user     = context.User as SocketGuildUser,
                _services = _services,
                _message  = context.Message,
                Console   = new FakeConsole(sb),
                _db       = _services.GetService <DbService>(),
                _misc     = this,
                _audio    = _services.GetService <AudioService>(),
                Random    = _random,
                _img      = _services.GetService <ImageService>(),
                _ms       = _services.GetService <MusicService>(),
                _commands = _services.GetService <CommandService>()
            };
            var options = ScriptOptions.Default
                          .AddReferences(assemblies)
                          .AddImports(globals.Imports)
                          .WithAllowUnsafe(true)
                          .WithLanguageVersion(LanguageVersion.CSharp8);

            Stopwatch s       = Stopwatch.StartNew();
            var       script  = CSharpScript.Create(code, options, typeof(Globals));
            var       compile = script.GetCompilation().GetDiagnostics();
            var       cErrors = compile.Where(x => x.Severity == DiagnosticSeverity.Error);

            s.Stop();

            if (cErrors.Any())
            {
                await msg.DeleteAsync();

                return(await GenerateErrorAsync(code, cErrors));
            }

            /*
             * if (code.WillExit(out string message))
             * {
             *  var ex = new CodeExitException(message, new Exception(message));
             *  await msg.DeleteAsync();
             *  return await GenerateErrorAsync(code, ex);
             * }
             */

            Stopwatch            c = Stopwatch.StartNew();
            ScriptState <object> eval;

            try
            {
                eval = await script.RunAsync(globals);
            }
            catch (Exception e)
            {
                await msg.DeleteAsync();

                return(await GenerateErrorAsync(code, e));
            }
            c.Stop();

            var result = eval.ReturnValue;

            if (eval.Exception != null)
            {
                await msg.DeleteAsync();

                return(await GenerateErrorAsync(code, eval.Exception));
            }

            string description;

            if (code.Length < 1000)
            {
                description = $"in: ```cs\n{code}```\nout: \n";
            }
            else
            {
                description = $"in: **[input]({await UploadToBisogaAsync(code)})**\nout: \n";
            }
            string tostringed = result == null ? " " : result.ToString();

            if (result is ICollection r)
            {
                tostringed = r.MakeString();
            }
            else if (result is IReadOnlyCollection <object> x)
            {
                tostringed = x.MakeString();
            }
            else if (result is string str)
            {
                tostringed = str;
            }
            else
            {
                tostringed = result.MakeString();
            }

            if (tostringed.Length > 1000)
            {
                description += $"Here is a **[link]({await UploadToBisogaAsync(tostringed)})** to the result.";
            }
            else
            {
                description += $"```{tostringed}```";
            }

            if (sb.ToString().Length > 0)
            {
                description += $"\nConsole: \n```\n{sb}\n```";
            }

            string footer = "";

            if (result is ICollection coll)
            {
                footer += $"Collection has {coll.Count} members • ";
            }
            else if (result is IReadOnlyCollection <object> colle)
            {
                footer += $"Collection has {colle.Count} members • ";
            }

            footer += $"Return type: {(result == null ? "null" : result.GetType().ToString())} • took {s.ElapsedTicks / 10000d} ms to compile and {c.ElapsedTicks / 10000d} ms to execute";


            var em = new EmbedBuilder()
                     .WithFooter(footer)
                     .WithDescription(description)
                     .WithColor(Color.Green);

            await msg.DeleteAsync();

            return(em);
        }
Exemple #28
0
        public async Task HandleReact(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction react)
        {
            if ((react.UserId != client.CurrentUser.Id))
            {
                string tag = null;
                Discord.Rest.RestUserMessage message = null;
                foreach (IMessage msg in Var.awaitingHelp)
                {
                    if (msg.Id == cache.Value.Id)
                    {
                        if (react.Emote.Name == Constants.Emotes.HAMMER.Name)
                        {
                            tag = "[MOD]";
                        }
                        else if (react.Emote.Name == Constants.Emotes.DIE.Name)
                        {
                            tag = "[FUN]";
                        }
                        else if (react.Emote.Name == Constants.Emotes.QUESTION.Name)
                        {
                            tag = "[OTHER]";
                        }
                        else if (react.Emote.Name == Constants.Emotes.BRADY.Name)
                        {
                            tag = "[BRADY]";
                        }
                        message = msg as Discord.Rest.RestUserMessage;
                        Var.awaitingHelp.Remove(msg);
                        break;
                    }
                }

                if (tag != null)
                {
                    JEmbed emb = new JEmbed();

                    emb.Author.Name = "ForkBot Commands";
                    emb.ColorStripe = Constants.Colours.DEFAULT_COLOUR;

                    foreach (CommandInfo c in commands.Commands)
                    {
                        string cTag = null;
                        if (c.Summary != null)
                        {
                            if (c.Summary.StartsWith("["))
                            {
                                int index;
                                index = c.Summary.IndexOf(']') + 1;
                                cTag  = c.Summary.Substring(0, index);
                            }
                            else
                            {
                                cTag = "[OTHER]";
                            }
                        }


                        if (cTag != null && cTag == tag)
                        {
                            emb.Fields.Add(new JEmbedField(x =>
                            {
                                string header = c.Name;
                                foreach (String alias in c.Aliases)
                                {
                                    if (alias != c.Name)
                                    {
                                        header += " (;" + alias + ") ";
                                    }
                                }
                                foreach (Discord.Commands.ParameterInfo parameter in c.Parameters)
                                {
                                    header += " [" + parameter.Name + "]";
                                }
                                x.Header = header;
                                x.Text   = c.Summary.Replace(tag + " ", "");
                            }));
                        }
                    }
                    await message.ModifyAsync(x => x.Embed = emb.Build());

                    await message.RemoveAllReactionsAsync();
                }
            }
        }
Exemple #29
0
        private async Task HandleCommandAsync(SocketMessage arg)
        {
            if (arg is not SocketUserMessage message)
            {
                return;
            }
            ShardedCommandContext context = new ShardedCommandContext(_client, message);

            if (_client.CurrentUser == null || message.Author.Id == _client.CurrentUser.Id || message.Author.IsBot)
            {
                return;
            }
            int argPos = 0;

            if (message.HasStringPrefix(prefix, ref argPos) || message.HasStringPrefix(_client.CurrentUser.Mention, ref argPos))
            {
                IResult result = await _commands.ExecuteAsync(context, argPos, _services);

                if (!result.IsSuccess)
                {
                    Console.WriteLine(result.ErrorReason);
                }

                SocketTextChannel channel = _client.GetChannel(config.Log_channel) as SocketTextChannel;
                if (!result.IsSuccess)
                {
                    EmbedBuilder b = new EmbedBuilder();
                    if (result.Error == CommandError.BadArgCount)
                    {
                        b = new EmbedBuilder();
                        b.WithTitle("You specified more or less arguments then needed");
                        b.WithDescription("More sent to bot-logs");
                        b.WithFooter("Requested by CONSOLE", "https://cdn.discordapp.com/attachments/728360861483401240/728362412373180566/console.png");
                        await message.Channel.SendMessageAsync("", false, b.Build());

                        b = new EmbedBuilder();
                        b.WithTitle("Error while executing command BAD ARG COUNT");
                        b.WithDescription("More detailed explination below");
                        b.AddField("Error reason", result.ErrorReason);
                        b.AddField("Message channel", message.Channel);
                        b.AddField("Message content", message.Content);
                        b.AddField("Message url", message.GetJumpUrl());
                        b.AddField("Error", result.Error);
                        b.AddField("IsSuccess", result.IsSuccess);
                        b.WithFooter("Requested by CONSOLE", "https://cdn.discordapp.com/attachments/728360861483401240/728362412373180566/console.png");
                        await channel.SendMessageAsync("", false, b.Build());

                        return;
                    }
                    else if (result.Error == CommandError.UnknownCommand)
                    {
                        //b = new EmbedBuilder();
                        //b.WithTitle("Unknown command");
                        //b.WithDescription("More sent to bot-logs");
                        //b.WithFooter("Requested by CONSOLE", "https://cdn.discordapp.com/attachments/728360861483401240/728362412373180566/console.png");
                        //await message.Channel.SendMessageAsync("", false, b.Build());
                        //b = new EmbedBuilder();
                        //b.WithTitle("Error while executing command unknown command");
                        //b.WithDescription("More detailed explination below");
                        //b.AddField("Error reason", result.ErrorReason);
                        //b.AddField("Message channel", message.Channel);
                        //b.AddField("Message content", message.Content);
                        //b.AddField("Message url", message.GetJumpUrl());
                        //b.AddField("Error", result.Error);
                        //b.AddField("IsSuccess", result.IsSuccess);
                        //b.WithFooter("Requested by CONSOLE", "https://cdn.discordapp.com/attachments/728360861483401240/728362412373180566/console.png");
                        //await channel.SendMessageAsync("", false, b.Build());
                        return;
                    }
                    else if (result.Error == CommandError.UnmetPrecondition)
                    {
                        b = new EmbedBuilder();
                        b.WithTitle(result.ErrorReason);
                        b.WithDescription("More sent to bot-logs");
                        b.WithFooter("Requested by CONSOLE", "https://cdn.discordapp.com/attachments/728360861483401240/728362412373180566/console.png");
                        await message.Channel.SendMessageAsync("", false, b.Build());

                        b = new EmbedBuilder();
                        b.WithTitle("Error while executing command unmet precondition");
                        b.WithDescription("More detailed explination below");
                        b.AddField("Error reason", result.ErrorReason);
                        b.AddField("Message channel", message.Channel);
                        b.AddField("Message content", message.Content);
                        b.AddField("Message url", message.GetJumpUrl());
                        b.AddField("Error", result.Error);
                        b.AddField("IsSuccess", result.IsSuccess);
                        b.WithFooter("Requested by CONSOLE", "https://cdn.discordapp.com/attachments/728360861483401240/728362412373180566/console.png");
                        await channel.SendMessageAsync("", false, b.Build());

                        return;
                    }
                    b.WithTitle("Error while executing command");
                    b.WithDescription("More detailed explination below");
                    b.AddField("Error reason", result.ErrorReason);
                    b.AddField("Message channel", message.Channel);
                    b.AddField("Message content", message.Content);
                    b.AddField("Message url", message.GetJumpUrl());
                    b.AddField("Error", result.Error);
                    b.AddField("IsSuccess", result.IsSuccess);
                    b.WithFooter("Requested by CONSOLE", "https://cdn.discordapp.com/attachments/728360861483401240/728362412373180566/console.png");
                    Discord.Rest.RestUserMessage e = await channel.SendMessageAsync("", false, b.Build());

                    b = new EmbedBuilder();

                    b.WithTitle("Error while executing command");
                    b.WithDescription("More sent to bot-logs");
                    b.WithFooter("Requested by CONSOLE", "https://cdn.discordapp.com/attachments/728360861483401240/728362412373180566/console.png");
                    await message.Channel.SendMessageAsync("", false, b.Build());

                    SentrySdk.CaptureException(new CommandException(result, " " + e.GetJumpUrl()));
                    throw new CommandException(result, " " + e.GetJumpUrl());
                    // SentrySdk.CaptureMessage(gay.GetJumpUrl());
                }
            }
        }