Exemple #1
0
        public async Task FolderTask(CommandContext ctx, [Description("Term to search for, leave blank for random file.")][RemainingText] string search = "")
        {
            var rng   = new Random();
            var files = CommandHelper.IndexFiles();

            var file = files[rng.Next(files.Length)];

            if (!string.IsNullOrEmpty(search))
            {
                files = files.Where(x => x.ToLower().Contains(search.ToLower())).ToArray();
                file  = files[rng.Next(files.Length)];
            }

            var fileName = file.Substring(file.LastIndexOf(Path.DirectorySeparatorChar) + 1);

            if (new FileInfo(file).Length > 8_388_608)
            {
                await ctx.RespondAsync($"File `{fileName}` was over 8MB");

                throw new Exception($"File '{fileName}' was over Discord's size limit");
            }

            Logger.Log($"Folder requested by {ctx.User.Username} in #{ctx.Channel.Name} ({ctx.Guild.Name})" +
                       $"\n\t=> Sending file \"{fileName}\"",
                       LogLevel.Info);

            var msg = new DiscordMessageBuilder()
                      .WithReply(ctx.Message.Id)
                      .WithFile(new FileStream(file, FileMode.Open));

            StalkbotClient.UpdateLastMessage(await ctx.RespondAsync(msg));
        }
Exemple #2
0
        public async Task ProcessesTask(CommandContext ctx)
        {
            Logger.Log($"Processes requested by {ctx.User.Username} in #{ctx.Channel.Name} ({ctx.Guild.Name})",
                       LogLevel.Info);
            var table = new ConsoleTable("Name", "RAM", "Uptime");

            Process.GetProcesses()
            .Where(x => x.SessionId == Process.GetCurrentProcess().SessionId)
            .OrderByDescending(p => p.PrivateMemorySize64)
            .Take(15)
            .ToList()
            .ForEach(process =>
            {
                try
                {
                    table.AddRow($"{process.ProcessName}", $"{process.PrivateMemorySize64 / 1_000_000}MB",
                                 $"{DateTime.Now - process.StartTime:h'h 'm'm 's's'}");
                }
                catch
                {
                    table.AddRow($"{process.ProcessName}", $"{process.PrivateMemorySize64 / 1_000_000}MB",
                                 "Not available");
                }
            });

            var tableString = table.Configure(x => x.NumberAlignment = Alignment.Right).ToMinimalString();

            StalkbotClient.UpdateLastMessage(await ctx.RespondAsync($"```{tableString}```"));
        }
Exemple #3
0
        public async Task WebcamTask(CommandContext ctx,
                                     [Description("Index of the cam you want to capture.\nUse the webcam command to list them.")]
                                     int camIndex = -1)
        {
            // if no camera index has been passed, use the one from the config
            if (camIndex == -1)
            {
                camIndex = Config.Instance.DefaultCam;
            }

            Logger.Log($"Webcam requested by {ctx.User.Username} in #{ctx.Channel.Name} ({ctx.Guild.Name})",
                       LogLevel.Info);

            // init capture
            var capture =
                new VideoCaptureDevice(Constants.Cameras[camIndex].MonikerString);

            try
            {
                capture.VideoResolution = TrySelectRes(capture, false);
            }
            catch (Exception ex)
            {
                if (ex.HResult != -2146233079)
                {
                    throw;
                }
            }

            capture.Start();

            // wait for configured time
            await Task.Delay(Config.Instance.CamTimer);

            // capture photo
            await ctx.Message.CreateReactionAsync(DiscordEmoji.FromUnicode("📸"));

            capture.NewFrame += (sender, args) =>
            {
                args.Frame.Save("webcam.png");
                capture.SignalToStop();
            };

            // stop capture
            while (capture.IsRunning)
            {
                capture.WaitForStop();
            }
            capture.Stop();
            // send/update message and delete file from disk
            var msg = new DiscordMessageBuilder()
                      .WithReply(ctx.Message.Id)
                      .WithFile(new FileStream("webcam.png", FileMode.Open));

            StalkbotClient.UpdateLastMessage(await ctx.RespondAsync(msg));
            File.Delete("webcam.png");
        }
Exemple #4
0
        public async Task ListCamsCommand(CommandContext ctx)
        {
            Logger.Log($"Webcam list requested by {ctx.User.Username} in #{ctx.Channel.Name} ({ctx.Guild.Name})",
                       LogLevel.Info);
            var result = "**Available Webcams:**\n```\n";

            for (var i = 0; i < Constants.Cameras.Count; i++)
            {
                result += $"{i} => {Constants.Cameras[i].Name}\n";
            }
            StalkbotClient.UpdateLastMessage(await ctx.RespondAsync($"{result}\n```"));
        }
Exemple #5
0
        public async Task ScreenshotTask(CommandContext ctx)
        {
            Logger.Log($"Screenshot requested by {ctx.User.Username} in #{ctx.Channel.Name} ({ctx.Guild.Name})",
                       LogLevel.Info);

            await TakeScreenshot(LiveFilename);

            if (Config.Instance.BlurAmount > 0)
            {
                using (var img = await Image.LoadAsync(LiveFilename))
                {
                    img.Mutate(x => x.GaussianBlur((float)Config.Instance.BlurAmount));
                    await img.SaveAsync(LiveFilename);
                }
            }

            var msg = new DiscordMessageBuilder()
                      .WithReply(ctx.Message.Id)
                      .WithFile(new FileStream(LiveFilename, FileMode.Open));

            StalkbotClient.UpdateLastMessage(await ctx.RespondAsync(msg));
            File.Delete(LiveFilename);
        }
Exemple #6
0
        /// <summary>
        /// Constructor
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
            Logger.Init(ref LogText, ref LogView);
            _client = new StalkbotClient();
            if (Config.Instance.AutoStartDiscord)
            {
                new Action(() => OnOffButton_Click(null, null))();
            }
            InitButtons();
            _notifyIcon = new NotifyIcon
            {
                BalloonTipText = @"Stalkbot is still running!",
                Icon           = System.Drawing.Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location)
            };
            _notifyIcon.DoubleClick += NotifyIconOnDoubleClick;

            Task.Delay(1000);
            CheckRequirements();
            CheckForNewRelease();
#if DEBUG
            this.Title += " - DEBUG";
#endif
        }
Exemple #7
0
        public async Task GifTask(CommandContext ctx, [Description("FPS value to set the gif at")] params string[] comArgs)
        {
            Directory.CreateDirectory("gif");
            Logger.Log($"Webcam Gif requested by {ctx.User.Username} in #{ctx.Channel.Name} ({ctx.Guild.Name})",
                       LogLevel.Info);

            var capture =
                new VideoCaptureDevice(Constants.Cameras[Config.Instance.DefaultCam].MonikerString);

            try
            {
                capture.VideoResolution = TrySelectRes(capture, true);
            }
            catch (Exception ex)
            {
                if (ex.HResult != -2146233079)
                {
                    throw;
                }
            }

            capture.Start();
            await Task.Delay(Config.Instance.CamTimer);

            await ctx.Message.CreateReactionAsync(DiscordEmoji.FromUnicode("🎥"));

            var timer = new Timer(Config.Instance.GifLength)
            {
                Enabled = true, AutoReset = false
            };

            timer.Elapsed += (sender, args) => capture.SignalToStop();

            var counter = 0;

            capture.NewFrame += (sender, args) =>
            {
                args.Frame.Save($"gif{Path.DirectorySeparatorChar}{counter++}.png", ImageFormat.Png);
                args.Frame.Dispose();
            };

            while (capture.IsRunning)
            {
                capture.WaitForStop();
            }
            capture.Stop();

            await ctx.Message.CreateReactionAsync(DiscordEmoji.FromUnicode("📤"));

            await ctx.Message.DeleteOwnReactionAsync(DiscordEmoji.FromUnicode("🎥"));

            await CreateGif(comArgs);

            var msg = new DiscordMessageBuilder()
                      .WithReply(ctx.Message.Id)
                      .WithFile(new FileStream("result.gif", FileMode.Open));

            StalkbotClient.UpdateLastMessage(await ctx.RespondAsync(msg));
            await ctx.Message.DeleteOwnReactionAsync(DiscordEmoji.FromUnicode("📤"));

            Directory.Delete("gif", true);
            File.Delete("result.gif");
            timer.Dispose();
        }
Exemple #8
0
        public async Task MicTask(CommandContext ctx, int sampleRate = 44100)
        {
            await Task.Delay(Config.Instance.MicTimer);

            var mic    = WaveIn.GetCapabilities(Config.Instance.MicIndex);
            var source = new WaveInEvent()
            {
                DeviceNumber = Config.Instance.MicIndex, WaveFormat = new WaveFormat(sampleRate, 1)
            };
            var writer = new WaveFileWriter("recording.wav", source.WaveFormat);
            var timer  = new Timer {
                AutoReset = false, Interval = Config.Instance.MicLength
            };

            timer.Elapsed += async(sender, args) =>
            {
                source.StopRecording();
                await Task.Delay(500);

                await ctx.Message.DeleteOwnReactionAsync(DiscordEmoji.FromUnicode("🎙"));

                var msg = new DiscordMessageBuilder()
                          .WithReply(ctx.Message.Id)
                          .WithFile(new FileStream("recording.wav", FileMode.Open));

                StalkbotClient.UpdateLastMessage(await ctx.RespondAsync(msg));
                File.Delete("recording.wav");
            };

            Logger.Log($"Started recording with mic {mic.ProductName}", LogLevel.Info);

            source.DataAvailable += (sender, args) =>
            {
                if (writer == null)
                {
                    return;
                }
                writer.Write(args.Buffer, 0, args.BytesRecorded);
                writer.Flush();
            };

            source.RecordingStopped += (sender, args) =>
            {
                if (source != null)
                {
                    source.StopRecording();
                    source.Dispose();
                    source = null;
                }

                if (writer == null)
                {
                    return;
                }

                writer.Dispose();
                writer = null;
            };
            timer.Start();
            source.StartRecording();
            await ctx.Message.CreateReactionAsync(DiscordEmoji.FromUnicode("🎙"));
        }