Exemplo n.º 1
0
        public void BotJoinsWithRespondToSelfEnabled()
        {
            JoinHandlerConfig joinHandlerConfig = new JoinHandlerConfig
            {
                JoinAction    = this.JoinFunction,
                RespondToSelf = true
            };
            JoinHandler uut = new JoinHandler(joinHandlerConfig);

            string ircString = TestHelpers.ConstructIrcString(
                this.ircConfig.Nick,
                JoinHandler.IrcCommand,
                this.ircConfig.Channels[0],
                string.Empty
                );

            uut.HandleEvent(this.ConstructArgs(ircString));

            Assert.IsNotNull(this.responseReceived);

            // Channels should match.
            Assert.AreEqual(this.ircConfig.Channels[0], this.responseReceived.Channel);

            // Nicks should match.
            Assert.AreEqual(this.ircConfig.Nick, this.responseReceived.User);
        }
Exemplo n.º 2
0
 public void TestSetup()
 {
     this.ircConfig   = TestHelpers.GetTestIrcConfig();
     ircConnection    = new MockIrcConnection(this.ircConfig);
     responseReceived = null;
     this.uut         = new JoinHandler(JoinFunction);
 }
Exemplo n.º 3
0
        // ---------------- Functions ----------------

        public void Init(PluginInitor initor)
        {
            this.chaskisEventCreator = initor.ChaskisEventCreator;
            this.eventSender         = initor.ChaskisEventSender;
            this.ircConfig           = initor.IrcConfig;
            this.logger = initor.Log;

            this.pluginDir = Path.Combine(
                initor.ChaskisConfigPluginRoot,
                "NewVersionNotifier"
                );

            string configPath = Path.Combine(
                this.pluginDir,
                "NewVersionNotifierConfig.xml"
                );

            this.config = XmlLoader.LoadConfig(configPath);

            this.cachedFilePath = Path.Combine(
                this.pluginDir,
                cacheFileName
                );

            if (File.Exists(this.cachedFilePath) == false)
            {
                this.cachedVersion = string.Empty;
            }
            else
            {
                string[] lines = File.ReadAllLines(this.cachedFilePath);
                if (lines.Length == 0)
                {
                    this.cachedVersion = string.Empty;
                }
                else
                {
                    this.cachedVersion = lines[0].Trim();
                }
            }

            ChaskisEventHandler eventHandler = this.chaskisEventCreator.CreatePluginEventHandler(
                "chaskis",
                this.HandleChaskisEvent
                );

            this.ircHandlers.Add(eventHandler);

            JoinHandlerConfig joinHandlerConfig = new JoinHandlerConfig
            {
                JoinAction    = this.OnJoinChannel,
                RespondToSelf = true
            };
            JoinHandler joinHandler = new JoinHandler(joinHandlerConfig);

            this.ircHandlers.Add(joinHandler);
        }
Exemplo n.º 4
0
        public void Parse(SocketMessage message)
        {
            _tokens.Clear();
            string[] contentWords = message.Content.Split(" ");

            #region create tokens
            for (int i = 0; i < contentWords.Length; i++)
            {
                var tokenString = contentWords[i].ToLower();


                if (tokenString == "join")
                {
                    _tokens.Add(new PreGameToken(tokenString, PreGameToken.TokenType.Join));
                }
                if (tokenString == "create")
                {
                    _tokens.Add(new PreGameToken(tokenString, PreGameToken.TokenType.Create));
                }
                if (tokenString == "chext")
                {
                    _tokens.Add(new PreGameToken(tokenString, PreGameToken.TokenType.Chext));
                }
                if (tokenString == "white" || tokenString == "black")
                {
                    _tokens.Add(new PreGameToken(tokenString, PreGameToken.TokenType.Side));
                }
            }
            #endregion

            #region trigger events depending on grammer

            if (_tokens.Count == 1)
            {
                if (_tokens[0].Type == PreGameToken.TokenType.Join)
                {
                    JoinHandler?.Invoke(new JoinEvent(message.Author, message.Channel));
                }
            }

            if (_tokens.Count == 2)
            {
                if (_tokens[0].Type == PreGameToken.TokenType.Create && _tokens[1].Type == PreGameToken.TokenType.Chext)
                {
                    GameProposalHandler?.Invoke(message.Channel, message.Author);
                }

                if (_tokens[0].Type == PreGameToken.TokenType.Join && _tokens[1].Type == PreGameToken.TokenType.Side)
                {
                    JoinSideHandler?.Invoke(new JoinSideEvent(message.Author, message.Channel, _tokens[1].Value == "white"));
                }
            }
            #endregion
        }
Exemplo n.º 5
0
        public void TestSetup()
        {
            this.ircConfig        = TestHelpers.GetTestIrcConfig();
            this.ircWriter        = new Mock <IIrcWriter>(MockBehavior.Strict);
            this.responseReceived = null;

            JoinHandlerConfig joinHandlerConfig = new JoinHandlerConfig
            {
                JoinAction = this.JoinFunction
            };

            this.uut = new JoinHandler(joinHandlerConfig);
        }
Exemplo n.º 6
0
        public IClient SingleJoinTest(string userName = "******", string nickName = "unispy", string channelName = "#GSP!room!test")
        {
            var session     = SingleLoginTest(userName, nickName);
            var joinReq     = new JoinRequest($"JOIN {channelName}");
            var joinHandler = new JoinHandler(session, joinReq);

            // we know the endpoint object is not set, so System.NullReferenceException will be thrown
            joinHandler.Handle();
            Assert.Single(_client.Info.JoinedChannels);
            Assert.True(_client.Info.JoinedChannels.ContainsKey(channelName));
            Assert.True(_client.Info.IsJoinedChannel(channelName));
            return(session);
        }
Exemplo n.º 7
0
        public void TestJoinAddName()
        {
            AddChatUsers("test", "a", "b", "c");

            Caller.join = new Action <JoinAction>(res => { });
            var joinHandler = new JoinHandler();
            var msg         = new MsgEventArgs {
                Command = "JOIN", Data = new[] { "test" }, Meta = "d!b@c"
            };

            joinHandler.Msg(Talker, Caller, msg);
            CollectionAssert.AreEqual(new[] { "a", "b", "c", "d" },
                                      Talker.Chats["test"].Users.Select(u => u.IrcUser.Nick).ToArray());
        }
Exemplo n.º 8
0
        public void TestJoin()
        {
            var joinHandler = new JoinHandler();
            var msg         = new MsgEventArgs {
                Command = "JOIN", Data = new[] { "test" }, Meta = "a!b@c"
            };
            var visited = false;

            Caller.join = new Action <JoinAction>(res =>
            {
                Assert.AreEqual("test", res.ChatNames.First());
                var user = res.User;
                Assert.AreEqual("a", user.Nick);
                Assert.AreEqual("b", user.Name);
                Assert.AreEqual("c", user.Host);
                visited = true;
            });
            joinHandler.Msg(Talker, Caller, msg);
            Assert.IsTrue(visited);
        }
Exemplo n.º 9
0
        public override void Install(ModuleManager manager)
        {
            manager.CreateCommands("", cgb =>
            {
                cgb.AddCheck(PermissionChecker.Instance);

                commands.ForEach(cmd => cmd.Init(cgb));
            });

            MessageHandler handler = new MessageHandler(this);

            manager.MessageReceived += handler.messageReceived;
            manager.MessageDeleted  += handler.messageDeleted;
            manager.MessageUpdated  += handler.messageUpdated;

            JoinHandler joinHandler = new JoinHandler();

            manager.UserJoined += joinHandler.serverJoined;

            LevelHandler levelHandler = new LevelHandler();

            LevelChanged += levelHandler.levelChanged;
        }
Exemplo n.º 10
0
    public async Task MainAsync()
    {
        //initialize and connect client
        _client      = new DiscordSocketClient();
        _client.Log += Log;

        //get config
        _config = new Config();
        String json_str;

        try {
            json_str = File.ReadAllText("data/config.json");
            _config  = JsonSerializer.Deserialize <Config>(json_str);
        } catch (Exception e) {
            if (e is FileNotFoundException)
            {
                Console.WriteLine("ERROR: data/config.json not found. Creating new config.json file. Please set BotToken field.");
                File.WriteAllText("data/config.json", JsonSerializer.Serialize(_config));
            }
            else if (e is JsonException)
            {
                Console.WriteLine("ERROR: data/config.json: " + e.Message);
            }
            else
            {
                Console.WriteLine("ERROR: exception thrown when trying to load data/config.json: ");
                throw;
            }
            return;
        }

        if (_config.CommandEnabled || _config.RoleEnabled)
        {
            Console.WriteLine("Setting up handler(s) in 4 seconds.");
        }

        //login using generated token
        try {
            await _client.LoginAsync(
                TokenType.Bot,
                _config.BotToken
                );
        } catch {
            Console.WriteLine("ERROR: could not log in. Ensure the BotToken field in data/config.json is valid.");
            return;
        }

        //begin running and wait 4 seconds to allow client to connect
        await _client.StartAsync();

        if (_config.CommandEnabled || _config.RoleEnabled)
        {
            await Task.Delay(4000);
        }

        //set up command handler
        if (_config.CommandEnabled)
        {
            _commandhandler = new CommandHandler(_config);
            if (_commandhandler.LoadCommands() != 0)
            {
                Console.WriteLine("WARN: could not initialize command handler.");
                _commandhandler = null;
            }
            else
            {
                //hook command handler to message received event
                _client.MessageReceived += HandleMessageAsync;
                Console.WriteLine("Command handler ready.");
            }
        }

        //set up role handler
        if (_config.RoleEnabled)
        {
            SocketGuild       foundguild   = null;
            SocketTextChannel foundchannel = null;

            //try to get guilds from client 3 times
            var guilds = _client.Guilds;
            int i      = 0;
            while (guilds.Count <= 0 && i < 2)
            {
                Console.WriteLine("WARN: retrieved 0 guilds from client. Retrying in 4 seconds.");
                await Task.Delay(4000);

                guilds = _client.Guilds;
                i     += 1;
            }

            if (guilds.Count > 0)
            {
                //find guild in config
                foreach (SocketGuild guild in guilds)
                {
                    if (guild.Name == _config.RoleGuild)
                    {
                        foundguild = guild;
                        break;
                    }
                }
                if (foundguild != null)
                {
                    //find channel in config
                    var channels = foundguild.TextChannels;
                    foreach (SocketTextChannel channel in channels)
                    {
                        if (channel.Name == _config.RoleChannel)
                        {
                            foundchannel = channel;
                            break;
                        }
                    }
                }
                //try to initialize role handler
                if (foundguild != null && foundchannel != null)
                {
                    _rolehandler = new RoleHandler(foundguild, foundchannel);
                    if ((await _rolehandler.LoadRoles()) != 0)
                    {
                        Console.WriteLine("WARN: could not initialize role handler.");
                        _rolehandler = null;
                    }
                    else
                    {
                        //give command handler reference to role handler's load method on success
                        _commandhandler.SetLoadRolesFn(_rolehandler.LoadRoles);

                        //hook reaction handler to reaction events
                        _client.ReactionAdded   += HandleReactionAddedAsync;
                        _client.ReactionRemoved += HandleReactionRemovedAsync;
                        Console.WriteLine("Role handler ready.");
                    }
                }
                else
                {
                    Console.WriteLine("WARN: config.json: could not find guild or channel specified in configuration for role handler. Either they do not exist, or client did not connect within 5 seconds.");
                    Console.WriteLine("WARN: could not initialize role handler.");
                }
            }
            else
            {
                Console.WriteLine("WARN: retrieved 0 guilds from client while trying to initialize role handler.");
                Console.WriteLine("WARN: could not initialize role handler.");
            }
        }

        //set up join handler
        if (_config.JoinEnabled)
        {
            SocketGuild       foundguild   = null;
            SocketTextChannel foundchannel = null;

            //try to get guilds from client 3 times
            var guilds = _client.Guilds;
            int i      = 0;
            while (guilds.Count <= 0 && i < 2)
            {
                Console.WriteLine("WARN: retrieved 0 guilds from client. Retrying in 4 seconds.");
                await Task.Delay(4000);

                guilds = _client.Guilds;
                i     += 1;
            }

            if (guilds.Count > 0)
            {
                //find guild in config
                foreach (SocketGuild guild in guilds)
                {
                    if (guild.Name == _config.JoinGuild)
                    {
                        foundguild = guild;
                        break;
                    }
                }
                if (foundguild != null)
                {
                    //find channel in config
                    var channels = foundguild.TextChannels;
                    foreach (SocketTextChannel channel in channels)
                    {
                        if (channel.Name == _config.JoinChannel)
                        {
                            foundchannel = channel;
                            break;
                        }
                    }
                }
                //try to initialize join handler
                if (foundguild != null && foundchannel != null)
                {
                    _joinhandler = new JoinHandler(foundguild, foundchannel);
                    if ((await _joinhandler.LoadJoin()) != 0)
                    {
                        Console.WriteLine("WARN: could not initialize join handler.");
                        _joinhandler = null;
                    }
                    else
                    {
                        //give command handler reference to join handler's load method on success
                        _commandhandler.SetLoadJoinFn(_joinhandler.LoadJoin);

                        //hook reaction handler to join event
                        _client.UserJoined += HandleUserJoinedAsync;
                        Console.WriteLine("Join handler ready.");
                    }
                }
                else
                {
                    Console.WriteLine("WARN: config.json: could not find guild or channel specified in configuration for join handler. Either they do not exist, or client did not connect within 5 seconds.");
                    Console.WriteLine("WARN: could not initialize join handler.");
                }
            }
            else
            {
                Console.WriteLine("WARN: retrieved 0 guilds from client while trying to initialize join handler.");
                Console.WriteLine("WARN: could not initialize join handler.");
            }
        }

        //delay infinitely
        await Task.Delay(-1);
    }
Exemplo n.º 11
0
        public void TestOnlyTriggerOnJoin()
        {
            var joinHandler = new JoinHandler();

            Assert.AreEqual("JOIN", joinHandler.ForCommand());
        }
Exemplo n.º 12
0
        protected override Expression VisitMethodCall(MethodCallExpression m)
        {
            if (m.Method.DeclaringType == typeof(Queryable))
            {

                switch (m.Method.Name)
                {
                    case "Select":
                        Debug.Assert(selectHandler == null);
                        selectHandler =
                            SelectHandler.GetSelectHandler(indentLevel + 1, m, aggregateType);
                        if (selectHandler == null)
                        {
                            this.queryableMethods.Enqueue(m);
                        }
                        this.Visit(m.Arguments[0]);
                        break;
                    case "Join":
                        Debug.Assert(joinHandler == null);
                        Debug.Assert(crossJoinHandler == null);
                        joinHandler = JoinHandler.GetJoinHandler(this, indentLevel + 1, m);
                        break;
                    case "SelectMany":
                        Debug.Assert(crossJoinHandler == null);
                        Debug.Assert(joinHandler == null);
                        crossJoinHandler = CrossJoinHandler.GetCrossJoinHandler(this, indentLevel + 1, m);
                        break;
                    case "Where":
                        Debug.Assert(whereHandler == null);
                        int parameterBaseIndex = outerStatement == null ? 0 : outerStatement.ParameterCount;
                        whereHandler =
                            WhereHandler.GetWhereHandler(indentLevel + 1, m, parameterBaseIndex);
                        if (whereHandler == null)
                        {
                            this.queryableMethods.Enqueue(m);
                        }
                        this.Visit(m.Arguments[0]);
                        break;
                    case "OrderBy":
                    case "OrderByDescending":
                    case "ThenBy":
                    case "ThenByDescending":
                        var orderByHandler = OrderByHandler.GetOrderByHandler(indentLevel + 1, m);
                        if (orderByHandler == null)
                        {
                            this.queryableMethods.Enqueue(m);
                        }
                        else
                        {
                            orderByHandlers.Push(orderByHandler);
                        }
                        this.Visit(m.Arguments[0]);
                        break;
                    default:
                        queryableMethods.Enqueue(m);
                        this.Visit(m.Arguments[0]);
                        break;
                }
            }
            else
            {

                throw new NotSupportedException(string.Format("The method '{0}' is not supported", m.Method.Name));
            }

            return m;
        }