NewTask() публичный статический Метод

Creates a new SchedulerTask object to run in the main thread. Use this if your task is time-sensitive or frequent, and your callback won't take too long to execute.
public static NewTask ( [ callback ) : SchedulerTask
callback [ Method to call when the task is triggered.
Результат SchedulerTask
Пример #1
0
        static void openDoor(Zone zone, Player player)
        {
            int sx = zone.Bounds.XMin;
            int ex = zone.Bounds.XMax;
            int sy = zone.Bounds.YMin;
            int ey = zone.Bounds.YMax;
            int sz = zone.Bounds.ZMin;
            int ez = zone.Bounds.ZMax;

            Block[] buffer = new Block[zone.Bounds.Volume];

            int counter = 0;

            for (int x = sx; x <= ex; x++)
            {
                for (int y = sy; y <= ey; y++)
                {
                    for (int z = sz; z <= ez; z++)
                    {
                        buffer[counter] = player.WorldMap.GetBlock(x, y, z);
                        player.WorldMap.QueueUpdate(new BlockUpdate(null, new Vector3I(x, y, z), Block.Air));
                        counter++;
                    }
                }
            }

            DoorInfo info = new DoorInfo(zone, buffer, player.WorldMap);

            //reclose door
            Scheduler.NewTask(doorTimer_Elapsed).RunOnce(info, DoorCloseTimer);
        }
Пример #2
0
        internal void StartTasks()
        {
            lock ( taskLock ) {
                updateTask = Scheduler.NewTask(UpdateTask);
                updateTask.RunForever(this,
                                      TimeSpan.FromMilliseconds(ConfigKey.TickInterval.GetInt()),
                                      TimeSpan.Zero);

                if (ConfigKey.SaveInterval.GetInt() > 0)
                {
                    saveTask = Scheduler.NewTask(SaveTask);
                    saveTask.RunForever(this,
                                        TimeSpan.FromSeconds(ConfigKey.SaveInterval.GetInt()),
                                        TimeSpan.FromSeconds(ConfigKey.SaveInterval.GetInt()));
                }

                if (ConfigKey.BackupInterval.GetInt() > 0)
                {
                    backupTask = Scheduler.NewTask(BackupTask);
                    TimeSpan interval = TimeSpan.FromMinutes(ConfigKey.BackupInterval.GetInt());
                    backupTask.RunForever(this,
                                          interval,
                                          (ConfigKey.BackupOnStartup.GetBool() ? TimeSpan.Zero : interval));
                }
            }
        }
 public static void Start()
 {
     world_.Hax      = false;
     world_.gameMode = GameMode.TeamDeathMatch; //set the game mode
     delayTask       = Scheduler.NewTask(t => world_.Players.Message("&WTEAM DEATHMATCH &fwill be starting in {0} seconds: &WGet ready!", timeDelay));
     delayTask.RunRepeating(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(10), 1);
 }
Пример #4
0
 public static void Start()
 {
     world_.Hax      = false;
     world_.gameMode = GameMode.FFA; //set the game mode
     delayTask       = Scheduler.NewTask(t => world_.Players.Message("&WFFA &fwill be starting in {0} seconds: &WGet ready!", (timeDelay - (DateTime.UtcNow - startTime).ToSeconds())));
     delayTask.RunRepeating(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(10), (timeDelay / 10));
 }
Пример #5
0
 private ChatTimer( TimeSpan duration, [CanBeNull] string message, [NotNull] string startedBy ) {
     if ( startedBy == null )
         throw new ArgumentNullException( "startedBy" );
     StartedBy = startedBy;
     Message = message;
     StartTime = DateTime.UtcNow;
     EndTime = StartTime.Add( duration );
     Duration = duration;
     int oneSecondRepeats = ( int )duration.TotalSeconds + 1;
     if ( duration > Hour ) {
         announceIntervalIndex = AnnounceIntervals.Length - 1;
         lastHourAnnounced = ( int )duration.TotalHours;
     } else {
         for ( int i = 0; i < AnnounceIntervals.Length; i++ ) {
             if ( duration <= AnnounceIntervals[i] ) {
                 announceIntervalIndex = i - 1;
                 break;
             }
         }
     }
     task = Scheduler.NewTask( TimerCallback, this );
     Id = Interlocked.Increment( ref timerCounter );
     AddTimerToList( this );
     IsRunning = true;
     task.RunRepeating( TimeSpan.Zero,
                        TimeSpan.FromSeconds( 1 ),
                        oneSecondRepeats );
 }
Пример #6
0
 /// <summary>
 /// Method to start the game
 /// </summary>
 public void Start()
 {
     _world.gameMode = GameMode.ZombieSurvival;                             //set the game mode
     _humanCount     = _world.Players.Where(p => p.iName != _zomb).Count(); //count all players
     Scheduler.NewTask(t => _world.Players.Message("&WThe game will be starting soon..."))
     .RunRepeating(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(20), 2);
 }
Пример #7
0
        public void Start()
        {
#if !(DEBUG)
            if (_world.Players.Count() < 2) //in case players leave the world or disconnect during the start delay
            {
                _world.Players.Message("&WPropHunt&s requires at least 2 people to play.");
                return;
            }
#endif
            if (PropHuntWorlds.Count <= 3)
            {
                Logger.Log(LogType.Error,
                           "You must have at least 3 PropHunt maps. Please add some with /PropHunt add [mapname].");
                return;
            }
            _world          = PropHuntWorlds[RandWorld.Next(0, PropHuntWorlds.Count)];
            _world.gameMode = GameMode.PropHunt;
            _startTime      = DateTime.Now;
            Logger.Log(LogType.SystemActivity, "&WPropHunt &S is starting in {0} seconds on world {1}.", TimeDelay,
                       _world.ClassyName);
            if (StartMode != Game.StartMode.PropHunt)
            {
                _task = new SchedulerTask(Interval, true).RunForever(TimeSpan.FromMilliseconds(500));
                _world.Players.Message("&WPropHunt &S is starting in {0} seconds on world {1}.", TimeDelay,
                                       _world.ClassyName);
                //Time delay if it is the on-demand instance of the game
                if ((DateTime.Now - _startTime).TotalSeconds > TimeDelay)
                {
                    foreach (Player p in PropHuntPlayers)
                    {
                        BeginGame(p);
                        ChooseSeeker();
                        if (p.IsPropHuntSeeker)
                        {
                            continue;
                        }
                        p.Model = blockId[randBlock.Next(0, blockId.Length)];
                        string blockName = Map.GetBlockByName(p.Model).ToString();
                        p.Message("&WYou are disgused as {0}.", blockName);
                        p.iName = null;
                    }
                }
                Player.Moving  += PlayerMovingHandler;
                LastChecked     = DateTime.Now; //used for intervals
                _checkIdlesTask = Scheduler.NewTask(CheckIdles).RunForever(TimeSpan.FromMilliseconds(100));
                IsOn            = true;
#if DEBUG
                Logger.Log(LogType.Warning, "It is on and stuff...");
#endif
            }
            Player.Clicking     += PlayerClickingHandler;
            Player.Connected    += PlayerConnectedHandler;
            Player.Disconnected += PlayerDisconnectedHandler;
        }
Пример #8
0
        private static void VoteKickCheck()
        {
            if (VoteIsOn)
            {
                Server.Players.Message(
                    "{0}&S wanted to get {1} kicked. Reason: {2} \n&SResults are in! Yes: &A{3} &SNo: &C{4}",
                    VoteStarter,
                    TargetName, VoteKickReason, VotedYes, VotedNo);

                Player target = null;

                try
                {
                    target = Server.FindPlayerOrPrintMatches(Player.Console, TargetName, true, true);
                }
                catch (Exception ex)
                {
                    // Log exception
                    Logger.Log(LogType.Error, ex.Message);

                    // Notify users
                    Server.Message("Unexpected error while trying to execute votekick");

                    // Unable to find target so quit.
                    VoteIsOn   = false;
                    TargetName = null;
                    return;
                }

                if (target == null)
                {
                    Server.Message("{0}&S is offline", target.ClassyName);
                    return;
                }
                else if (VotedYes > VotedNo)
                {
                    Scheduler.NewTask(
                        t =>
                        target.Kick(Player.Console, "VoteKick by: " + VoteStarter + " - " + VoteKickReason,
                                    LeaveReason.Kick, false, true, false)).RunOnce(TimeSpan.FromSeconds(3));
                    Server.Players.Message("{0}&S was kicked from the server", target.ClassyName);
                }
                else
                {
                    Server.Players.Message("{0} &Sdid not get kicked from the server", target.ClassyName);
                }
                VoteIsOn   = false;
                TargetName = null;
                foreach (Player V in Voted)
                {
                    V.HasVoted = false;
                }
            }
        }
Пример #9
0
        public List <Vector3I> PositionList = new List <Vector3I>(); //Vectors in this list are connected, but not neccessarily in a line

        #region Public Methods

        /// <summary>
        /// Sets a bot, as well as the bot values. Must be called before any other bot classes.
        /// </summary>
        public void setBot(String botName, World botWorld, Position pos, int entityID)
        {
            Name     = botName;
            World    = botWorld;
            Position = pos;
            ID       = entityID;

            thread = Scheduler.NewTask(t => NetworkLoop());
            thread.RunForever(TimeSpan.FromSeconds(0.1));            //run the network loop every 0.1 seconds

            Server.Bots.Add(this);
        }
Пример #10
0
        /// <summary>
        /// Updates a specific block for a given time
        /// </summary>
        private void updateBlock(Block blockType, Vector3I blockPosition, bool replaceWithAir, double time)        //I left this class rather generic incase i used it for anything else
        {
            BlockUpdate update = new BlockUpdate(null, blockPosition, blockType);

            foreach (Player p in World.Players)
            {
                p.World.Map.QueueUpdate(update);
            }

            if (replaceWithAir)
            {
                Scheduler.NewTask(t => updateBlock(Block.Air, blockPosition, false, time)).RunManual(TimeSpan.FromSeconds(time));                //place a block, replace it with air once 'time' is up
            }
        }
Пример #11
0
        //Used if the server starts prophunt on launch. This brings the player to the world that the game is in.
        public void PlayerConnectedHandler(object sender, Events.PlayerConnectedEventArgs e)
        {
            PropHuntPlayers.Add(e.Player);
            e.StartingWorld = _world;
            if (StartMode != Game.StartMode.PropHunt)
            {
                return;
            }
            if (PropHuntPlayers.Count() < 2)
            {
                e.Player.Message("&WThere are not enough players online to being PropHunt. Please try again later.");
                Logger.Log(LogType.Warning,
                           "There are not enough players online to being PropHunt. Please try again later.");
            }
            else
            {
                BeginGame(e.Player);
                if (PropHuntPlayers.Count(player => player.IsPropHuntSeeker) == 0)
                {
                    ChooseSeeker();
                }
                if (RoundStarted && TimeDelay == 0)
                {
                    e.Player.Message("&cYou connected while a round was in progress. You have been made a seeker.");
                    Logger.Log(LogType.SystemActivity,
                               "{0} connected while a round was in progress. They have been made a seeker.", e.Player);
                    e.Player.IsPropHuntSeeker = true;
                }
                foreach (Player p in PropHuntPlayers)
                {
                    if (!p.IsPropHuntSeeker)
                    {
                        p.Model = blockId[randBlock.Next(0, blockId.Length)];
                        string blockName = Map.GetBlockByName(p.Model).ToString();
                        p.Message("&HYou are disgused as {0}.", blockName);
                        p.iName = null;
                    }
                }
                //Handlers for various things
                Player.Moving += PlayerMovingHandler;

                _checkIdlesTask = Scheduler.NewTask(CheckIdles).RunForever(TimeSpan.FromMilliseconds(100));
                _task           = new SchedulerTask(Interval, true).RunForever(TimeSpan.FromMilliseconds(500));

#if DEBUG
                Logger.Log(LogType.Warning, "It is on and stuff...");
#endif
            }
        }
Пример #12
0
        void StartTasks() {
            lock( taskLock ) {
                updateTask = Scheduler.NewTask( UpdateTask );
                updateTask.RunForever( this,
                                       TimeSpan.FromMilliseconds( ConfigKey.TickInterval.GetInt() ),
                                       TimeSpan.Zero );

                if( ConfigKey.SaveInterval.GetInt() > 0 ) {
                    saveTask = Scheduler.NewBackgroundTask( SaveTask );
                    saveTask.RunForever( this,
                                         TimeSpan.FromSeconds( ConfigKey.SaveInterval.GetInt() ),
                                         TimeSpan.FromSeconds( ConfigKey.SaveInterval.GetInt() ) );
                }
            }
        }
Пример #13
0
        public static void Start()
        {
            world_.Hax = false;

            //world_.Players.Send(PacketWriter.MakeHackControl(0,0,0,0,0,-1)); Commented out until classicube clients support hax packet
            stopwatch.Reset();
            stopwatch.Start();
            world_.gameMode = GameMode.CaptureTheFlag;
            delayTask       = Scheduler.NewTask(t => world_.Players.Message("&WCTF &fwill be starting in {0} seconds: &WGet ready!", (timeDelay - stopwatch.Elapsed.Seconds)));
            delayTask.RunRepeating(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(10), (int)Math.Floor((double)(timeDelay / 10)));//Start task immediately, send message every 10s
            if (stopwatch.Elapsed.Seconds > 11)
            {
                stopwatch.Stop();
            }
        }
Пример #14
0
        ChatTimer(TimeSpan duration, [CanBeNull] string message, [NotNull] string startedBy)
        {
            if (startedBy == null)
            {
                throw new ArgumentNullException("startedBy");
            }
            StartedBy = startedBy;
            Message   = message;
            StartTime = DateTime.UtcNow;
            EndTime   = StartTime.Add(duration);
            Duration  = duration;
            int oneSecondRepeats = (int)duration.TotalSeconds + 1;

            if (duration > Hour)
            {
                announceIntervalIndex = AnnounceIntervals.Length - 1;
                lastHourAnnounced     = (int)duration.TotalHours;
            }
            else
            {
                for (int i = 0; i < AnnounceIntervals.Length; i++)
                {
                    if (duration <= AnnounceIntervals[i])
                    {
                        announceIntervalIndex = i - 1;
                        break;
                    }
                }
            }
            task = Scheduler.NewTask(TimerCallback, this);
            ID   = Interlocked.Increment(ref timerCounter);
            AddTimerToList(this);
            IsRunning = true;
            task.RunRepeating(TimeSpan.Zero,
                              TimeSpan.FromSeconds(1),
                              oneSecondRepeats);

            try {
                if (!Directory.Exists("./Timers"))
                {
                    Directory.CreateDirectory("./Timers");
                }
                string[] output = { "StartDate: " + StartTime, "EndDate: " + EndTime, "CreatedBy: " + StartedBy, "Message: " + Message };
                File.WriteAllLines("./Timers/" + TimerFilename(this), output);
            } catch (Exception ex) {
                Player.Console.Message("Timer Writer Has Crashed: {0}", ex);
            }
        }
Пример #15
0
        static void HandleCommandBlock(Player p, Zone zone)
        {
            p.LastSignClicked = zone.Name;
            if (p.IsCommandBlockRunning || TextCooldown(p))
            {
                return;
            }

            if (zone.Sign == null)
            {
                string path = SignPath(p, zone);
                if (File.Exists(path))
                {
                    p.SignLines = File.ReadAllLines(path);

                    if (p.SignLines.Length >= 1)
                    {
                        if (!zone.Name.CaselessStarts(ConsoleCommand))
                        {
                            Scheduler.NewTask(CommandBlock).RunRepeating(p, new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 1), p.SignLines.Length);
                        }
                        else
                        {
                            Scheduler.NewTask(CommandBlock).RunRepeating(p, new TimeSpan(0, 0, 0), new TimeSpan(0, 0, 0, 0, 1), p.SignLines.Length);
                        }
                    }
                    Logger.Log(LogType.Debug, "[Signs] {0} clicked on command block [{1}] On map [{2}]", p.Name, zone.Name, p.World.Name);
                }
                else
                {
                    p.Message("&WThis zone, {0}&W, is marked as a command block, but no text is added to the sign!", zone.ClassyName);
                    Logger.Log(LogType.Debug, "[Signs] {0} clicked on an empty command block [{1}] On map: [{2}]", p.Name, zone.Name, p.World.Name);
                }
            }
            else
            {
                p.Message("&WThis zone, {0}&W, is marked as a command block, but no text is added to the sign!", zone.ClassyName);
                Logger.Log(LogType.Debug, "[Signs] {0} clicked on an empty command block [{1}] On map: [{2}]", p.Name, zone.Name, p.World.Name);
            }
            p.LastZoneNotification = DateTime.UtcNow;
        }
Пример #16
0
        //Voting
        public void TakeVote()
        {
            //Actual voting
            if (!_votingRestarting)
            {
                World[] voteWorlds = PropHuntWorlds.OrderBy(x => RandWorld.Next())
                                     .Take(3)
                                     .ToArray();
                World1 = voteWorlds[0];
                World2 = voteWorlds[1];
                World3 = voteWorlds[2];

                //Stop the game before voting
                _task.Stop();
                _checkIdlesTask.Stop();
                Player.Moving -= PlayerMovingHandler;
                if (PropHuntPlayers != null)
                {
                    lock (PropHuntPlayers.ToList())
                    {
                        foreach (Player p in PropHuntPlayers.ToList())
                        {
                            RevertPlayer(p);
                        }
                    }
                }
            }
            if (_votingRestarting)
            {
                _votingRestarting = false;
            }
            Server.Players.Message("&S--------------------------------------------------------------");
            Server.Players.Message("&SVote for the next map!");
            Server.Players.Message("&S/Vote &c1&S for {0}&S, &c2&S for {1}&S, and &c3&S for {2}",
                                   World1.ClassyName, World2.ClassyName, World3.ClassyName);
            Server.Players.Message("&S--------------------------------------------------------------");

            Scheduler.NewTask(task => VoteCheck())
            .RunOnce(TimeSpan.FromSeconds(60));
            VoteIsOn = true;
        }
Пример #17
0
        /// <summary>
        /// Emulates a small explosion at a specific location
        /// </summary>
        private void explode(Vector3I center, double delay, double length)
        {
            Scheduler.NewTask(t => updateBlock(Block.Lava, center, true, length)).RunManual(TimeSpan.FromSeconds(delay));

            Random rand1 = new Random((int)DateTime.UtcNow.Ticks);
            Random rand2 = new Random((int)DateTime.UtcNow.Ticks + 1);
            Random rand3 = new Random((int)DateTime.UtcNow.Ticks + 2);
            Random rand4 = new Random((int)DateTime.UtcNow.Ticks + 3);
            Random rand5 = new Random((int)DateTime.UtcNow.Ticks + 4);
            Random rand6 = new Random((int)DateTime.UtcNow.Ticks + 5);

            //The code block generates a lava block from 0 to 3 block spaces, randomly away from the center block

            Scheduler.NewTask(t => updateBlock(Block.Lava, new Vector3I(center.X, center.Y, center.Z), true, length)).RunManual(TimeSpan.FromSeconds(delay));
            Scheduler.NewTask(t => updateBlock(Block.Lava, new Vector3I(center.X + rand1.Next(0, 3), center.Y, center.Z), true, length)).RunManual(TimeSpan.FromSeconds(delay));
            Scheduler.NewTask(t => updateBlock(Block.Lava, new Vector3I(center.X - rand2.Next(0, 3), center.Y, center.Z), true, length)).RunManual(TimeSpan.FromSeconds(delay));
            Scheduler.NewTask(t => updateBlock(Block.Lava, new Vector3I(center.X, center.Y + rand3.Next(0, 3), center.Z), true, length)).RunManual(TimeSpan.FromSeconds(delay));
            Scheduler.NewTask(t => updateBlock(Block.Lava, new Vector3I(center.X, center.Y - rand4.Next(0, 3), center.Z), true, length)).RunManual(TimeSpan.FromSeconds(delay));
            Scheduler.NewTask(t => updateBlock(Block.Lava, new Vector3I(center.X, center.Y, center.Z + rand5.Next(0, 3)), true, length)).RunManual(TimeSpan.FromSeconds(delay));
            Scheduler.NewTask(t => updateBlock(Block.Lava, new Vector3I(center.X, center.Y, center.Z - rand6.Next(0, 3)), true, length)).RunManual(TimeSpan.FromSeconds(delay));
        }
Пример #18
0
        static void OpenDoor(Zone zone, Player player)
        {
            Block[]  buffer = new Block[zone.Bounds.Volume];
            DoorInfo info   = new DoorInfo(zone, buffer, player.WorldMap);
            int      i      = 0;

            for (int x = info.Zone.Bounds.XMin; x <= info.Zone.Bounds.XMax; x++)
            {
                for (int y = info.Zone.Bounds.YMin; y <= info.Zone.Bounds.YMax; y++)
                {
                    for (int z = info.Zone.Bounds.ZMin; z <= info.Zone.Bounds.ZMax; z++)
                    {
                        buffer[i] = player.WorldMap.GetBlock(x, y, z);
                        info.WorldMap.QueueUpdate(new BlockUpdate(null, new Vector3I(x, y, z), Block.Air));
                        i++;
                    }
                }
            }

            // reclose door
            Scheduler.NewTask(DoorTimerElapsed).RunOnce(info, DoorCloseTimer);
        }
Пример #19
0
 public void Start()
 {
     started = true;
     task    = Scheduler.NewTask(StartFeed);
     task.RunForever(TimeSpan.FromMilliseconds(600));
 }
Пример #20
0
            void HandleMessage([NotNull] string message)
            {
                if (message == null)
                {
                    throw new ArgumentNullException("message");
                }

                IRCMessage msg = MessageParser(message, ActualBotNick);

#if DEBUG_IRC
                Logger.Log(LogType.IRC,
                           "[{0}]: {1}",
                           msg.Type, msg.RawMessage);
#endif

                switch (msg.Type)
                {
                case IRCMessageType.Login:
                    if (ConfigKey.IRCRegisteredNick.Enabled())
                    {
                        Send(IRCCommands.Privmsg(ConfigKey.IRCNickServ.GetString(),
                                                 ConfigKey.IRCNickServMessage.GetString()));
                    }
                    foreach (string channel in channelNames)
                    {
                        if (ConfigKey.IRCChannelPassword.GetString() != "password")
                        {
                            Send(IRCCommands.Join(channel + " " + ConfigKey.IRCChannelPassword.GetString()));
                        }
                        else
                        {
                            Send(IRCCommands.Join(channel));
                        }
                    }
                    IsReady = true;
                    AssignBotForInputParsing();     // bot should be ready to receive input after joining
                    return;


                case IRCMessageType.Ping:
                    // ping-pong
                    Send(IRCCommands.Pong(msg.RawMessageArray[1].Substring(1)));
                    return;


                case IRCMessageType.ChannelAction:
                case IRCMessageType.ChannelMessage:
                    // channel chat
                    if (!ResponsibleForInputParsing)
                    {
                        return;
                    }
                    if (!IsBotNick(msg.Nick))
                    {
                        string processedMessage = msg.Message;
                        if (msg.Type == IRCMessageType.ChannelAction)
                        {
                            if (processedMessage.StartsWith("\u0001ACTION"))
                            {
                                processedMessage = processedMessage.Substring(8);
                            }
                            else
                            {
                                return;
                            }
                        }
                        processedMessage = NonPrintableChars.Replace(processedMessage, "");
                        if (processedMessage.Length > 0)
                        {
                            if (ConfigKey.IRCBotForwardFromIRC.Enabled())
                            {
                                if (msg.Type == IRCMessageType.ChannelAction)
                                {
                                    Server.Message("&i(IRC) * {0} {1}",
                                                   msg.Nick, processedMessage);
                                    Logger.Log(LogType.IRC, "(IRC) * {0} {1}",
                                               msg.Nick, processedMessage);
                                }
                                else
                                {
                                    Server.Message("&i(IRC) {0}{1}: {2}",
                                                   msg.Nick, Color.White, processedMessage);
                                    Logger.Log(LogType.IRC, "(IRC) {0}: {1}",
                                               msg.Nick, processedMessage);
                                }
                            }
                            else if (msg.Message.StartsWith("#"))
                            {
                                Server.Message("&i(IRC) {0}{1}: {2}",
                                               msg.Nick, Color.White, processedMessage.Substring(1));
                                Logger.Log(LogType.IRC, "(IRC) {0}: {1}",
                                           msg.Nick, processedMessage.Substring(1));
                            }
                        }
                    }
                    return;


                case IRCMessageType.Join:
                    if (!ResponsibleForInputParsing)
                    {
                        return;
                    }
                    if (ConfigKey.IRCBotAnnounceIRCJoins.Enabled())
                    {
                        Server.Message("&i(IRC) {0} joined {1}",
                                       msg.Nick, msg.Channel);
                    }
                    return;


                case IRCMessageType.Kick:
                    string kicked = msg.RawMessageArray[3];
                    if (kicked == ActualBotNick)
                    {
                        Logger.Log(LogType.IRC,
                                   "Bot was kicked from {0} by {1} ({2}), rejoining.",
                                   msg.Channel, msg.Nick, msg.Message);
                        Thread.Sleep(ReconnectDelay);
                        Send(IRCCommands.Join(msg.Channel));
                    }
                    else
                    {
                        if (!ResponsibleForInputParsing)
                        {
                            return;
                        }
                        Server.Message("&i(IRC) {0} kicked {1} from {2} ({3})",
                                       msg.Nick, kicked, msg.Channel, msg.Message);
                    }
                    return;


                case IRCMessageType.Part:
                case IRCMessageType.Quit:
                    if (!ResponsibleForInputParsing)
                    {
                        return;
                    }
                    if (ConfigKey.IRCBotAnnounceIRCJoins.Enabled())
                    {
                        Server.Message("&i(IRC) {0} left {1}",
                                       msg.Nick, msg.Channel);
                    }
                    return;


                case IRCMessageType.NickChange:
                    if (!ResponsibleForInputParsing)
                    {
                        return;
                    }
                    Server.Message("&i(IRC) {0} is now known as {1}",
                                   msg.Nick, msg.Message);
                    return;

                case IRCMessageType.ErrorMessage:
                case IRCMessageType.Error:
                    bool die = false;
                    switch (msg.ReplyCode)
                    {
                    case IRCReplyCode.ErrorNicknameInUse:
                    case IRCReplyCode.ErrorNicknameCollision:
                        Logger.Log(LogType.IRC,
                                   "Error: Nickname \"{0}\" is already in use. Trying \"{0}_\"",
                                   ActualBotNick);
                        ActualBotNick += "_";
                        Send(IRCCommands.Nick(ActualBotNick));
                        break;

                    case IRCReplyCode.ErrorPasswordMismatch:
                        if (triedPass)
                        {
                            Logger.Log(LogType.IRC, "Could not connect with irc server password. Please configure your correct irc server password in the ConfigGUI.");
                            die = true;
                            break;
                        }
                        if (ConfigKey.IRCBotNetworkPass.GetString() == "defaultPass")
                        {
                            Logger.Log(LogType.IRC, "Requested irc server is password-locked. Please set your irc server password in the ConfigGUI.");
                            break;
                        }
                        Logger.Log(LogType.IRC, "Requested irc server is password-locked, attempting to connect with " + ConfigKey.IRCBotNetworkPass.GetString());

                        //give the irc client a second to prompt for password before sending
                        Scheduler.NewTask(t => SendChannelMessage("/pass " + ConfigKey.IRCBotNetworkPass.GetString())).RunManual(TimeSpan.FromSeconds(2));
                        triedPass = true;

                        break;

                    case IRCReplyCode.ErrorBannedFromChannel:
                    case IRCReplyCode.ErrorNoSuchChannel:
                        Logger.Log(LogType.IRC,
                                   "Error: {0} ({1})",
                                   msg.ReplyCode, msg.Channel);
                        die = true;
                        break;

                    default:
                        Logger.Log(LogType.IRC,
                                   "Error ({0}): {1}",
                                   msg.ReplyCode, msg.RawMessage);
                        break;
                    }

                    if (die)
                    {
                        Logger.Log(LogType.IRC, "Error: Disconnecting.");
                        reconnect = false;
                        DisconnectThread();
                    }

                    return;


                case IRCMessageType.QueryAction:
                    // TODO: PMs
                    Logger.Log(LogType.IRC,
                               "Query: {0}", msg.RawMessage);
                    break;


                case IRCMessageType.Kill:
                    Logger.Log(LogType.IRC,
                               "Bot was killed from {0} by {1} ({2}), reconnecting.",
                               hostName, msg.Nick, msg.Message);
                    reconnect   = true;
                    isConnected = false;
                    return;
                }
            }
Пример #21
0
        public static void VoteParams(Player player, Command cmd)
        {
            string option = cmd.Next();

            if (option == null)
            {
                MessageVoteStatus(player); return;
            }
            switch (option)
            {
            default:
                MessageVoteStatus(player);
                break;

            case "abort":
            case "stop":
                if (!VoteIsOn)
                {
                    player.Message("No vote is currently running");
                    return;
                }

                if (!player.Can(Permission.MakeVotes))
                {
                    player.Message("You do not have Permission to abort votes");
                    return;
                }
                VoteIsOn = false;
                foreach (Player V in Voted)
                {
                    if (V.Info.HasVoted)
                    {
                        V.Info.HasVoted = false;
                    }
                    V.Message("Your vote was cancelled");
                }
                Voted.Clear();
                TargetName = null;
                Server.Players.Message("{0} &Saborted the vote.", player.ClassyName);
                break;

            case "yes":
                if (!VoteIsOn)
                {
                    player.Message("No vote is currently running");
                    return;
                }

                if (player.Info.HasVoted)
                {
                    player.Message("&CYou have already voted");
                    return;
                }
                Voted.Add(player);
                VotedYes++;
                player.Info.HasVoted = true;
                player.Message("&8You have voted for 'Yes'");
                break;

            case "no":
                if (!VoteIsOn)
                {
                    player.Message("No vote is currently running");
                    return;
                }
                if (player.Info.HasVoted)
                {
                    player.Message("&CYou have already voted");
                    return;
                }
                VotedNo++;
                Voted.Add(player);
                player.Info.HasVoted = true;
                player.Message("&8You have voted for 'No'");
                break;

            case "ask":
                string AskQuestion = cmd.NextAll();
                Question = AskQuestion;
                if (!player.Can(Permission.MakeVotes))
                {
                    player.Message("You do not have permissions to ask a question");
                    return;
                }
                if (VoteIsOn)
                {
                    player.Message("A vote has already started. Each vote lasts 1 minute.");
                    return;
                }
                if (Question.Length < 5)
                {
                    player.Message("Invalid question");
                    return;
                }

                NewVote();
                VoteStarter = player.ClassyName;
                Server.Players.Message("{0}&S Asked: {1}", player.ClassyName, Question);
                Server.Players.Message("&9Vote now! &S/Vote &AYes &Sor /Vote &CNo");
                VoteIsOn = true;
                Scheduler.NewTask(VoteCheck).RunOnce(TimeSpan.FromMinutes(1));
                break;
            }
        }