Example #1
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
            BotHandler bot = new BotHandler();
        }
Example #2
0
        public async Task LeaveRoom(CommandContext ctx)
        {
            foreach (var room in BotHandler.openRooms)
            {
                if (room.Value.players.Contains(ctx.User.Id))
                {
                    room.Value.players.Remove(ctx.User.Id);
                    BotHandler.SetUserState(ctx.User.Id, UserState.Idle);

                    await ctx.RespondAsync(new DiscordEmbedBuilder {
                        Title = "Room Left Successfully",
                        Color = DiscordColor.Green
                    }).ConfigureAwait(false);

                    return;
                }
            }

            await ctx.RespondAsync(new DiscordEmbedBuilder
            {
                Title       = "You Are Not In Any Rooms",
                Description = "You shouln't be seeing this message. This is a bug.",
                Color       = DiscordColor.Violet
            }).ConfigureAwait(false);
        }
Example #3
0
        // POST api/values
        public HttpResponseMessage Post(UpdateObject input)
        {
            BotHandler botHandler = new BotHandler();

            botHandler.Process(input);
            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
Example #4
0
        public override void OnUserChangeRoom(ClientInfo client, Room oldRoom, Room newRoom)
        {
            Dictionary <string, ClientInfo> clients = BotHandler.TRequestClients();

            foreach (KeyValuePair <string, ClientInfo> info in clients)
            {
                if (info.Value.GUID != client.GUID)
                {
                    if (info.Value.RoomId == newRoom.ID)
                    {
                        Message m = new Message("Server", MessageType.Message);
                        m.SetContent(client.Name + " Joined your room");
                        m.SetColor(NColor.Orange);
                        info.Value.Send(m);
                    }
                    else if (info.Value.RoomId == oldRoom.ID)
                    {
                        Message m = new Message("Server", MessageType.Message);
                        m.SetContent(client.Name + " Left your room");
                        m.SetColor(NColor.Orange);
                        info.Value.Send(m);
                    }
                }
            }
        }
Example #5
0
        public async void HandlesValidBotAdded()
        {
            var bots = new List<BotModel>
            {
                new BotModel { Id = "BOTID1" },
                new BotModel { Id = "BOTID2" }
            };

            var mockState = new Mock<IBotState>();
            mockState.Setup(s => s.Bots)
                     .Returns(bots)
                     .Verifiable();

            var message = new BotAdded
            {
                Type = EventType.BotAdded,
                Bot = new BotModel { Id = "BOTID3" }
            };

            var handler = new BotHandler();
            handler.BotState = mockState.Object;

            var result = await handler.HandleMessageAsync(message);

            mockState.Verify();
            Assert.Equal(3, bots.Count);
            Assert.Equal("BOTID3", bots.Last().Id);
        }
Example #6
0
        public async void AddsMissingChangedBot()
        {
            var bots = new List <BotModel>
            {
                new BotModel {
                    Id = "BOTID2"
                }
            };

            var mockState = new Mock <IBotState>();

            mockState.Setup(s => s.Bots)
            .Returns(bots)
            .Verifiable();

            var message = new BotChanged
            {
                Type = EventType.BotChanged,
                Bot  = new BotModel {
                    Id = "BOTID1", Name = "NameB"
                }
            };

            var handler = new BotHandler();

            handler.BotState = mockState.Object;

            var result = await handler.HandleMessageAsync(message);

            mockState.Verify();
            Assert.Equal(2, bots.Count);
            Assert.Equal("NameB", bots.First(b => b.Id == "BOTID1").Name);
        }
Example #7
0
        public async void HandlesValidBotChanged()
        {
            var bots = new List<BotModel>
            {
                new BotModel { Id = "BOTID1", Name = "NameA" },
                new BotModel { Id = "BOTID2" }
            };

            var mockState = new Mock<IBotState>();
            mockState.Setup(s => s.Bots)
                     .Returns(bots)
                     .Verifiable();

            var message = new BotChanged
            {
                Type = EventType.BotChanged,
                Bot = new BotModel { Id = "BOTID1", Name = "NameB" }
            };

            var handler = new BotHandler();
            handler.BotState = mockState.Object;

            var result = await handler.HandleMessageAsync(message);

            mockState.Verify();
            Assert.Equal(2, bots.Count);
            Assert.Equal("NameB", bots.First(b => b.Id == "BOTID1").Name);
        }
Example #8
0
        public async Task JoinRoom(CommandContext ctx, [RemainingText] string roomName)
        {
            string filterMsg;
            bool   res = BotHandler.FilterName(ref roomName, out filterMsg, 3, 40);

            if (res)
            {
                foreach (var room in BotHandler.openRooms)
                {
                    if (room.Value.guild.Id == ctx.Guild.Id && room.Value.roomName.Equals(roomName))
                    {
                        room.Value.AddPlayer(ctx.User.Id);
                        await ctx.RespondAsync(new DiscordEmbedBuilder {
                            Title = "Room Joined Successfully",
                            Color = DiscordColor.Green
                        }).ConfigureAwait(false);

                        await MechCustomizationCommands.SetName(ctx);

                        return;
                    }
                }
            }

            await ctx.RespondAsync(new DiscordEmbedBuilder
            {
                Title = "Could Not Join The Room",
                Color = DiscordColor.Red
            }).ConfigureAwait(false);
        }
Example #9
0
        public async Task RenameRoom(CommandContext ctx, [RemainingText] string roomName)
        {
            string filterMsg;
            bool   res = BotHandler.FilterName(ref roomName, out filterMsg, 3, 40);

            if (res)
            {
                if (BotHandler.Rooms.IsNameAvailable(ctx, roomName))
                {
                    await ctx.RespondAsync(new DiscordEmbedBuilder {
                        Title = "Room Renamed Successfully",
                        Color = DiscordColor.Green
                    }).ConfigureAwait(false);

                    BotHandler.openRooms[ctx.User.Id].roomName = roomName;
                }
                else
                {
                    await ctx.RespondAsync(new DiscordEmbedBuilder {
                        Title = "Room Name Already Taken",
                        Color = DiscordColor.Red
                    }).ConfigureAwait(false);
                }
            }
            else
            {
                await ctx.RespondAsync(new DiscordEmbedBuilder
                {
                    Title       = "Invalid Name",
                    Description = filterMsg,
                    Color       = DiscordColor.Red
                }).ConfigureAwait(false);
            }
        }
Example #10
0
        private void Users(string[] parameters, ClientInfo sender)
        {
            Room    r = BotHandler.TRequestRoomByID(sender.RoomId);
            Message m = new Message("Test Bot", MessageType.Message);

            m.SetContent(r.ToString());
            sender.Send(m);
        }
        public void Configure()
        {
            services.AddScoped(typeof(IChatState <>), typeof(EchoState <>));

            var provider = services.BuildServiceProvider();

            botHandler = provider.GetRequiredService <BotHandler <ChatActivity> >();
            connector  = provider.GetRequiredService <IConnector <ChatActivity> >() as MockConnector <ChatActivity>;
        }
Example #12
0
        public void Setup()
        {
            services.AddTelegramCore("634874153:AAHzU5D63iP8a_3Jn_PCjO6NlDcx9_cncak");

            services.AddScoped(typeof(IChatState <>), typeof(EchoState <>));

            var provider = services.BuildServiceProvider();

            botHandler = provider.GetRequiredService <BotHandler <TelegramActivity> >();
        }
Example #13
0
        public void CanHandleBotMessages()
        {
            var handler = new BotHandler();

            var result = handler.CanHandle(new BotChanged { Type = EventType.BotChanged });
            Assert.True(result);

            result = handler.CanHandle(new BotAdded { Type = EventType.BotAdded });
            Assert.True(result);
        }
Example #14
0
        public override void OnUserConnect(ClientInfo client)
        {
            Message m = new Message("Test Bot", MessageType.Message);

            m.SetColor(NColor.Blue);
            m.SetContent("Welcome " + client.Name);
            BotHandler.TRequestClients().SendToAll(m, new List <ClientInfo>()
            {
                client
            });
        }
Example #15
0
 private static bool Prefix(BotHandler __instance)
 {
     if (MainGameMode.Instance.started)
     {
         for (int i = 0; i < __instance.êóæìíîìñäîí.Length; i++)
         {
             __instance.êóæìíîìñäîí[i].GetComponent <BotPlayer>().åñîïòíæêêåî.îëæêéïåðæìå("Unload", óëððîêðëóêó.îéäåéçèïïñí, new object[0]);
         }
         return(false);
     }
     return(true);
 }
Example #16
0
        public async Task MainAsync(string[] args)
        {
            if (args.Length == 0)
            {
                botType = BotType.Experimental;
            }
            else
            {
                botType = (BotType)int.Parse(args[0]);
            }
            await Library.LoadKeys();

            BotHandler = new BotHandler();
            random     = new Random();
            await Boot.Load(BotHandler);

            handler = new Handler();

            Library.rOpts.RetryMode = RetryMode.RetryRatelimit;
            Library.rOpts.Timeout   = null;

            IMessages = new List <InteractMessage>();

            client                  = new DiscordSocketClient();
            client.Log             += Log;
            client.MessageReceived += MessageReceived;

            client.ReactionAdded   += Client_ReactionAdded;
            client.ReactionRemoved += Client_ReactionRemoved;
            client.Ready           += Client_Ready;

            commands = new CommandService();
            services = new ServiceCollection().BuildServiceProvider();

            await InstallCommands();

            string token = "";

            switch (botType)
            {
            case BotType.Live: token = Library.API_KEYS["MrDestructoid"]; break;

            case BotType.Experimental: token = Library.API_KEYS["MrRestructoid"]; break;
            }

            await client.LoginAsync(TokenType.Bot, token);

            await client.StartAsync();

            timer1s = new Timer(async(object o) => await Events.OnTimerDown(o), null, 0, 1000);
            await Task.Delay(-1);
        }
Example #17
0
        public async Task InitializeEarlyAsync(IServiceProvider services)
        {
            await ConfigHandler.InitializeAsync();

            await CommandHandler.InitializeAsync(this, services);

            await TextHandler.InitializeAsync(ConfigHandler.GetSwearString());

            await ShipHandler.InitializeAsync();

            await BotHandler.InitializeAsync();

            await DatabaseHandler.InitializeAsync();
        }
Example #18
0
 public MainHandler(DiscordSocketClient Discord)
 {
     guilds            = new Dictionary <ulong, GuildHandler>();
     Client            = Discord;
     ConfigHandler     = new Handlers.ConfigHandler();
     CommandHandler    = new CommandHandler();
     PermissionHandler = new PermissionHandler(this);
     TextHandler       = new TextHandler(this);
     ShipHandler       = new ShipHandler(this);
     BotHandler        = new BotHandler();
     forumUpdater      = new ForumUpdater(this);
     ExceptionHandler  = new ExceptionHandler(this);
     DatabaseHandler   = new Handlers.DatabaseHandler(this);
 }
Example #19
0
 static void Main(string[] args)
 {
     while (true)
     {
         Bot testBot = BotHandler.CreateBot("localhost", 49186, "Bot42_CSharp");
         testBot.AddJoinQueue("#Bot42");
         testBot.AddJoinQueue("#Bot42_CSharp");
         testBot.AddJoinQueue("#botz");
         testBot.AddJoinQueue("#CSharp");
         testBot.Connect();
     }
     //Console.WriteLine("Bot terminated, press any key to exit...");
     Console.Read();
 }
Example #20
0
        public void CanHandleBotMessages()
        {
            var handler = new BotHandler();

            var result = handler.CanHandle(new BotChanged {
                Type = EventType.BotChanged
            });

            Assert.True(result);

            result = handler.CanHandle(new BotAdded {
                Type = EventType.BotAdded
            });
            Assert.True(result);
        }
Example #21
0
        public void Init()
        {
            services.AddScoped(typeof(IChatState <>), typeof(TestState1 <>));
            services.AddScoped(typeof(TestState1 <>));
            services.AddScoped(typeof(TestState2 <>));
            services.AddScoped(typeof(TestState3 <>));

            var provider = services.BuildServiceProvider();

            botHandler = provider.GetRequiredService <BotHandler <ChatActivity> >();
            connector  = provider.GetRequiredService <IConnector <ChatActivity> >() as MockConnector <ChatActivity>;

            state1 = provider.GetRequiredService <TestState1 <TextActivity> >();
            state2 = provider.GetRequiredService <TestState2 <TextActivity> >();
            state3 = provider.GetRequiredService <TestState3 <TextActivity> >();
        }
Example #22
0
        public async Task Close()
        {
            foreach (ulong id in guilds.Keys)
            {
                await guilds[id].Close();
            }
            await ConfigHandler.Close();

            await CommandHandler.Close();

            await TextHandler.Close();

            await ShipHandler.Close();

            await BotHandler.Close();

            await DatabaseHandler.Close();
        }
Example #23
0
        public async Task <IActionResult> StopBot(int Id)
        {
            try
            {
                Models.User user = await db.Users.Include(x => x.Bots).ThenInclude(x => x.BotQueries)
                                   .ThenInclude(x => x.Response).FirstAsync(x => x.Name == User.Identity.Name);

                TelegramBot model;
                model           = user.Bots.First(x => x.Id == Id);
                model.IsStarted = false;
                db.Bots.Update(model);
                await db.SaveChangesAsync();

                BotHandler.StopHandle(model);
                return(new NoContentResult());
            }
            catch
            {
                return(View("Error", new ErrorModel("Bad bot index")));
            }
        }
Example #24
0
        static void Main(string[] args)
        {
            using (StreamReader sr = new StreamReader("token.txt"))
            {
                token = sr.ReadLine();
            }
            client                  = new TelegramBotClient(token);
            client.OnMessage       += OnMessage;
            client.OnCallbackQuery += OnCallback;
            List <BotUser> users = new List <BotUser>();

            if (System.IO.File.Exists("users.dat"))
            {
                using (FileStream fs = new FileStream("users.dat", FileMode.Open))
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    users = (List <BotUser>)bf.Deserialize(fs);
                }
            }
            handler = new BotHandler(client, users);
            client.StartReceiving();
            Console.ReadLine();
        }
Example #25
0
        async Task ICallbackQueryCommand.ExecuteAsync(CallbackQuery callbackQuery, BotUser user)
        {
            int    page        = Convert.ToInt32(callbackQuery.Data.Substring(1, callbackQuery.Data.IndexOf('.') - 1));
            string accountName = callbackQuery.Data.Length != (callbackQuery.Data.IndexOf('.') + 1) ?
                                 callbackQuery.Data.Substring(callbackQuery.Data.IndexOf('.') + 1) : null;
            int accountCount = .GetAccountCount(callbackQuery.From.Id, accountName);

            if (accountCount != 0)
            {
                await.ShowPage(callbackQuery.From.Id, accountName, page,
                               .GetPageCount(accountCount),
                               user.Lang, callbackQuery.Message.MessageId);
                await bot.Client.AnswerCallbackQueryAsync(callbackQuery.Id);
            }
            else
            {
                await bot.Client.AnswerCallbackQueryAsync(callbackQuery.Id,
                                                          Localization.GetMessage("SearchAgain", user.Lang), showAlert : true);

                await BotHandler.TryDeleteMessageAsync(
                    callbackQuery.Message.Chat.Id, callbackQuery.Message.MessageId);
            }
        }
Example #26
0
        public async void HandlesValidBotAdded()
        {
            var bots = new List <BotModel>
            {
                new BotModel {
                    Id = "BOTID1"
                },
                new BotModel {
                    Id = "BOTID2"
                }
            };

            var mockState = new Mock <IBotState>();

            mockState.Setup(s => s.Bots)
            .Returns(bots)
            .Verifiable();

            var message = new BotAdded
            {
                Type = EventType.BotAdded,
                Bot  = new BotModel {
                    Id = "BOTID3"
                }
            };

            var handler = new BotHandler();

            handler.BotState = mockState.Object;

            var result = await handler.HandleMessageAsync(message);

            mockState.Verify();
            Assert.Equal(3, bots.Count);
            Assert.Equal("BOTID3", bots.Last().Id);
        }
Example #27
0
        static void Main(string[] args)
        {
            clients = new Dictionary <string, ClientInfo>();
            Rooms   = new Dictionary <string, Room>();

            Room m = new Room("Main", 0);

            Rooms[m.GUID] = m;
            m             = new Room("Extra", 1);
            Rooms[m.GUID] = m;

            #region Config loading code
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Loading Configuration...");
            XmlDocument settings = new XmlDocument();
            settings.Load("config.xml");
            XmlNode     roomsNode = settings.SelectSingleNode("Config/Rooms");
            XmlNodeList rooms     = roomsNode.SelectNodes("Room");
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            if (roomsNode.Attributes[0].InnerText == "true")
            {
                Console.WriteLine("Overriden Default Room(s)");
                Rooms = new Dictionary <string, Room>();
            }
            foreach (XmlNode node in rooms)
            {
                try
                {
                    XmlAttributeCollection attr = node.Attributes;
                    Console.WriteLine("Generating Room " + node.InnerText);
                    m             = new Room(node.InnerText, int.Parse(attr[0].InnerText), int.Parse(attr[1].InnerText), int.Parse(attr[2].InnerText));
                    Rooms[m.GUID] = m;
                }
                catch
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Failed to Generate Room " + node.InnerText);
                    Console.ForegroundColor = ConsoleColor.DarkCyan;
                }
            }
            string webPort = settings.SelectSingleNode("Config/GeneralSettings/WebPort").InnerText;
            if (webPort != "")
            {
                if (!int.TryParse(webPort, out WebPort))
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Failed to read WebPort, reverting to default port (8911)");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.DarkCyan;
                    Console.WriteLine("Set WebPort to " + WebPort);
                }
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.DarkCyan;
                Console.WriteLine("WebPort set to default (8911)");
            }
            string desktopPort = settings.SelectSingleNode("Config/GeneralSettings/DesktopPort").InnerText;
            if (desktopPort != "")
            {
                if (!int.TryParse(desktopPort, out DesktopPort))
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Failed to read DesktopPort, reverting to default port (8910)");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.DarkCyan;
                    Console.WriteLine("Set DesktopPort to " + DesktopPort);
                }
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.DarkCyan;
                Console.WriteLine("DesktopPort set to default (8910)");
            }
            string ip = settings.SelectSingleNode("Config/GeneralSettings/ServerIp").InnerText;
            if (ip != "")
            {
                if (!IPAddress.TryParse(ip, out iPAddress))
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Failed to read ServerIp, reverting to default (Automatic " + GetLocalIPAddress() + ")");
                    iPAddress = IPAddress.Parse(GetLocalIPAddress());
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.DarkCyan;
                    Console.WriteLine("Set ServerIp to " + iPAddress.ToString());
                }
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.DarkCyan;
                Console.WriteLine("Automaticly setting ip to " + GetLocalIPAddress());
                iPAddress = IPAddress.Parse(GetLocalIPAddress());
            }
            try
            {
                if (!bool.TryParse(settings.SelectSingleNode("Config/GeneralSettings/WebPort").Attributes[0].InnerText, out WebActive))
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Failed to read WebPort active attribute");
                }
                if (!bool.TryParse(settings.SelectSingleNode("Config/GeneralSettings/DesktopPort").Attributes[0].InnerText, out DesktopActive))
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Failed to read WebPort active attribute");
                }
            }
            catch
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Failed to read active states");
            }
            string sslPath = settings.SelectSingleNode("Config/GeneralSettings/PfxCertificate").InnerText;
            if (sslPath != "")
            {
                try
                {
                    X509 = new X509Certificate2(sslPath, settings.SelectSingleNode("Config/GeneralSettings/PfxCertificate").Attributes[0].InnerText);
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("Loaded Pfx Certificate, starting ssl");
                }
                catch
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Failed to load Pfx Certificate, reverting to non-ssl");
                }
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("No Pfx Certificate provided, reverting to non-ssl");
            }

            if (Rooms.Count == 0)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[Server not started] Please add atleast one room to the server or set overrideDefault to false. Press enter to quit.");
                Console.ReadLine();
                return;
            }
            if (!DesktopActive && !WebActive)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[Server not started] Please set atleast one server to active (Web or Desktop). Press enter to quit.");
                Console.ReadLine();
                return;
            }
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Complete!");
            #endregion

            Bots    = new List <dynamic>();
            handler = new BotHandler();
            handler.OnReqestClients += () => { return(clients); };
            handler.OnUpdateClient  += (c) => { clients[c.GUID] = c; };
            handler.OnUpdateRoom    += (r) => { Rooms[r.GUID] = r; };

            startup = DateTime.UtcNow;

            #region Bot Loader
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Loading Bots...");
            foreach (string dll in Directory.GetDirectories(@"Bots"))
            {
                string path = Directory.GetParent(dll).FullName;
                path = path + @"\" + new DirectoryInfo(dll).Name + @"\" + new DirectoryInfo(dll).Name + ".dll";
                if (!File.Exists(path))
                {
                    continue;
                }

                if (!File.Exists(path.Replace(".dll", ".pdb")))
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("No .pdb file found for \n" + path);
                    Console.WriteLine("Exact location of error is impossible to determine");
                    Console.ForegroundColor = ConsoleColor.White;
                }
                Assembly DLL   = Assembly.LoadFrom(path);
                Type[]   types = DLL.GetExportedTypes();
                foreach (Type type in types)
                {
                    Bot bot = (Bot)Attribute.GetCustomAttribute(type, typeof(Bot));
                    if (bot != null)
                    {
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine($"{bot.Name} By {bot.Creator}");
                        Console.ForegroundColor = ConsoleColor.Gray;
                        Console.WriteLine(bot.Desc);
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine($"Version: {bot.Version}");
                        Console.ForegroundColor = ConsoleColor.White;
                        dynamic c = Activator.CreateInstance(type);
                        try
                        {
                            try
                            {
                                c.Init(handler);
                                Bots.Add(c);
                            }
                            catch (RuntimeBinderException e)
                            {
                                Console.ForegroundColor = ConsoleColor.DarkRed;
                                Console.WriteLine("Failed to load " + path);
                                Console.WriteLine("(" + e.Message + ") thrown in " + e.TargetSite.Name + " at line " + GetLineNumber(e));
                                Console.ForegroundColor = ConsoleColor.White;
                                continue;
                            }
                            catch (Exception e)
                            {
                                Console.ForegroundColor = ConsoleColor.DarkRed;
                                Console.WriteLine("Failed to load " + path);
                                Console.WriteLine("(" + e.Message + ") thrown in " + e.TargetSite.Name + " at line " + GetLineNumber(e));
                                Console.ForegroundColor = ConsoleColor.White;
                                continue;
                            }
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine("Sucessfully loaded!");
                            Console.ForegroundColor = ConsoleColor.White;
                        }
                        catch (Exception e)
                        {
                            Console.ForegroundColor = ConsoleColor.DarkRed;
                            Console.WriteLine("Failed to load " + path);
                            Console.WriteLine("Method Init Missing or Incorrect or other error has occured");
                            Console.WriteLine("(" + e.Message + ") thrown in " + e.TargetSite.Name + " at line " + GetLineNumber(e));
                            Console.ForegroundColor = ConsoleColor.White;
                            continue;
                        }
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.DarkMagenta;
                        Console.WriteLine("Failed to load " + path);
                        Console.WriteLine("File doesnt contain Bot Attribute/Code");
                        Console.ForegroundColor = ConsoleColor.White;
                    }
                }
            }
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Complete!");
            Console.ForegroundColor = ConsoleColor.White;
            #endregion

            ListenerState WebState     = ListenerState.Waiting;
            ListenerState DesktopState = ListenerState.Waiting;

            web = new Thread(() => WebListener(ref WebState))
            {
                IsBackground = true
            };

            desktop = new Thread(() => ClientListener(ref DesktopState))
            {
                IsBackground = true
            };

            if (WebActive)
            {
                web.Start();
            }

            if (DesktopActive)
            {
                desktop.Start();
            }

            string json = Rooms.SerializeRooms();
            Rooms = json.DeserializeRooms();

            Console.WriteLine("Type quit to stop server or help for a list of commands");
            while (true)
            {
                string[] command = Console.ReadLine().Split(' ');
                if (command[0] == "quit")
                {
                    break;
                }
                else if (command[0] == "log")
                {
                    if (command[1] == "users")
                    {
                        Console.WriteLine("Users:");
                        foreach (KeyValuePair <string, ClientInfo> client in clients)
                        {
                            Console.WriteLine(client.ToString());
                        }
                    }
                    else if (command[1] == "threads")
                    {
                        Console.WriteLine("Web: ");
                        Console.WriteLine("State -> " + WebState.ToString());
                        Console.WriteLine("Status -> " + web.ThreadState.ToString());

                        Console.WriteLine("Desktop: ");
                        Console.WriteLine("State -> " + DesktopState.ToString());
                        Console.WriteLine("Status -> " + desktop.ThreadState.ToString());
                    }

                    if (command[1] == "rooms")
                    {
                        Console.WriteLine("Rooms:");
                        foreach (KeyValuePair <string, Room> room in Rooms)
                        {
                            Console.WriteLine(room.Value.ToString());
                        }
                    }
                }
                else if (command[0] == "restart")
                {
                    if (command[1] == "web")
                    {
                        WebState = ListenerState.Quiting;
                        while (web.IsAlive)
                        {
                            ;
                        }

                        WebState = ListenerState.Waiting;
                        web      = new Thread(() => WebListener(ref WebState))
                        {
                            IsBackground = true
                        };
                        web.Start();
                        Console.WriteLine("Web Restarted");
                    }
                    else if (command[1] == "desktop")
                    {
                        DesktopState = ListenerState.Quiting;
                        while (desktop.IsAlive)
                        {
                            ;
                        }

                        DesktopState = ListenerState.Waiting;
                        desktop      = new Thread(() => ClientListener(ref DesktopState))
                        {
                            IsBackground = true
                        };
                        desktop.Start();
                        Console.WriteLine("Desktop Restarted");
                    }
                    else if (command[1] == "both")
                    {
                        WebState = ListenerState.Quiting;
                        while (web.IsAlive)
                        {
                            ;
                        }

                        WebState = ListenerState.Waiting;
                        web      = new Thread(() => WebListener(ref WebState))
                        {
                            IsBackground = true
                        };
                        web.Start();
                        Console.WriteLine("Web Restarted");

                        DesktopState = ListenerState.Quiting;
                        while (desktop.IsAlive)
                        {
                            ;
                        }

                        DesktopState = ListenerState.Waiting;
                        desktop      = new Thread(() => ClientListener(ref DesktopState))
                        {
                            IsBackground = true
                        };
                        desktop.Start();
                        Console.WriteLine("Desktop Restarted");
                    }
                }
                else if (command[0] == "help")
                {
                    Console.WriteLine("Coming soon");
                }
            }
        }
Example #28
0
        static void Main(string[] args)
        {
            Logger.SetupLogger();

            Logger.Log("Chino-chan handler loading...");
            ConfigEditor = new ConfigEditor();

loadConfig:
            Logger.Log("Loading config...");
            Config = LoadConfig(ConfigPath);
            Logger.Log("Config loaded!", Color: ConsoleColor.Green);
            if (Config.IsNewConfig())
            {
                Config.SaveConfig();
                Logger.Log("Your config is outdated! Please check your configuration to avoid future crashes, and press enter!", Color: ConsoleColor.Cyan);
                ConfigEditor.FillEmpty(Config);
                goto loadConfig;
            }

            Logger.Log("Checking libraries...");
            if (!CheckLibraries())
            {
                Logger.Log("Please install the libraries / runtimes mentioned above! Press enter to exit!", Color: ConsoleColor.Red);
                Console.ReadLine();
                Environment.Exit(1);
            }
            Logger.Log("Checking libraries done!", Color: ConsoleColor.Green);

            Logger.Log("Initializing Webhook manager...");
            Manager = new WebhookManager(Config);
            Logger.Log("Webhook manager initialized!", Color: ConsoleColor.Green);

            Logger.Log("Initializing Bot handler...");
            BotHandler = new BotHandler(Config);
            Logger.Log("Handler initialized!", Color: ConsoleColor.Green);

            Logger.Log("Initializing updater...");
            Updater    = new Updater(Config);
            BotUpdate += () =>
            {
                Updater.Update(true);
            };
            HandlerUpdate += () =>
            {
                Updater.Update(false);
            };
            Logger.Log("Updater initialized!", Color: ConsoleColor.Green);

            Logger.Log("Initializing Remote Console...");
            RemoteConsole = new RemoteConsole(Config);
            Logger.Log("Remote Console initialized!", Color: ConsoleColor.Green);


            Logger.Log("Initializing menu...");
            MenuHandler = new MenuHandler();
            MenuHandler.Add("Start", () =>
            {
                BotHandler.Start();
                ShowMenu = false;
            });
            MenuHandler.Add("Edit Config", () =>
            {
                ConfigEditor.EditAll(Config);
                Logger.Log("Restart the program for the changes to take effect.");
            });
            MenuHandler.Add("Exit", () =>
            {
                BotHandler.Quit();
                Environment.Exit(0);
            });
            Console.Clear();

            Logger.Log("Starting Webhook manager...");
            if (Manager.Start())
            {
                Logger.Log("Webhook manager successfully started!", Color: ConsoleColor.Green);
                Console.Clear();
            }
            RemoteConsole.Start();
            Console.WriteLine();
            HandleCommands();
        }
Example #29
0
        public async Task AutomaticGame(CommandContext ctx, Room room)
        {
            //calls the Room command that starts a game / tries to start the Room
            bool successfulStart = await room.StartGame(ctx);

            if (!successfulStart)
            {
                await ctx.RespondAsync(new DiscordEmbedBuilder
                {
                    Title = "Something Went Wrong",
                    Color = DiscordColor.Red
                }).ConfigureAwait(false);

                return;
            }

            await ctx.RespondAsync(new DiscordEmbedBuilder
            {
                Title = "Game Started Successfully",
                Color = DiscordColor.Green
            }).ConfigureAwait(false);

            do
            {
                //send shops
                await room.gameHandler.SendShopsAsync(ctx).ConfigureAwait(false);

                //show pairs
                await PairsList(ctx);

                //make a msg that updates on ready
                await room.gameHandler.SendNewInteractivePlayerList(ctx);

                //wait for all players to ready
                await WaitToProceedToFights(room);

                //do end of turn
                foreach (var player in room.gameHandler.players)
                {
                    await player.Value.TriggerEndOfTurn(room.gameHandler, player.Key, room.gameHandler.pairsHandler.opponents[player.Key], ctx);
                }

                //do the fights
                await DoAllFights(ctx);

                if (room.gameHandler.AlivePlayers > 1)
                {
                    await NextRound(ctx);
                }
            } while (room.gameHandler.AlivePlayers > 1);

            ulong winner = 0;

            foreach (var player in room.gameHandler.players)
            {
                if (player.Value.lives > 0)
                {
                    winner = player.Key;
                    break;
                }
            }

            if (winner == 0)
            {
                return;
            }

            await room.gameHandler.outputChannel.SendMessageAsync(new DiscordEmbedBuilder {
                Title = $"{room.nicknames[winner]} Is The Winner!",
                Color = DiscordColor.Gold
            }).ConfigureAwait(false);

            foreach (var player in room.gameHandler.players)
            {
                BotHandler.SetUserState(player.Key, UserState.WaitingInRoom);

                if (room.hostId == player.Key)
                {
                    BotHandler.SetUserState(player.Key, UserState.HostingARoom);
                }
            }
        }
Example #30
0
 public DoController(BotHandler botHandler)
 {
     _botHandler = botHandler;
 }
        public static async Task SetName(CommandContext ctx)
        {
            await ctx.RespondAsync(new DiscordEmbedBuilder {
                Title = "Choose A Name For Your Mech",
                Color = DiscordColor.Azure
            }).ConfigureAwait(false);

            var interactivity = ctx.Client.GetInteractivity();

            Room room = BotHandler.Rooms.GetUserRoom(ctx.User.Id);

            while (true)
            {
                var input = await interactivity.WaitForMessageAsync(x => x.Author.Id == ctx.User.Id && x.Channel.Id == ctx.Channel.Id).ConfigureAwait(false);

                if (input.TimedOut)
                {
                    await ctx.RespondAsync(new DiscordEmbedBuilder
                    {
                        Title       = "Interaction Timed Out",
                        Description = "A default name has been applied, you can change it using \"mech rename\"",
                        Color       = DiscordColor.Gold
                    }).ConfigureAwait(false);

                    //asign default name

                    string defaultName = ctx.User.Username;
                    bool   takenName   = false;

                    foreach (var player in room.nicknames)
                    {
                        if (player.Value.Equals(defaultName))
                        {
                            //not good
                            takenName = true;
                            break;
                        }
                    }

                    if (!takenName)
                    {
                        room.nicknames[ctx.User.Id] = defaultName;
                        return;
                    }

                    int extra = 1;
                    while (true)
                    {
                        takenName = false;
                        foreach (var player in room.nicknames)
                        {
                            if (player.Value.Equals($"{defaultName}{extra}"))
                            {
                                extra++;
                                takenName = true;
                                break;
                            }
                        }

                        if (!takenName)
                        {
                            room.nicknames[ctx.User.Id] = $"{defaultName}{extra}";
                            return;
                        }
                    }
                }
                else
                {
                    //check for valid name and not an already used name
                    string filterMsg;
                    string name = input.Result.Content;
                    bool   res  = BotHandler.FilterName(ref name, out filterMsg, 3, 20);

                    if (res)
                    {
                        bool takenName = false;

                        foreach (var player in room.gameHandler.players)
                        {
                            if (player.Value.name == name)
                            {
                                //not good
                                takenName = true;
                                break;
                            }
                        }

                        if (!takenName)
                        {
                            await ctx.RespondAsync(new DiscordEmbedBuilder
                            {
                                Title       = "Named Assigned Successfully",
                                Description = $"Your Mech is now called \"{name}\".",
                                Color       = DiscordColor.Green
                            }).ConfigureAwait(false);

                            room.nicknames[ctx.User.Id] = name;
                            return;
                        }
                        else
                        {
                            await ctx.RespondAsync(new DiscordEmbedBuilder
                            {
                                Title       = "Mech Name Already Taken",
                                Description = "Please choose another name.",
                                Color       = DiscordColor.Red
                            }).ConfigureAwait(false);
                        }
                    }
                    else
                    {
                        //do something
                        await ctx.RespondAsync(new DiscordEmbedBuilder
                        {
                            Title       = "Invalid Name",
                            Description = filterMsg,
                            Color       = DiscordColor.Red
                        }).ConfigureAwait(false);
                    }
                }
            }
        }
Example #32
0
        public async Task CreateRoom(CommandContext ctx)
        {
            bool result = BotHandler.Rooms.CreateRoom(ctx);

            if (!result)
            {
                //something went wrong
                await ctx.RespondAsync(new DiscordEmbedBuilder
                {
                    Title       = "Unable to Create a Room",
                    Description = "You don't meet some of the conditions required to make a room.",
                    Color       = DiscordColor.Red
                }).ConfigureAwait(false);
            }
            else
            {
                //room created successfully
                await ctx.RespondAsync(new DiscordEmbedBuilder
                {
                    Title = "Room Created Successfully",
                    Color = DiscordColor.Green
                }).ConfigureAwait(false);

                await ctx.RespondAsync(new DiscordEmbedBuilder {
                    Title       = "Name Your Room",
                    Description = "Type the name in the chat",
                    Color       = DiscordColor.Azure
                }).ConfigureAwait(false);

                var interactivity = ctx.Client.GetInteractivity();

                while (true)
                {
                    var feedback = await interactivity.WaitForMessageAsync(x => x.Channel.Id == ctx.Channel.Id &&
                                                                           x.Author.Id == ctx.User.Id).ConfigureAwait(false);

                    if (feedback.TimedOut)
                    {
                        //timed out
                        await ctx.RespondAsync(new DiscordEmbedBuilder
                        {
                            Title       = "Interaction Timed Out",
                            Description = "A default name has been applied, you can change it using \"room rename\"",
                            Color       = DiscordColor.Gold
                        }).ConfigureAwait(false);

                        break;
                    }

                    string filterMsg;
                    string name = feedback.Result.Content;
                    bool   res  = BotHandler.FilterName(ref name, out filterMsg, 3, 40);

                    if (res)
                    {
                        if (BotHandler.Rooms.IsNameAvailable(ctx, name))
                        {
                            //successfully
                            //await feedback.Result.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":+1:")).ConfigureAwait(false);
                            await ctx.RespondAsync(new DiscordEmbedBuilder
                            {
                                Title       = "Named Assigned Successfully",
                                Description = $"Your room is now called \"{name}\".",
                                Color       = DiscordColor.Green
                            }).ConfigureAwait(false);

                            BotHandler.openRooms[ctx.User.Id].roomName = name;
                            break;
                        }
                        else
                        {
                            //there's already a room with that name
                            await ctx.RespondAsync(new DiscordEmbedBuilder
                            {
                                Title       = "Room Name Already Taken",
                                Description = "Please choose another name.",
                                Color       = DiscordColor.Red
                            }).ConfigureAwait(false);
                        }
                    }
                    else
                    {
                        //await feedback.Result.CreateReactionAsync(DiscordEmoji.FromName(ctx.Client, ":no_entry_sign:")).ConfigureAwait(false);
                        await ctx.RespondAsync(new DiscordEmbedBuilder {
                            Title       = "Invalid Name",
                            Description = filterMsg,
                            Color       = DiscordColor.Red
                        }).ConfigureAwait(false);
                    }
                }

                await MechCustomizationCommands.SetName(ctx);
            }
        }
Example #33
0
 public MyBot(BotHandler bot) : base(bot)
 {
     CommandHandler.CreateCommand("ping", Ping);
     CommandHandler.CreateCommand("room", Users);
 }