Пример #1
0
        public void TestDynamoDbClient()
        {
            AWSSDKHandler.RegisterXRayForAllServices(_path);
            // IAmazonDynamoDb will be registered. All new instances of AmazonServiceClient will be automatically registered.

            using (var client = new AmazonDynamoDBClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1))
            {
                string requestId = @"fakerequ-esti-dfak-ereq-uestidfakere";
                CustomResponses.SetResponse(client, null, requestId, true);

                _recorder.BeginSegment("test", TraceId);
#if NET45
                client.ListTables();
#else
                client.ListTablesAsync().Wait();
#endif
                var segment    = TraceContext.GetEntity();
                var subsegment = segment.Subsegments[0];
                _recorder.EndSegment();

                Assert.AreEqual(segment.Subsegments.Count, 1);
                Assert.AreEqual(subsegment.Name, "DynamoDBv2");
                Assert.AreEqual(subsegment.Aws["region"], RegionEndpoint.USEast1.SystemName);
                Assert.AreEqual(subsegment.Aws["operation"], "ListTables");
                Assert.AreEqual(requestId, subsegment.Aws["request_id"]);
                Assert.AreEqual("aws", subsegment.Namespace);
            }
        }
Пример #2
0
        public void TestLambdaInvokeSubsegmentContainsFunctionNameForAWSSDKHandler()
        {
            String temp_path = @"JSONs\AWSRequestInfoWithLambda.json"; //registering manifest file with Lambda

            AWSSDKHandler.RegisterXRayManifest(temp_path);
            var lambda = new AmazonLambdaClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1);

            CustomResponses.SetResponse(lambda, null, null, true);
            AWSXRayRecorder.Instance.BeginSegment("lambda", TraceId);
#if NET45
            lambda.Invoke(new InvokeRequest
            {
                FunctionName = "testFunction"
            });
#else
            lambda.InvokeAsync(new InvokeRequest
            {
                FunctionName = "testFunction"
            }).Wait();
#endif
            var segment = TraceContext.GetEntity();
            AWSXRayRecorder.Instance.EndSegment();

            Assert.AreEqual("Invoke", segment.Subsegments[0].Aws["operation"]);
            Assert.AreEqual("testFunction", segment.Subsegments[0].Aws["function_name"]);
        }
Пример #3
0
        public void TestExceptionHandler()
        {
            using (var client = new AmazonDynamoDBClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1))
            {
                _handler.AddEventHandler(client);
                CustomResponses.SetResponse(client, (request) => { throw new InvalidOperationException(); });

                _recorder.BeginSegment("test", TraceId);
                var segment = TraceContext.GetEntity();

                try
                {
                    client.GetItem(
                        "test", new Dictionary <string, AttributeValue>()
                    {
                        { "invalid_key", new AttributeValue("1") }
                    });
                    Assert.Fail();
                }
                catch (InvalidOperationException e)
                {
                    Assert.ReferenceEquals(e, segment.Subsegments[0].Cause.ExceptionDescriptors[0].Exception);
                    Assert.IsTrue(segment.Subsegments[0].Aws.ContainsKey("table_name"));
                    Assert.IsTrue(segment.Subsegments[0].Aws.ContainsKey("consistent_read"));
                    Assert.IsTrue(segment.Subsegments[0].Aws.ContainsKey("projection_expression"));
                    Assert.IsTrue(segment.Subsegments[0].Aws.ContainsKey("attribute_names_substituted"));
                }
                finally
                {
                    _recorder.EndSegment();
                }
            }
        }
Пример #4
0
        public async static Task MainAsync(string Token)
        {
            MGXStatistics.StartedAt = DateTime.UtcNow;
            var config = new DiscordSocketConfig {
                MessageCacheSize = 5, TotalShards = 1
            };

            Client = new DiscordShardedClient(config);
            DiscordBotListClient = new AuthDiscordBotListApi(534193192329805854, "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjUzNDE5MzE5MjMyOTgwNTg1NCIsImJvdCI6dHJ1ZSwiaWF0IjoxNTg3NDI3NzQxfQ.lU-e43AqYswMC3UZsc145RgadqEhrrrelKoSCvT8UXg");
            //(await DiscordBotListClient.GetMeAsync()).
            CustomResponses.UpdateResponses();
            await Client.LoginAsync(TokenType.Bot, Token);

            await Client.StartAsync();

            Client.MessageReceived += Client_MessageReceived;
            Client.MessageReceived += globalchat.MessageReceived;
            Client.MessageReceived += snipe.OnReceived;
            Client.MessageReceived += Secondary.MyClient_MessageReceived;
            Client.ShardReady      += Client_Ready;
            Client.JoinedGuild     += Client_JoinedGuild;
            Client.LeftGuild       += Client_LeftGuild;
            Client.MessageDeleted  += snipe.OnDelete;
            new Thread(async x =>
            {
                await Secondary.Secondary_Thread();
            }).Start();

            await Task.Delay(-1);
        }
Пример #5
0
        public static async Task Maindo(SocketMessage arg)
        {
            try
            {
                var GuildId = ((SocketTextChannel)arg.Channel).Guild.Id;
                int Ran     = new Random().Next(1, CustomResponses.WordResp.Count);
                CustomResponses.UpdateResponses();
                bool CusResp = await SetupX(arg, $"Would you like me to send occasional replies to certain messages?\n\n`Reply with 'yes' or 'no'`");

                await arg.Channel.TriggerTypingAsync();

                Thread.Sleep(1250);
                bool GloblCht = await SetupX(arg, $"Do you want to participate in MGX globalchat?\nMGX globalchat allows your server to communicate with other servers through a specific channel. If you'd like more information about it, please friend and message {Program.MyAccount.Username}#{Program.MyAccount.Discriminator}.\n\n`Reply with 'yes' or 'no'`");

                if (GloblCht)
                {
                    await globalchat.DefSet(arg, true);
                }
                await arg.Channel.TriggerTypingAsync();

                Thread.Sleep(2000);
                bool QuarantineCmd = await SetupX(arg, $"{Program.Prefix}quarantine is a command that can be used by anyone, and can mute people (it was created more as a meme than for genuine usefullness). Would you like this command to be usable?\n\n`Reply with 'yes' or 'no'`");

                GuildStuff.NewGuildSetting(GuildStuff.GuildSettings.CustomResponses, GuildId, CusResp);
                GuildStuff.NewGuildSetting(GuildStuff.GuildSettings.CanUseQuarantine, GuildId, QuarantineCmd);
                string Desc = $"**Applied New Settings!**\nCongrats! You've successfully setup your server for use with {Program.Client.CurrentUser.Username}.\nCurrent settings:\n```\nCustom Responses: {ResolveBool(CusResp)}\nMGX Globalchat: {ResolveBool(GloblCht)}\nQuarantine Command: {ResolveBool(QuarantineCmd)}\n```";
                var    Emb  = CreateEmbed($"{Program.Client.CurrentUser.Username}", "<3", Desc, null);
                await arg.Channel.SendMessageAsync("", false, Emb);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Пример #6
0
        public void TestDynamoSubsegmentNameIsCorrectForAWSSDKHandler()
        {
            var dynamo = new AmazonDynamoDBClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1);

            CustomResponses.SetResponse(dynamo, null, null, true);
            AWSXRayRecorder.Instance.BeginSegment("test dynamo", TraceId);
#if NET45
            dynamo.ListTables();
#else
            dynamo.ListTablesAsync().Wait();
#endif
            var segment = TraceContext.GetEntity();
            AWSXRayRecorder.Instance.EndSegment();

            Assert.AreEqual("DynamoDBv2", segment.Subsegments[0].Name);
        }
Пример #7
0
        public void TestInvokeResponseBody()
        {
            var responseBody = "Process exited before completing request:TypeError: Object #<LambdaEventResponse> has no method 'write': at exports.handler (/var/task/helloworld.js:4:14)";
            var requestId    = "fakerequ-esti-dfak-ereq-uestidfakere";

            using (var client = new Amazon.Lambda.AmazonLambdaClient(new Amazon.Runtime.AnonymousAWSCredentials(), RegionEndpoint.USEast1))
            {
                CustomResponses.SetResponse(client, responseBody, requestId, isOK: true);

                var response = client.Invoke(new InvokeRequest
                {
                });
                Assert.AreEqual(requestId, response.ResponseMetadata.RequestId);
                Assert.AreEqual(responseBody, Encoding.UTF8.GetString(response.Payload.ToArray()));
            }
        }
Пример #8
0
        public void TestS3SubsegmentNameIsCorrect()
        {
            var s3 = new AmazonS3Client(new AnonymousAWSCredentials(), RegionEndpoint.USEast1);

            new AWSSdkTracingHandler(AWSXRayRecorder.Instance).AddEventHandler(s3);
            CustomResponses.SetResponse(s3, null, null, true);

            AWSXRayRecorder.Instance.BeginSegment("test s3", TraceId);

            s3.GetObject("testBucket", "testKey");

            var segment = TraceContext.GetEntity();

            AWSXRayRecorder.Instance.EndSegment();

            Assert.AreEqual("S3", segment.Subsegments[0].Name);
        }
Пример #9
0
        public void TestDynamoSubsegmentNameIsCorrect()
        {
            var dynamo = new AmazonDynamoDBClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1);

            new AWSSdkTracingHandler(AWSXRayRecorder.Instance).AddEventHandler(dynamo);
            CustomResponses.SetResponse(dynamo, null, null, true);

            AWSXRayRecorder.Instance.BeginSegment("test dynamo", TraceId);

            dynamo.ListTables();

            var segment = TraceContext.GetEntity();

            AWSXRayRecorder.Instance.EndSegment();

            Assert.AreEqual("DynamoDBv2", segment.Subsegments[0].Name);
        }
Пример #10
0
        public void TestS3SubsegmentNameIsCorrectForAWSSDKHandler()
        {
            AWSSDKHandler.RegisterXRay <IAmazonS3>();
            var s3 = new AmazonS3Client(new AnonymousAWSCredentials(), RegionEndpoint.USEast1);

            CustomResponses.SetResponse(s3, null, null, true);

            AWSXRayRecorder.Instance.BeginSegment("test s3", TraceId);
#if NET45
            s3.GetObject("testBucket", "testKey");
#else
            s3.GetObjectAsync("testBucket", "testKey").Wait();
#endif
            var segment = TraceContext.GetEntity();
            AWSXRayRecorder.Instance.EndSegment();
            Assert.AreEqual("S3", segment.Subsegments[0].Name);
        }
Пример #11
0
        public void TestRequestResponseParameterAndDescriptorForAWSSDKHandler()
        {
            using (var client = new AmazonDynamoDBClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1))
            {
                CustomResponses.SetResponse(client, null, null, true);
                _recorder.BeginSegment("test", TraceId);
                var segment = TraceContext.GetEntity();

                var key1 = new Dictionary <string, AttributeValue>()
                {
                    { "id", new AttributeValue("1") }
                };
                var key2 = new Dictionary <string, AttributeValue>()
                {
                    { "id", new AttributeValue("2") }
                };
                var keys = new KeysAndAttributes()
                {
                    Keys = new List <Dictionary <string, AttributeValue> >()
                    {
                        key1, key2
                    }
                };

#if NET45
                client.BatchGetItem(new Dictionary <string, KeysAndAttributes>()
                {
                    { "test", keys }
                });
#else
                client.BatchGetItemAsync(new Dictionary <string, KeysAndAttributes>()
                {
                    { "test", keys }
                }).Wait();
#endif
                _recorder.EndSegment();
                Assert.IsTrue(segment.Subsegments[0].Aws.ContainsKey("request_items"));
                Assert.IsTrue(segment.Subsegments[0].Aws.ContainsKey("responses"));
                Assert.IsTrue(segment.Subsegments[0].Aws.ContainsKey("item_count"));
                Assert.IsTrue(segment.Subsegments[0].Aws.ContainsKey("table_names"));
                Assert.IsTrue(segment.Subsegments[0].Aws.ContainsKey("operation"));
                Assert.IsTrue(segment.Subsegments[0].Aws.ContainsKey("request_id"));
            }
        }
Пример #12
0
        public async Task TestExceptionHandlerAsyncForAWSSDKHandler()
        {
            using (var client = new AmazonDynamoDBClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1))
            {
                string requestId = @"fakerequ-esti-dfak-ereq-uestidfakere";
                AmazonServiceException amazonServiceException = new AmazonServiceException();
                amazonServiceException.StatusCode = System.Net.HttpStatusCode.NotFound;
                amazonServiceException.RequestId  = requestId;
                CustomResponses.SetResponse(client, (request) => { throw amazonServiceException; });
                _recorder.BeginSegment("test", TraceId);
                var segment = TraceContext.GetEntity();

                try
                {
                    await client.GetItemAsync(
                        "test", new Dictionary <string, AttributeValue>() { { "invalid_key", new AttributeValue("1") } });

                    Assert.Fail();
                }
                catch (AmazonServiceException e)
                {
                    Assert.ReferenceEquals(e, segment.Subsegments[0].Cause.ExceptionDescriptors[0].Exception);
                    Assert.IsTrue(segment.Subsegments[0].Aws.ContainsKey("table_name"));
                    Assert.IsTrue(segment.Subsegments[0].Aws.ContainsKey("consistent_read"));
                    Assert.IsTrue(segment.Subsegments[0].Aws.ContainsKey("projection_expression"));
                    Assert.IsTrue(segment.Subsegments[0].Aws.ContainsKey("attribute_names_substituted"));

                    var responseInfo = segment.Subsegments[0].Http["response"] as Dictionary <string, object>;
                    Assert.AreEqual(404, responseInfo["status"]);

                    var subsegment = segment.Subsegments[0];
                    Assert.AreEqual(requestId, subsegment.Aws["request_id"]);
                    Assert.IsTrue(subsegment.HasError);
                    Assert.IsFalse(subsegment.HasFault);
                }
                finally
                {
                    _recorder.EndSegment();
                }
            }
        }
Пример #13
0
        public void TestManifestFileNoLambda() //At this point, current manifest file doen't contain Lambda service.
        {
            var lambda = new AmazonLambdaClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1);

            CustomResponses.SetResponse(lambda, null, null, true);
            AWSXRayRecorder.Instance.BeginSegment("lambda", TraceId);
#if NET45
            lambda.Invoke(new InvokeRequest
            {
                FunctionName = "testFunction"
            });
#else
            lambda.InvokeAsync(new InvokeRequest
            {
                FunctionName = "testFunction"
            }).Wait();
#endif
            var segment = TraceContext.GetEntity();
            AWSXRayRecorder.Instance.EndSegment();
            Assert.IsFalse(segment.Subsegments[0].Aws.ContainsKey("function_name"));
        }
Пример #14
0
        public void TestLambdaInvokeSubsegmentContainsFunctionName()
        {
            var lambda = new AmazonLambdaClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1);

            new AWSSdkTracingHandler(AWSXRayRecorder.Instance).AddEventHandler(lambda);
            CustomResponses.SetResponse(lambda, null, null, true);

            AWSXRayRecorder.Instance.BeginSegment("lambda", TraceId);

            lambda.Invoke(new InvokeRequest
            {
                FunctionName = "testFunction"
            });

            var segment = TraceContext.GetEntity();

            AWSXRayRecorder.Instance.EndSegment();

            Assert.AreEqual("Invoke", segment.Subsegments[0].Aws["operation"]);
            Assert.AreEqual("testFunction", segment.Subsegments[0].Aws["function_name"]);
        }
Пример #15
0
        public void TestAddEventHandlerToDynamoDBClient()
        {
            using (var client = new AmazonDynamoDBClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast1))
            {
                _handler.AddEventHandler(client);
                string requestId = @"fakerequ-esti-dfak-ereq-uestidfakere";
                CustomResponses.SetResponse(client, null, requestId, true);

                _recorder.BeginSegment("test", TraceId);

                client.ListTables();

                var segment    = TraceContext.GetEntity();
                var subsegment = segment.Subsegments[0];
                _recorder.EndSegment();

                Assert.AreEqual(segment.Subsegments.Count, 1);
                Assert.AreEqual(subsegment.Name, "DynamoDBv2");
                Assert.AreEqual(subsegment.Aws["region"], RegionEndpoint.USEast1.SystemName);
                Assert.AreEqual(subsegment.Aws["operation"], "ListTables");
                Assert.AreEqual(requestId, subsegment.Aws["request_id"]);
                Assert.AreEqual("aws", subsegment.Namespace);
            }
        }
Пример #16
0
        //COMMAND HANDLING
        private static async Task Client_MessageReceived(SocketMessage arg)
        {
            try
            {
                if (!arg.Author.IsBot && arg.Channel.GetType() == typeof(SocketTextChannel))
                {
                    var Guild = ((SocketGuildChannel)arg.Channel).Guild;
                    if (arg.Content.ToLower().StartsWith(Prefix))
                    {
                        var Cmd           = Type.GetType($"MGX_Discord_Bot.EModules.Commands.General.{arg.Content.Split(' ')[0].Split(new[] { Prefix }, StringSplitOptions.None)[1].ToLower()}");
                        int UserGuildRank = GuildStuff.ReadRank(Guild.Id, arg.Author.Id);
                        int UserMGXRank   = RankingManager.BotOwners.ContainsKey(arg.Author.Id) ? RankingManager.BotOwners[arg.Author.Id] : 1;
                        if (Cmd != null)
                        {
                            var CmdInfo = (CommandInformation)Cmd.GetField("Info").GetValue(null);
                            if (CmdInfo.Premium && false) // change false to check database for user if they have premium
                            {
                                await arg.Channel.SendMessageAsync("MGX premium is required for this command :pensive:");
                            }
                            else if (CmdInfo.RequiredPermissions <= UserGuildRank)
                            {
                                Cmd.GetMethod("Maindo").Invoke(null, new[] { arg });
                                int CountAlr = StoreHandler.LoadData(arg.Author.Id, $"CMD-COUNT") != null?int.Parse(StoreHandler.LoadData(arg.Author.Id, $"CMD-COUNT")) : 0;

                                StoreHandler.SaveData(arg.Author.Id, "CMD-COUNT", CountAlr + 1);
                            }
                            else
                            {
                                await arg.Channel.SendMessageAsync($"You aren't able to run this! You must be `{GuildStuff.GetNameOfRank(CmdInfo.RequiredPermissions)}` or higher.");
                            }
                            int CurCmd = StoreHandler.LoadData(0, "cmdcount") == null ? 0 : int.Parse(StoreHandler.LoadData(0, "cmdcount"));
                            StoreHandler.SaveData(0, "cmdcount", CurCmd + 1);
                        }
                        else if (RankingManager.BotOwners.ContainsKey(arg.Author.Id))
                        {
                            Cmd = Type.GetType($"MGX_Discord_Bot.EModules.Commands.Maintenance.{arg.Content.Split(' ')[0].Split(new[] { Prefix }, StringSplitOptions.None)[1].ToLower()}");
                            var CmdInfo = (CommandInformation)Cmd.GetField("Info").GetValue(null);
                            if (Cmd != null && CmdInfo.RequiredPermissions <= UserMGXRank)
                            {
                                Cmd.GetMethod("Maindo").Invoke(null, new[] { arg });
                            }
                            else
                            {
                                Console.WriteLine("Maint null");
                            }
                        }
                    }
                    // CUSTOM RESPONSES \\
                    if (GuildStuff.ReadSetting(GuildStuff.GuildSettings.CustomResponses, Guild.Id))
                    {
                        var ReturnedWordResp = CustomResponses.ReturnResponse(arg.Content);
                        if (ReturnedWordResp != null)
                        {
                            await arg.Channel.SendMessageAsync(ReturnedWordResp);
                        }
                        else if (arg.Content.ToLower().StartsWith("ree"))
                        {
                            await arg.Channel.SendMessageAsync("*r e e ?*");
                        }
                        else if (arg.Content.ToLower().Contains("anti") && arg.Content.ToLower().Contains("va") || arg.Content.ToLower().Contains("vac") && arg.Content.ToLower().Contains("do") && arg.Content.ToLower().Contains("nt"))
                        {
                            await arg.Channel.SendMessageAsync($"i swear to f*****g god you better vaccinate your kids");
                        }
                        else if (arg.Content.ToLower().Contains("sksk") | arg.Content.ToLower().Contains(" oop ") | arg.Content.ToLower().Contains("ess kay") | arg.Content.ToLower().Contains("esskay"))
                        {
                            await arg.Channel.SendMessageAsync("ew, vsco. begone thot");
                        }
                        else if (arg.Content.ToLower().StartsWith("i am ") || arg.Content.ToLower().StartsWith("im ") || arg.Content.ToLower().StartsWith("i'm "))
                        {
                            string WhatTheyAre = arg.Content.Split(new string[] { "m" }, 2, StringSplitOptions.None)[1];
                            await arg.Channel.SendMessageAsync($"hi {WhatTheyAre.Trim()}, im dad");
                        }
                        CustomResponses.UpdateResponses();
                    }
                    if (GuildStuff.ReadSetting(GuildStuff.GuildSettings.ReplaceInvites, Guild.Id) && arg.Content.ToLower().Contains("discord.gg/"))
                    {
                        var RepInvEm = new EmbedBuilder()
                        {
                            Color     = new Color(0x36393F),
                            Timestamp = DateTime.UtcNow,
                            Author    = new EmbedAuthorBuilder()
                            {
                                Name = $"{arg.Author.Username} has invited you to a guild!"
                            },
                        };
                    }
                }
                else if (!arg.Author.IsBot)
                {
                    await MyAccount.SendMessageAsync($"{arg.Author.Username}#{arg.Author.Discriminator}: {arg.Content}\n\n{arg.Author.Id}");

                    foreach (var Attachment in arg.Attachments)
                    {
                        await MyAccount.SendMessageAsync(Attachment.Url);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }