Add first hook to server: chat

This commit is contained in:
ChillerDragon 2024-01-20 21:39:21 +08:00
parent 78a8d95e6a
commit 8f647e165c
3 changed files with 34 additions and 0 deletions

View file

@ -1,5 +1,6 @@
# frozen_string_literal: true
require_relative'context'
require_relative 'models/map'
require_relative 'models/chat_message'
require_relative 'messages/game_info'
@ -24,6 +25,21 @@ class GameServer
)
end
##
# call_hook
#
# @param: hook_sym [Symbol] name of the symbol to call
# @param: context [Context] context object to pass on data
# @param: optional [Any] optional 2nd parameter passed to the callback
def call_hook(hook_sym, context, optional = nil)
@server.hooks[hook_sym].each do |hook|
hook.call(context, optional)
context.verify
return nil if context.canceld?
end
context
end
def on_emoticon(chunk, _packet)
message = ClEmoticon.new(chunk.data[1..])
p message
@ -69,6 +85,9 @@ class GameServer
say = ClSay.new(chunk.data[1..])
author = packet.client.player
msg = ChatMesage.new(say.to_h.merge(client_id: author.id, author:))
context = Context.new(say, chunk:)
return if call_hook(:chat, context, msg).nil?
puts msg.to_s
end

View file

@ -59,6 +59,7 @@ end
class TeeworldsServer
attr_accessor :clients
attr_reader :hooks
def initialize(options = {})
@verbose = options[:verbose] || false
@ -68,6 +69,13 @@ class TeeworldsServer
@clients = {}
@current_game_tick = 0
@last_snap_time = Time.now
@hooks = {
chat: []
}
end
def on_chat(&block)
@hooks[:chat].push(block)
end
def run(ip, port)

View file

@ -4,4 +4,11 @@
require_relative 'lib/teeworlds_server'
srv = TeeworldsServer.new(verbose: false)
srv.on_chat do |context, msg|
context.cancel
puts "[chat] #{msg.author.name}: #{msg.message}"
end
srv.run('127.0.0.1', 8303)