コード例 #1
0
 public void onMsg(ref IMessageBase msg)
 {
     if (GetInfo().IsBanned(msg.User.RawText))
     {
         msg.Cancel = true;
     }
 }
コード例 #2
0
ファイル: BiliBili.cs プロジェクト: Mother-Ship/SyncPlugin
 public override void Send(IMessageBase Message)
 {
     if (sender.loginStauts)
     {
         sender.send(Message.Message);
     }
 }
コード例 #3
0
        public void OnFrontendConnect(IMessageBase messageBase)
        {
            Logger.Debug("Frontend connected");
            FrontendRegistration message = (FrontendRegistration)messageBase;

            _sessionIds[FrontendUserId] = message.SessionId;

            // send user preferences
            foreach (int userId in PlayerData.Instance.GetKeys())
            {
                if (!PlayerData.Instance.TryGetEntry(userId, out PlayerDataEntry entry))
                {
                    continue;
                }

                PreferencesMessage playerPosition = new PreferencesMessage()
                {
                    preferences = entry.Preferences,
                    UserId      = userId
                };

                SendToFrontend(new FrontendPayload(playerPosition));
            }

            Logger.AddPrinter(new FrontendPrinter(this));

            StrategyManager.Instance.ActiveStrategy.UpdateFrontend();
        }
コード例 #4
0
        protected void _handleTimeMessage(IMessageBase baseMessage)
        {
            //Debug.Log("Received time message");

            if (!(baseMessage is TimeMessage))
            {
                Logger.Warn("Received the incorrect message type " + baseMessage.GetType() + ". " +
                            "Excepted " + typeof(TimeMessage));
                return;
            }

            TimeMessage message = (TimeMessage)baseMessage;

            SendUnreliable(message);

            //Logger.Info("Received time message: " + message.turn + " " + message.millis + " " + message.turnMillis);
#if BACKEND
            double timeBeforeSync = VirtualSpaceTime.CurrentTimeInMillis;
            VirtualSpaceTime.Update(message.Millis, message.TripTime);
            double timeAfterSync = VirtualSpaceTime.CurrentTimeInMillis;

            double timeOffset = Math.Abs(timeAfterSync - timeBeforeSync);
            if (timeOffset > 20)
            {
                Logger.Warn($"{message.UserId}: Time offset was {Math.Abs(timeOffset)}");
            }
#elif UNITY
            LastTimeMessage = message;
#endif
            //Debug.Log("Handled time message");
        }
コード例 #5
0
        /// <summary>
        /// Write message to the ublox reciver.
        /// </summary>
        /// <param name="message"></param>
        public bool WriteMessage(IMessageBase message)
        {
            byte[] messageArray = message.ToArray();

            WriteReceiver(messageArray);

            if (message.IsAcknowledged)
            {
                int acknowledgeKey = new { Class = 0x05, Id = 0x01, MessageClass = messageArray[2], MessageId = messageArray[3] }.GetHashCode();

                var stopwatch = new Stopwatch();
                stopwatch.Start();

                do
                {
                    if (Acknowlagements.ContainsKey(acknowledgeKey))
                    {
                        Acknowlagements.Remove(acknowledgeKey);
                        return(true);
                    }
                    else
                    {
                        Task.Delay(10).Wait();
                    }
                } while (stopwatch.Elapsed < TimeSpan.FromSeconds(AcknowledgementTimeOut));
            }

            return(false);
        }
コード例 #6
0
        public void onMsg(ref IMessageBase msg)
        {
            msg.Cancel = true; //block all

            if (string.IsNullOrWhiteSpace(msg.Message.RawText))
            {
                return;
            }

            var cmd = msg.Message.RawText.Split(' ').FirstOrDefault().ToLower();

            switch (cmd)
            {
            case "play":
                MusicPlayerManager.ActivityPlayer.Play();
                break;

            case "pause":
                MusicPlayerManager.ActivityPlayer.Pause();
                break;

            case "replay":
                MusicPlayerManager.ActivityPlayer.Jump(0);
                MusicPlayerManager.ActivityPlayer.Play();
                break;

            default:
                ProcessComplexCommand(msg.Message.RawText);
                break;
            }
        }
コード例 #7
0
        /// <summary>
        /// Generate the base <c>MessageJson</c> for a message
        /// </summary>
        /// <param name="message">The base interface, <c>IMessageBase</c>, of the message to be sent.</param>
        /// <returns>A <c>MessageJson</c> object for generating an InjectionRequest</returns>
        internal virtual MessageJson GenerateBaseMessageJson(IMessageBase message)
        {
            var jsonMsg = new MessageJson
            {
                Subject       = message.Subject,
                TextBody      = message.PlainTextBody,
                HtmlBody      = message.HtmlBody,
                MailingId     = message.MailingId,
                MessageId     = message.MessageId,
                CharSet       = message.CharSet,
                CustomHeaders = PopulateCustomHeaders(message.CustomHeaders),
                From          = new AddressJson(message.From.Email, message.From.FriendlyName),
                Attachments   = PopulateList(message.Attachments)
            };

            if (message.ReplyTo != null)
            {
                jsonMsg.ReplyTo = new AddressJson(message.ReplyTo.Email, message.ReplyTo.FriendlyName);
            }

            if (message.ApiTemplate.HasValue)
            {
                jsonMsg.ApiTemplate = message.ApiTemplate.ToString();
            }

            return(jsonMsg);
        }
コード例 #8
0
        public void onMsg(ref IMessageBase msg)
        {
            if ((!msg.Message.RawText.StartsWith(DownloadCommand)) || Scheduler == null)
            {
                return;
            }

            msg.Cancel = true;

            string param = msg.Message.RawText.Replace(DownloadCommand, string.Empty).Trim();

            switch (param)
            {
            case "":
            case "last":
                Scheduler.DownloadLastSuggest();
                break;

            case "all":
                Scheduler.DownloadAll();
                break;

            default:
                break;
            }
        }
コード例 #9
0
        internal void RemovePlayer(IMessageBase messageBase)
        {
            Deregistration deregistration = (Deregistration)messageBase;
            int            playerID       = deregistration.UserId;

            Logger.Debug($"{playerID} wants to deregister");

            bool success = PlayerData.Instance.RemovePlayer(playerID);

            if (success)
            {
                Logger.Info("Removing player " + playerID + " with sessionid " + _sessionIds[playerID]);
                SendReliable(new DeregistrationSuccess
                {
                    UserId = playerID
                });
                lock (_sessionIds)
                    _sessionIds[playerID] = -1;
                PlayerIDManager.FreeID(playerID);
            }
            else
            {
                Logger.Warn("Could not remove player " + playerID);
            }

            StrategyManager.Instance.UpdatePlayerList();
        }
コード例 #10
0
        private void _reactToIncentives(IMessageBase baseMessage)
        {
            //Logger.Debug("react to incentives");
            Incentives incentives = (Incentives)baseMessage;

            // do nothing
        }
コード例 #11
0
 internal MessageInfo(IMessageBase message, int channel, int bytes, int count)
 {
     this.message = message;
     this.channel = channel;
     this.bytes   = bytes;
     this.count   = count;
 }
コード例 #12
0
        private static IMessageBase CheckPorn(string cacheImageName, byte[] image)
        {
            IMessageBase imageMessage             = null;
            string       path                     = Path.GetDirectoryName(cacheImageName);
            string       fileNameWithoutExtension = Path.GetFileNameWithoutExtension(cacheImageName);
            string       healthFileName           = Path.Combine(path, fileNameWithoutExtension + "_IsHealth.png");
            string       notHealthFileName        = Path.Combine(path, fileNameWithoutExtension + "_NotHealth.png");

            try
            {
                bool bHealth = TencentCloudHelper.CheckImageHealth(image);
                if (bHealth)
                {
                    if (File.Exists(cacheImageName))
                    {
                        File.Move(cacheImageName, healthFileName, true);
                    }
                }
                else
                {
                    imageMessage = new PlainMessage(BotInfo.SearchCheckPornIllegalReply);
                    if (File.Exists(cacheImageName))
                    {
                        File.Move(cacheImageName, notHealthFileName, true);
                    }
                }
            }
            catch (Exception ex)
            {
                imageMessage = new PlainMessage(BotInfo.SearchCheckPornErrorReply.ReplaceGreenOnionsTags(new KeyValuePair <string, string>("错误信息", ex.Message)));
            }
            return(imageMessage);
        }
コード例 #13
0
        public void onMsg(ref IMessageBase msg)
        {
            string message = msg.Message.RawText, param = string.Empty;

            if (message.StartsWith(queryUserIdCommand))
            {
                param = message.Substring(queryUserIdCommand.Length).Trim();

                string result = String.Format("userid \"{0}\" is {1} ", param, (UserIdGenerator.GetId(param)));

                Sync.SyncHost.Instance.Messages.RaiseMessage <ISourceClient>(new IRCMessage("RecentQuery", result));
                msg.Cancel = true;
                return;
            }

            if (message.StartsWith(queryUserNameCommand))
            {
                msg.Cancel = true;
                param      = message.Substring(queryUserNameCommand.Length).Trim();

                if (Int32.TryParse(param, out int id))
                {
                    return;
                }

                string result = String.Format("userName \"{0}\" is {1} ", UserIdGenerator.GetUserName(id), param);

                Sync.SyncHost.Instance.Messages.RaiseMessage <ISourceClient>(new IRCMessage("RecentQuery", result));
            }
        }
コード例 #14
0
 protected override void _handleMessage(IMessageBase message)
 {
     if (OnHandleMessage != null)
     {
         OnHandleMessage(message);
     }
 }
コード例 #15
0
        private void _handlePlayerPreferences(IMessageBase messageBase)
        {
            PreferencesMessage preferences = (PreferencesMessage)messageBase;

            Logger.Debug("Received new player preferences from P" + preferences.UserId);
            if (preferences == null)
            {
                Logger.Warn("Received invalid message type " + messageBase.GetType() +
                            ". Expected " + typeof(PreferencesMessage));
                return;
            }
            if (preferences.UserId < 0)
            {
                Logger.Warn("Received invalid player id " + preferences.UserId);
                return;
            }
            if (!PlayerData.Instance.TryGetEntry(preferences.UserId, out PlayerDataEntry entry))
            {
                Logger.Warn("Received unregistered player id " + preferences.UserId);
                return;
            }

            entry.UpdatePreferences(preferences.preferences);
            SendToFrontend(new FrontendPayload(preferences));
            MetricLogger.Log(preferences.UserId + " reregistered as " + preferences.preferences.SceneName);
        }
コード例 #16
0
        const int timeout = 6000;//ms

        public void onMsg(ref IMessageBase msg)
        {
            if (msgManager == null)
            {
                return; //没完全初始化,发送不了信息
            }
            string message = msg.Message.RawText.Trim();
            string user    = msg.User.RawText;

            if (message.StartsWith(suggestCommand))
            {
                msg.Cancel = true;
                TryParseNormalCommand(msg.User.RawText, message);
                return;
            }

            Match match = simple_command_regex.Match(message);

            if (match.Success)
            {
                int  id      = int.Parse(match.Groups[6].ToString());
                char isSetID = match.Groups[5].ToString()[0];

                if (isSetID == 's' || isSetID == 'b')
                {
                    SendSuggestMessage(id, user, isSetID == 's');
                    msg.Cancel = true;
                }
            }
        }
コード例 #17
0
        public async void DoHandleAsync(MiraiHttpSession session, IMessageBase[] chain, IBaseInfo info, bool isGroupMessage = true)
        {
            ChineseLunisolarCalendar calendar = new ChineseLunisolarCalendar();
            var now          = DateTime.Now;
            var year         = calendar.GetYear(now);
            var month        = calendar.GetMonth(now);
            var day          = calendar.GetDayOfMonth(now);
            var hasLeapMonth = calendar.GetLeapMonth(year) > 0;

            if (hasLeapMonth)
            {
                if (month < 13 && day < 23)
                {
                    if (month > 1 && day > 15)
                    {
                        return;
                    }
                }
            }
            else
            {
                if (month < 12 && day < 23)
                {
                    if (month > 1 && day > 15)
                    {
                        return;
                    }
                }
            }
            List <IMessageBase> result = new List <IMessageBase>();
            IMessageBase        img    = null;

            switch (chain.First(m => m.Type == "Plain").ToString())
            {
            case "新年快乐":
                img = await session.UploadPictureAsync(UploadTarget.Group, "Resources\\NewYear\\NewYearStick.png");

                result.Add(img);
                break;

            case "新年抽签":
                string[] lotterise = Directory.GetFiles("Resources\\Lottery");
                img = await session.UploadPictureAsync(UploadTarget.Group, lotterise[randomer.Next(0, lotterise.Length - 1)]);

                result.Add(img);
                break;

            default:
                break;
            }
            if (isGroupMessage)
            {
                await session.SendGroupMessageAsync(((IGroupMemberInfo)info).Group.Id, result.ToArray());
            }
            else
            {
                await session.SendFriendMessageAsync(info.Id, result.ToArray());
            }
        }
コード例 #18
0
 //listening messages from Danmaku
 public void onMsg(ref IMessageBase msg)
 {
     if (msg.Cancel || recorder == null || msg.User.RawText.Length == 0)
     {
         return;
     }
     recorder.Update(msg.User.RawText, msg.Message.RawText);
 }
コード例 #19
0
 public new Task <int> SendGroupMessageAsync(long groupNumber, params IMessageBase[] chain)
 {
     return(Task.Factory.StartNew <int>(msg => {
         IMessageBase data = msg as IMessageBase;
         Console.WriteLine("Group -> " + data.ToString());
         return 1;
     }, chain[0]));
 }
コード例 #20
0
ファイル: MessageDispatcher.cs プロジェクト: vollR/Sync
 public void onMsg(ref IMessageBase msg)
 {
     if (!msg.Message.RawText.StartsWith("?send"))
     {
         msg.Cancel = true;
     }
     msg.Message = new StringElement(msg.Message.RawText.TrimStart("?send".ToArray()));
 }
コード例 #21
0
        public void OnFrontendDisconnect(IMessageBase messageBase)
        {
            Logger.Debug("Frontend disconnected");

            Logger.RemovePrinter(typeof(FrontendPrinter));

            _sessionIds.TryRemove(FrontendUserId, out int _);
        }
コード例 #22
0
 public void onMsg(ref IMessageBase msg)
 {
     if (msg is GiftMessage)
     {
         msg.Cancel = true;
         AddGift(((GiftMessage)msg).Source);
     }
 }
コード例 #23
0
 /// <summary>
 /// If set, check if a ReplyTo email address is valid
 /// </summary>
 /// <param name="message">The base interface, <c>IMessageBase</c>, of the message to be sent.</param>
 /// <returns><c>bool</c> result</returns>
 internal virtual bool HasValidReplyTo(IMessageBase message)
 {
     if (String.IsNullOrWhiteSpace(message.ReplyTo.Email) && String.IsNullOrWhiteSpace(message.ReplyTo.FriendlyName))
     {
         return(true);
     }
     return(message.ReplyTo.IsValid);
 }
コード例 #24
0
        public void _handleIncentives(IMessageBase message)
        {
            //Logger.Debug("handle incentives");
            Incentives incentives = (Incentives)message;

            List <RevokeEvent> revokeEvents    = new List <RevokeEvent>();
            List <TimedEvent>  actuationEvents = new List <TimedEvent>();

            foreach (TimedEvent newEvent in incentives.Events)
            {
                var newTimedEvent = (TimedEvent)newEvent;
                if (newEvent is RevokeEvent)
                {
                    revokeEvents.Add((RevokeEvent)newTimedEvent);
                }
                else
                {
                    actuationEvents.Add(newTimedEvent);
                }
            }

            lock (_events)
            {
                _events.RemoveAll(event_ =>
                                  revokeEvents.TrueForOne(
                                      revokeEvent => revokeEvent.Id == event_.Id
                                      )
                                  );

                foreach (TimedEvent newEvent in actuationEvents)
                {
                    TimedEvent eventToOverwrite = _events.Find(existingEvent => newEvent.StrategyId == existingEvent.StrategyId && newEvent.Id == existingEvent.Id);
                    if (eventToOverwrite == null)
                    {
                        _events.Add(newEvent);
                    }
                    else
                    {
                        eventToOverwrite.OverrideWith(newEvent);
                    }
                }
            }

            //double minDistance = double.MaxValue;
            //Vector minPosition = null;
            //Vector currentPosition = CurrentPosition;
            //foreach (Vector position in positions)
            //{
            //    double distance = (currentPosition - position).SqrMagnitude;
            //    if (distance < minDistance)
            //    {
            //        minDistance = distance;
            //        minPosition = position;
            //    }
            //}

            // _recommendedPosition = minPosition;
        }
コード例 #25
0
        private void Invoke <T>(IMessageBase message) where T : IMessageBase
        {
            object handler = null;

            if (_handlers.TryGetValue(typeof(T), out handler))
            {
                ((IHandler <T>)handler).Handle((T)message);
            }
        }
コード例 #26
0
        private async Task SendPictureAsync(MiraiHttpSession session, string path) // 发图
        {
            // 你也可以使用另一个重载 UploadPictureAsync(PictureTarget, Stream)
            // mirai-api-http 在v1.7.0以下时将使用本地的HttpListener做图片中转
            ImageMessage msg = await session.UploadPictureAsync(PictureTarget.Group, path);

            IMessageBase[] chain = new IMessageBase[] { msg }; // 数组里边可以加上更多的 IMessageBase, 以此达到例如图文并发的情况
            await session.SendGroupMessageAsync(0, chain);     // 自己填群号, 一般由 IGroupMessageEventArgs 提供
        }
コード例 #27
0
 public void onMsg(ref IMessageBase msg)
 {
     if (DefaultPlugin.MainClient.Client is DirectOSUIRCBot client &&
         DirectOSUIRCBot.IRCBotName.ToString() == DirectOSUIRCBot.IRCNick.ToString() &&
         msg.User.RawText == DirectOSUIRCBot.IRCBotName.ToString())
     {
         msg.Cancel = true;
     }
 }
コード例 #28
0
ファイル: Message.cs プロジェクト: clifordunique/Tetris-3
        public static T GetData <T>(this IMessageBase e)
        {
            // try get data
            if (e is IMessageData eventData && eventData.Data is T dataCast)
            {
                return(dataCast);
            }

            return(default);
コード例 #29
0
        public void AddMessage(IMessageBase message)
        {
            if (_database.Any(f => f.MessageId == message.MessageId))
            {
                _database.Remove(_database.First(f => f.MessageId == message.MessageId));
            }

            _database.Add(message);
        }
コード例 #30
0
ファイル: SourceBase.cs プロジェクト: vollR/Sync
 internal void send(IMessageBase message)
 {
     if (!SendStatus)
     {
         IO.CurrentIO.WriteColor(DefaultI18n.LANG_SendNotReady, ConsoleColor.Red);
         return;
     }
     Send(message);
 }
コード例 #31
0
        private static string GetMessageIdentity(IMessageBase requestMessage)
        {
            var message = requestMessage as IRequestMessage;
            if (message != null)
            {
                return message.MessageId.ToString(CultureInfo.InvariantCulture);
            }

            return requestMessage.FromUserName + requestMessage.CreateTime;
        }
コード例 #32
0
ファイル: CommandDistributor.cs プロジェクト: jacan/services
        public void Add(IMessageBase command)
        {
            //if (command.Id.Equals(Guid.Empty) || command.Timestamp == null)
            //{
            //	throw new MessageIdInvalidException();
            //}

            if (command.Timestamp == null)
            {
                throw new MessageTimestampInvalidException();
            }

            _commands.Add(command);
        }
コード例 #33
0
 public string Serialize(IMessageBase graph)
 {
     throw new NotImplementedException();
 }