/// <summary> /// Starts a message loop that allows events to be subsribed to. /// </summary> /// <param name="waitAfterPoll">Wait before each poll.</param> private void MessageLoop(TimeSpan waitAfterPoll, int secTimeOut = 0) { _searching = true; while (_searching) { Thread.Sleep(waitAfterPoll); PollResponse response = _chatHandler.Poll(secTimeOut); PollReceived?.Invoke(this, new PollArgs(response)); if (response.Messages == null) { continue; } foreach (Message message in response.Messages) { MessageReceived?.Invoke(this, new MessageArgs(message)); switch (message.Type.ToLower()) { case "saytext": ChatMessageReceived?.Invoke(this, new ChatMessageArgs(message)); break; case "typing": OnUserTyping?.Invoke(this, new TypingArgs(message)); break; } } } }
private void OnChatMessage(ref ChatMsg message, ref bool cancel) { // TODO player manager to cache these objects var player = new Player { Name = message.CustomAuthorName, SteamId = message.Author }; var text = message.Text; if (_commands.IsCommand(text)) { _commands.Execute(player, text.TrimStart(CommandPrefix), s => SendMessageTo(s, player.SteamId)); cancel = true; } else { var e = new ChatMessageEvent(message.Author, message.CustomAuthorName, text); ChatMessageReceived?.Invoke(ref e); cancel |= e.IsCancelled; if (!cancel) { _chatLog.Info($"{e.SenderName}: {e.Content}"); } } }
private void RecvCallback(IAsyncResult result) { int byte_len = stream.EndRead(result); if (byte_len <= 0) { Logger.LogError("Received length < 0!"); ClientErrored?.Invoke("Invalid length!"); return; } var data = new byte[byte_len]; Array.Copy(receiveBuf, data, byte_len); string msg = Encoding.UTF8.GetString(data); Logger.Log($"Received message: {LocalUser}: {msg}"); ChatMessageReceived?.Invoke(LocalUser, msg); stream.BeginRead(receiveBuf, 0, 4096, RecvCallback, null); }
/// <summary> /// Receives a tell from another <see cref="ChatSession"/>. /// </summary> /// <param name="sender"></param> /// <param name="message"> </param> void ReceiveTell(ChatSession sender, string message) { // sending back the message to the sender (acknowledges message sent) var sentMessage = new ChatMessageReceived { MessageType = (byte)MessageType.Tell, Sender = sender.name, Receiver = this.Name, Message = message }; sender.SendEvent(sentMessage, new MessageParameters { ChannelId = PeerSettings.ChatEventChannel }); // sending the receiver the message var receivedMessage = new ChatMessageReceived { MessageType = (byte)MessageType.Tell, Sender = sender.name, Message = message }; this.SendEvent(receivedMessage, new MessageParameters { ChannelId = PeerSettings.ChatEventChannel }); }
/// <summary> /// Fire when a normal chat message was received /// </summary> /// <param name="e"></param> /// <returns></returns> public async Task OnMessageReceivedAsync(ChatMessageReceivedEventArgs e) { if (ChatMessageReceived != null) { await ChatMessageReceived.Invoke(e); } }
private async Task IrcMessageReceived(object sender, IrcMessageRecievedEventArgs e) { //Console.WriteLine($"{e.Prefix,-64}{e.Command,-16}{e.Parameters}"); switch (e.Command) { case "001": Connected?.Invoke(this); break; case "PING": await ircClient.SendIrcMessage("PONG :tmi.twitch.tv"); break; case "PRIVMSG": ChatMessageReceived?.Invoke(this, new ChatMessageReceivedEventArgs(this, e.Prefix, e.Parameters)); break; case "JOIN": TwitchChannel channel = new TwitchChannel(e.Parameters.Replace("#", null), this); joinedChannels.Add(channel); ChannelJoined?.Invoke(this, new ChannelJoinedEventArgs(channel)); break; } }
public static bool Prefix(ref ChatMsg msg) { var cancel = false; ChatMessageReceived?.Invoke(ref msg, ref cancel); return(!cancel); }
private async Task SignalRInit() { hub = new HubConnectionBuilder().WithUrl(Constants.HUB_URL).Build(); hub.On <string, string, double>("NewAnalyzedMessage", (username, text, sentiment) => ChatMessageReceived?.Invoke(this, new ChatEventArgs(username, text, sentiment))); await hub.StartAsync(); }
public Task SendMessage(TextMessageData textMessage) { if (textMessage == null) { throw new ArgumentNullException(nameof(textMessage)); } textMessage.EnsureIsValid <TextMessageData, TextMessageValidator>(); var @event = new ChatMessageReceived(_state.RoomId, _state.UserId, textMessage); return(_state.Room.NotifyEverybody(@event)); }
private Task Client_OnMessageReceived(SocketMessage message) { if (HandleCommand(message)) { return(Task.CompletedTask); } ChatMessageReceived?.Invoke(this, new ChatMessageEventArgs { Message = message.Content }); return(Task.CompletedTask); }
public override Task <MessageReply> SendMessage(MessageRequest request, ServerCallContext context) { var message = new ChatMessage { Text = request.Text, SenderName = request.Sender }; ChatMessageReceived?.Invoke(this, message); return(Task.FromResult(new MessageReply { Received = true, Read = false })); }
void IChatMessageReceiver.ReceiveChatMessage(Client.Client sender, string message, ChatMode mode) { if (message.StartsWith("/")) { ChatCommandReceived?.Invoke(this, new ChatCommandReceivedEventArgs(sender, message, mode)); return; } ChatMessageReceived?.Invoke(this, new ChatMessageEventArgs(sender, message, mode)); if (mode == ChatMode.All) { SendMessageToAll($"{sender.ControlledNpc.CustomName ?? throw new NullReferenceException("Character custom name must not be null")}: {message}"); } }
private void Client_OnMessageReceived(object sender, OnMessageReceivedArgs e) { Action <string> replyAction = (msg) => { client.SendMessage(e.ChatMessage.Channel, $"@{e.ChatMessage.DisplayName} {msg}"); }; var args = new MessageEventArgs(replyAction) { User = e.ChatMessage.DisplayName, Message = e.ChatMessage.Message, Timestamp = DateTime.Now, MessageId = e.ChatMessage.Id }; ChatMessageReceived?.Invoke(this, args); }
private void Socket_DataReceived(WebSocketWrapper wrapper, ArraySegment <byte> data) { try { IMessage message = JsonSerializer.Deserialize <IMessage>(data, new JsonSerializerOptions { PropertyNameCaseInsensitive = true, }); if (message == null) { return; } switch (message.Type) { case ChatMessage.TypeString: if (IMessage.TryParseMessage <ChatMessage>(data, out ChatMessage chatMessage)) { ChatMessageReceived?.Invoke(chatMessage); } else { Console.WriteLine(String.Format("Unable to parse ChatMessage out of ChatMessage header.")); } break; case ServerCommand.TypeString: if (IMessage.TryParseMessage <ServerCommand>(data, out ServerCommand serverCommand)) { ServerCommandReceived?.Invoke(serverCommand); } else { Console.WriteLine(String.Format("Unable to parse ServerCommand out of ServerCommand header.")); } break; default: Console.WriteLine(String.Format("Unhandled Hub Message of type = {0}", message.Type)); break; } } catch (Exception e) { Console.WriteLine(String.Format("Error deserializing Json message = {0}", e.ToString())); } }
private void ProcessMessage(string message) { if (message == null) { return; } if (message.Contains("PING")) { SendMessage("PONG :tmi.twitch.tv"); Console.WriteLine("sent pong!"); } else if (message.Contains("PRIVMSG")) { string user = message.Substring(1, message.IndexOf("!") - 1); string cleaned = message.Split(':').Last(); ChatMessageReceived?.Invoke(user, cleaned); } }
/// <summary> /// Receives a chat message /// </summary> /// <param name="message"></param> void IListener.ReceiveMessage(ChannelMessage message) { var receivedMessage = new ChatMessageReceived { Message = message.Message }; switch (message.Channel.Type) { case ChannelType.Guild: receivedMessage.MessageType = (byte)MessageType.Guild; break; case ChannelType.Group: receivedMessage.MessageType = (byte)MessageType.Group; break; case ChannelType.Local: receivedMessage.MessageType = (byte)MessageType.Local; break; case ChannelType.Trade: receivedMessage.MessageType = (byte)MessageType.Trade; break; case ChannelType.Custom: receivedMessage.MessageType = (byte)MessageType.Channel; receivedMessage.ChannelName = message.Channel.Name; break; } if (message.Publisher != null) { receivedMessage.Sender = message.Publisher.Name; } this.SendEvent(receivedMessage, new MessageParameters { ChannelId = PeerSettings.ChatEventChannel }); }
/// <summary> /// process the json result which response from BiliBili /// </summary> /// <param name="json"></param> private void ProcessJson(string json) { if (json == null) { return; } var rt = JsonConvert.DeserializeObject <Root>(json); try { List <RoomItem> room = rt.data.room; foreach (Message m in room.Select(r => new Message(r.nickname, r.timeline, r.text)).Where(m => !_log.Contains(m))) { _log.Add(m); // Don't execute messages > 30 seconds. if (TimeOut(m)) { continue; } ChatMessageReceived?.Invoke(m.user, m.text); } } catch { ClientErrored?.Invoke($"{rt == null} Please Check your Roomid[{data["roomid"]}] \r\n {json}"); } if (_log.Count > 1000) { _log.RemoveRange(0, 800); } }
public void HandleChatMessage(NetworkMessage msg) { MsgMessage t = msg as MsgMessage; ChatMessage chat = new ChatMessage(); chat.From = t.From; chat.To = t.To; chat.IsAction = t.MessageType == MsgMessage.MessageTypes.ActionMessage; chat.Message = t.MessageText; GlobalChatLog.Add(chat); if (!UserLogs.ContainsKey(chat.From)) { UserLogs.Add(chat.From, new UserChatLog()); } UserLogs[chat.From].Messages.Add(chat); ChatMessageEventArgs args = new ChatMessageEventArgs(chat); if (chat.To == LocalPlayerID && DirectMessageReceived != null) { DirectMessageReceived.Invoke(this, args); } if (chat.To == LocalTeam && TeamMessageReceived != null) { TeamMessageReceived.Invoke(this, args); } if (ChatMessageReceived != null) { ChatMessageReceived.Invoke(this, args); } }
private void Listen() { while (Thread.CurrentThread.IsAlive) { NetworkRequest type; byte[] message = ReadMessage(); if (message.Length == 0) { continue; } type = (NetworkRequest)message[0]; var payload = new MemoryStream(message.Skip(1).ToArray()); BinaryReader reader = new BinaryReader(payload); switch (type) { case NetworkRequest.FatalError: // Any fatal error that occured lead here reader.ReadByte(); throw new Exception("Fatal error: " + reader.ReadString()); case NetworkRequest.AuthentificationSuccess: // Authentification confirmation { byte slot = reader.ReadByte(); _me = new PlayerSelf(this, _playerInfos.GetName(), slot); _otherPlayers.Add(slot, _me); LogDebug("Player slot is now " + slot); SendPlayerInfoMessage(); // We don't send our health/mana/etc because we keep the default one if (_playerInfos.GetHealth() != 100) { SendPlayerHealth(_playerInfos.GetHealth()); } if (_playerInfos.GetMana() != 20) { SendPlayerMana(_playerInfos.GetMana()); } SendWorldInfoRequest(); } break; case NetworkRequest.CharacterCreation: { byte slot = reader.ReadByte(); reader.ReadByte(); reader.ReadByte(); string name = reader.ReadString(); if (!_otherPlayers.ContainsKey(slot)) { LogInfo("New player with slot " + slot); Player player = new Player(this, name, slot); _otherPlayers.Add(slot, player); NewPlayerJoined?.Invoke(player); } } break; case NetworkRequest.WorldInfoAnswer: // Various basic information about the world if (!_didSpawn) { _didSpawn = true; var blocPixelSize = BlocGroup.blocPixelSize; int time = reader.ReadInt32(); byte moonInfo = reader.ReadByte(); byte moonPhase = reader.ReadByte(); short maxTilesX = reader.ReadInt16(); short maxTilesY = reader.ReadInt16(); short spawnX = reader.ReadInt16(); short spawnY = reader.ReadInt16(); short surfaceY = reader.ReadInt16(); short rockY = reader.ReadInt16(); LogDebug("Current time is " + time); LogDebug(ByteToBool(moonInfo, 1) ? "It's currently day time" : "It's currently night time"); LogDebug(ByteToBool(moonInfo, 2) ? "It's currently the blood moon" : "It's not currently the blood moon"); LogDebug(ByteToBool(moonInfo, 4) ? "It's currently an eclipse" : "It's not currently an eclipse"); LogDebug("The current moon phrase is " + moonPhase); LogDebug("Maximum world value at (" + (maxTilesX * blocPixelSize) + ";" + (maxTilesY * blocPixelSize) + ")"); LogDebug("Spawn world value at (" + (spawnX * blocPixelSize) + ";" + (spawnY * blocPixelSize) + ")"); LogDebug("Surface layer is at heigth of " + surfaceY); LogDebug("Rock layer is at height of " + rockY); _me.SetPosition(new Vector2(spawnX * blocPixelSize, spawnY * blocPixelSize), Vector2.Zero); _tiles = new Tile[maxTilesX, maxTilesY]; for (int i = 0; i < maxTilesX; i++) { for (int y = 0; y < maxTilesY; y++) { _tiles[i, y] = null; } } SendInitialTile(); } break; case NetworkRequest.TileData: // Some information about a row of tile? { MemoryStream stream = new MemoryStream(); if (payload.ReadByte() != 0) { using (DeflateStream deflate = new DeflateStream(payload, CompressionMode.Decompress)) { deflate.CopyTo(stream); deflate.Close(); } stream.Position = 0L; } else { stream = payload; stream.Position = 1L; } using (BinaryReader r = new BinaryReader(stream)) { int xStart = r.ReadInt32(); int yStart = r.ReadInt32(); int width = r.ReadInt16(); int height = r.ReadInt16(); LogDebug("Updating " + width + " x " + height + " tiles beginning at (" + xStart + ";" + yStart + ")"); // I have no idea what I'm doing but it's what Terraria is doing Tile tile = null; int value = 0; for (int y = yStart; y < yStart + height; y++) { for (int x = xStart; x < xStart + width; x++) { if (value != 0) { value--; _tiles[x, y] = (tile == null ? new Tile() : new Tile(tile)); } else { byte b = 0; byte b2 = 0; tile = _tiles[x, y]; _tiles[x, y] = new Tile(); if (tile == null) { tile = _tiles[x, y]; } byte b3 = r.ReadByte(); if ((b3 & 1) == 1) { b2 = r.ReadByte(); if ((b2 & 1) == 1) { b = r.ReadByte(); } } bool flag = tile.IsActive(); byte b4; if ((b3 & 2) == 2) { tile.Activate(true); ushort ttype = tile.GetTileType(); int num2; if ((b3 & 32) == 32) { b4 = r.ReadByte(); num2 = r.ReadByte(); num2 = (num2 << 8 | b4); } else { num2 = r.ReadByte(); } tile.SetTileType((ushort)num2); // num2 < _tileFrameImportant.Length shouldn't be here if (num2 > _tileFrameImportant.Length) { LogError(num2 + " is bigger than _tileFrameImportant length (" + _tileFrameImportant.Length + ")"); } if (num2 < _tileFrameImportant.Length && _tileFrameImportant[num2]) { tile.SetFrames(r.ReadInt16(), r.ReadInt16()); } else if (!flag || tile.GetTileType() != ttype) { tile.SetFrames(-1, -1); } if ((b & 8) == 8) { tile.Color(r.ReadByte()); } } if ((b3 & 4) == 4) { tile.SetWall(r.ReadByte()); if ((b & 16) == 16) { tile.ColorWall(r.ReadByte()); } } b4 = (byte)((b3 & 24) >> 3); if (b4 != 0) { tile.SetLiquid(r.ReadByte()); if (b4 > 1) { // Lava and honey management } } if (b2 > 1) { // Wires and slops management } if (b > 0) { // Some others electrical management } b4 = (byte)((b3 & 192) >> 6); if (b4 == 0) { value = 0; } else if (b4 == 1) { value = r.ReadByte(); } else { value = r.ReadInt16(); } } } } } } break; case NetworkRequest.PlayerControls: { byte slot = reader.ReadByte(); byte movement = reader.ReadByte(); bool up = ByteToBool(movement, 1); bool down = ByteToBool(movement, 2); bool left = ByteToBool(movement, 4); bool right = ByteToBool(movement, 8); bool jump = ByteToBool(movement, 16); bool useItem = ByteToBool(movement, 32); bool direction = ByteToBool(movement, 64); string keyInfo = "Key pressed: " + (up ? "Up " : "") + (down ? ", Down " : "") + (left + ", Left " + "") + (right + ", Right " + "") + (jump + ", Jump " + ""); byte otherMovement = reader.ReadByte(); byte selectedItem = reader.ReadByte(); float posX = reader.ReadSingle(); float posY = reader.ReadSingle(); var player = _otherPlayers[slot]; var newPos = new Vector2(posX, posY); float velX = 0f; float velY = 0f; PlayerPositionUpdate?.Invoke(player, newPos); if (ByteToBool(otherMovement, 4)) { velX = reader.ReadSingle(); velY = reader.ReadSingle(); LogDebug("Player " + slot + " is at (" + posX + ";" + posY + ") with a velocity of (" + velX + ";" + velY + ") " + keyInfo); } player.SetPosition(newPos, new Vector2(velX, velY)); LogDebug("Player " + slot + " is at (" + posX + ";" + posY + ") " + keyInfo); } break; case NetworkRequest.TileEdit: { byte action = reader.ReadByte(); short xPos = reader.ReadInt16(); short yPos = reader.ReadInt16(); short tileId = reader.ReadInt16(); if (action == 0) // Tile destroyed { _tiles[xPos, yPos] = new Tile(); } else { _tiles[xPos, yPos] = new Tile((byte)tileId); } } break; case NetworkRequest.TogglePVP: { byte slot = reader.ReadByte(); bool isPVP = reader.ReadByte() == 1; PVPStatusChanged?.Invoke(_otherPlayers[slot], isPVP); } break; case NetworkRequest.PasswordRequest: // The server need a password to be joined if (_password == "") { throw new ArgumentException("A password is needed to connect to the server."); } else { LogDebug("Sending password to server"); SendStringMessage(NetworkRequest.PasswordAnswer, _password); } break; case NetworkRequest.JoinTeam: { byte slot = reader.ReadByte(); byte team = reader.ReadByte(); TeamStatusChanged?.Invoke(_otherPlayers[slot], (Team)team); } break; case NetworkRequest.SpawnRequest: // When this is received, need to reply with spawn location LogInfo("Sending spawn request at (" + -1 + ";" + -1 + ")"); SendSpawnRequest(); ServerJoined?.Invoke(_me); break; case NetworkRequest.ChatMessage: { ushort id = reader.ReadUInt16(); byte slot = reader.ReadByte(); byte mode = reader.ReadByte(); try { string content = reader.ReadString(); if (mode == 0 && _otherPlayers.ContainsKey(slot)) { ChatMessageReceived?.Invoke(_otherPlayers[slot], content); } else if (mode == 2 && slot == 255) { LogDebug("Message received from server with id " + id + " and mode " + mode + ": " + content); } } catch (EndOfStreamException) // TODO: Need to fix this { } } break; case NetworkRequest.CharacterInventorySlot: case NetworkRequest.Status: case NetworkRequest.RecalculateUV: case NetworkRequest.BlockUpdate: case NetworkRequest.ItemInfo: case NetworkRequest.ItemOwnerInfo: case NetworkRequest.NPCInfo: case NetworkRequest.UpdateProjectile: case NetworkRequest.DeleteProjectile: case NetworkRequest.EvilRatio: case NetworkRequest.DailyAnglerQuestFinished: case NetworkRequest.EightyThree: case NetworkRequest.CharacterStealth: case NetworkRequest.InventoryItemInfo: case NetworkRequest.NinetySix: case NetworkRequest.TowerShieldStrength: break; default: // LogDebug("Unknown message type " + type); break; } } }
public SignalRChatService(HubConnection connection) { _connection = connection; _connection.On <ChatMessage>("ReceiveMessage", (message) => ChatMessageReceived?.Invoke(message)); }
protected virtual void OnChatMessageReceived(TwitchChatMessage msg) { ChatMessageReceived?.Invoke(this, new TwitchChatMessageReceivedEventArgs(_credentials, msg)); }
protected virtual void OnChatMessageReceived(TwitchChatMessage message) { ChatMessageReceived?.Invoke(this, new ChatMessageReceivedEventArgs(message)); }
public Task Handle(ChatMessageReceived notification, CancellationToken cancellationToken) { return(Task.CompletedTask); }
protected virtual void OnChatMessageReceived(ITwitchAccount account, TwitchChatMessage tcm) { ChatMessageReceived?.Invoke(this, new ChatConnectionMessageReceivedEventArgs(account, tcm)); }
public void ReadTeamMessage(PacketReader stream) { ChatMessageReceived?.Invoke(this, new ChatMessageReceivedArgs(ChatMode.Team, stream.ReadString())); }
internal void OnChatMessageReceived(ChatMessage message) => ChatMessageReceived?.Invoke(this, new ChatMessageEventArgs(message));