Ir para conteúdo
Entre para seguir isso  
Mock

Channel entre 2 servers -- alfa

Recommended Posts

Mock    32
Mock

Servidor testado: TFS 0.3.x

--------

Autor: bearpaw.png(Baseado em um outro script so que pela source.)

--------

Requerimento: O.T.A.L (Open Tibia Advanced Lib) http://otal.awardspace.info/

--------

Versão: 0.1 ALFA

 

 

Eu fiz esse script, é aquele scritp pra 2 servers abrirem um canal de chat entre eles, o script esta todo cheio de POG's, alem disso eu fiz ele via talkactions, todos os comandos dele tem que ser via talk, Ja aviso, o conteudo abaixo não e aconselhado a inesperientes na area. nao vai adiantar eu ser claro pois um iniciantes na area, mesmo eu sendo muito claro ele nao vai entender BULHUFAS entao sorry amigos :(

 

Bem, o script eu fiz via talkactions, como vocês sabem TALK esta em um luastate diferente de move, actions etc entao nao rola de criar uma var global em talk e usa-la em actions entao estamos limitados as talkactions.

 

Bem o sistema é o seginte, você escolhe entre ser o host ou o cara que vai conectar, caos vc seje o host vc so tem a configurar:


port = "7175", --- Porta
pass = "otal", --- Senha para a pessoa conectar
name = "OtalHost", --- O nome
greet = "Welcome to otal host", --- Uma mensagem de boas vindas
luapass = "omgapass", --- Password dos comandos lua
allowLua = true, --- Usar comandos lua?
maxconections = 2, --- Maximo de conexões aceitas (eu consegi com 10)
otherluaPass = "usethis", --- Se for usar o lua do outro server ponha a senha

 

Bem esse allowlua é o seginte, tem um comando que você pode executar linhas de comando em lua no outro server basta habilitar isso :D!

Vamos começar pelo host mesmo.

Bem vá até em talkactions e adcione a tag:

<talkaction words="!host" event="script" value="host.lua" />

Agora adcione o host.lua com esse conteudo GIGANTE que merece Pogpowered2.gif

dofile('config.lua')
if ip == nil then
  ip = "host"
end
function doIP(ip)
if string.len(ip) > 15 then
    return string.sub(ip,1,15).."..." 
else
return ip 
end
end
function send_all(msg)
  local on = getPlayersOnline()
  for i=1,#on do
      doPlayerSendToChannel(on[i], on[i], 8, info.name.." ["..string.sub(ip,1,15).."...]: "..msg, 4)
  end
  for a,e in pairs(pepes) do
     e:send('TEXT='..info.name.." ["..string.sub(ip,1,15).."...]: "..msg..'\n')
  end
end

function send_all2(msg,players,tx)
local term = ""   
if tx then
     term = "TEXT=" 
  end
  if players then
        local on = getPlayersOnline()
        for i=1,#on do
            doPlayerSendToChannel(on[i], on[i], 8,msg, 4)
        end
  end
  for a,e in pairs(pepes) do
     e:send(term..msg..'\n')
  end
end

function sendLeft(c,msg,me,ig)
  if me == nil then
     me = {}
  end
  if ig == nil then             
     local on = getPlayersOnline()
     for i=1,#on do
          if me.name then
             doPlayerSendToChannel(on[i], on[i], 8, me.name.." [".. doIP(c:getpeername()) .."]: "..msg, 4)
          end
     end
  end
  for a,e in pairs(pepes) do
     if pepes[a] ~= c then
        if me.name then
           pepes[a]:send('TEXT='..me.name.." [".. doIP(c:getpeername()) .."]: "..msg..'\n')
        end
     end
  end
end

function sendLeft2(c,msg,me,ig)
  if me == nil then
     me = {}
     me.name = "Server"
  end
  if ig == nil then
     local on = getPlayersOnline()
     for i=1,#on do
         if me.name then
          doPlayerSendToChannel(on[i], on[i], 8,msg, 4)
     end
     end
  end
  for a,e in pairs(pepes) do
     if pepes[a] ~= c then
        pepes[a]:send('TEXT='..msg..'\n')
     end
  end
end

function remove(c)
           for i=1,#pepes do
              if pepes[i] == c then
                 table.remove(pepes,i)
                 print('Removed: '..i)
              end
           end
end

function getId(c)
           for a,e in pairs(pepes) do
              if e == c then
                 return a
              end
           end
           return 0
end

function getC(id)
  for a,e in pairs(pepes) do
    if a == id then
     return e
     end
  end
end

function send_to(msg,id)
     for a,e in pairs(pepes) do
        if a == id then
           e:send(msg..'\n')
           return true
        end
     end
  return nil
end

function run_c(c,byte,info,id)
        local me = users[id]
        if not me then
           return
        end
        c:settimeout(0.01);
        l, e = c:receive()
        if me.finish ~= 0 then
           if me.finish < os.clock() then
              print('No info send... Closing... ['..c:getpeername()..']')
              sendLeft2(c,me.name..' {'..id..'} ['..c:getpeername()..'] has left.',me)
              c:send('NO INFO\n')
              c:close()
              return remove(c)
           end
        end
        if me.ping2 < os.clock() then
           if c ~= nil then
           print('['..c:getpeername()..'] Ping timeout [120]')
           sendLeft2(c,'['..c:getpeername()..'] {'..id..'} Ping timeout [120]')
           c:close()
           return remove(c)
           end
        end
        if e ~= 'timeout' and l == nil then
           if c and me.name then
           	sendLeft2(c,me.name..' {'..id..'} ['..c:getpeername()..'] has left.',me)
           end
           print('Conection closed ['..c:getpeername()..']')
           c:close()
           return remove(c)
        end
        if l ~= nil then
           if byte == 1 then
              if l ~= 'PASS='..info.pass then
                 c:send('WRONG PASS\n')
                 c:close()
                 return remove(c)
              else
                 c:send('REQ NAME\n')
                 me.finish = os.clock()+5
                 byte = byte+1   --- aqui byte ja é 2 e requer o nome
                 return addEvent(run_c,100,c,byte,info,id) 
              end
           end   
           if byte == 2 then
                   local _,_,name = string.find(l,'NAME=(.+)')
                   if string.len(name) > 15 or string.find(name,'[!@#$%%¨&*()´`~^,.<>;://\\¬¢£³²¹€.+-]') then
                     c:send('INVALID NAME\n')
                     c:close()
                     return remove(c)
                   else
                    me.name = name
                    me.finish = 0
                    print('[Chat] '..c:getpeername()..' has connected {'..id..'} ['..me.name..']!')
                    sendLeft2(c,me.name..' {'..id..'} ['..c:getpeername()..'] has connected.',me)
                    c:send("TEXT="..info.name..": "..info.greet.."\n")
                    return addEvent(run_c,100,c,3,info,id)
                   end  
           end
           if l == 'PING' then
              c:send('PONG\n')
              me.ping2 = os.clock()+120
              return addEvent(run_c,200,c,byte,info,id)
           elseif l:find('ERROR=(.+)') then
               local _,_,err = l:find('ERROR=(.+)')
               if err then
                  print("From: "..c:getpeername().."\a Error: "..err..".")
               end            
               return addEvent(run_c,200,c,byte,info,id)
           elseif l:find('INFORM=(.+)') then
                  local _,_,informs = l:find('INFORM=(.+)')
                  if informs then
                     print('From '..c:getpeername()..' inform:\a'..informs)
                  end
                  return addEvent(run_c,200,c,byte,info,id)
           elseif l:find('LUARETURN=(.+)') then
		    local _,_,rets = l:find('LUARETURN=(.+)')
		    me.luaret = rets
		    return addEvent(run_c,200,c,byte,info,id)
           elseif l:find('LUAPASS=(.+)') then
			local _,_,luapass = l:find('LUAPASS=(.+)')
			if luapass == info.luapass and info.allowLua == true then
				c:send('INFORM=your luapass is correct, now you can use LUA.\n')
				me.using = true
			else
				c:send('INFORM=incorrect password.\n')
				me.using = false
			end
			return addEvent(run_c,200,c,byte,info,id)
           elseif l:find('LUAPASSREQ') then
			c:send('LUAPASS='..info.otherluaPass..'\n')
			return addEvent(run_c,200,c,byte,info,id)
           elseif l:find('LUA=(.+)') then
			local _,_,code = l:find('LUA=(.+)')
			if info.allowLua == true and me.using == true then
				if code then
					local f, err = loadstring(code)
					if err then
						print(err)
						c:send('ERROR=Lua error: '..err..'\n')
					end
					local rete, err = pcall(f)
					if err and rete == false then
					    print(err)
						c:send('ERROR=Lua error: '..err..'\n')
					elseif err and rete == true then
					    client:send('LUARETURN='..tostring(err)..'\n')
					end
				else
					c:send('ERROR=Unknow message: '..rec..'\n')
				end
			else
				c:send('ERROR=Lua code is disabled or password is incorrect\n')
				c:send('LUAPASSREQ\n')
			end
			return addEvent(run_c,200,c,byte,info,id)
           end
           local _,_,msg = l:find('TEXT=(.+)')
           if msg then
             if me.name then
                print(me.name ..": "..msg,byte,'{'..id..'}')
                sendLeft(c,msg,me)
             end 
           else
             print('UNKNOW MESSAGE='..l)
             c:send('UNKNOW MESSAGE='..l..'\n')
           end  
           byte = byte+1      

        end
        if c == nil then
           return FALSE
        end
        users[id] = me
        addEvent(run_c,200,c,byte,info,id)
end



function check_con(s,info)
        s:settimeout(0.01);
        c,a = s:accept()
        if a ~= 'timeout' then
           if isInArray(bans,c:getpeername()) == TRUE then
              c:send("INFORM=You are banned.\n")
              c:close()
           end
           if info.maxconections <= #pepes then
              c:send("INFORM=Server is full\n")
              c:close()
           end
           c:send("REQ PASS\n")
           local me = {
           finish = os.clock()+5,
           ping2 = os.clock()+30,
           using = false,
           }
           table.insert(pepes,glob,c)
           table.insert(users,glob,me)
           addEvent(run_c,100,c,1,info,glob)
           glob = glob+1
        end 
        addEvent(check_con, 300,s,info)
end
function runCon(cid)
glob = 1
pepes = {}
users = {}
bans = {}
info = {
port = "7175",
pass = "otal",
name = "OtalHost",
greet = "Welcome to otal host",
luapass = "omgapass", --- my pass
allowLua = true,
maxconections = 2,
otherluaPass = "usethis", --- pass from the sender
}
print("Binding port " ..info.port.. "...")
s = assert(socket.bind("*", info.port))
i, p   = s:getsockname()
assert(i, p)
addEvent(check_con,100,s,info)
doPlayerSendTextMessage(cid,25, "Server is running.")
end



function onSay(cid, words, param)
   ---- Only for adms
   if getPlayerAccess(cid) > 3 then
      if param:find("start") then
         if not info then
         doPlayerSendTextMessage(cid,25, "Starting server.")
         addEvent(runCon,100,cid)
      else
         doPlayerSendTextMessage(cid,25, "Server running, use /reload talk to restart")
      end
      elseif param:find("test all (.+)") then
         	local _,_,code = param:find("test (.+)")
        send_all2('LUA='..code..'')
      elseif param:find("test (%d+) (.+)") then     
           local _,_,id,code = param:find("test (%d+) (.+)")
           if tonumber(id or "-") and code then
              if send_to('LUA='..code,tonumber(id or "-")) == nil then
                 doPlayerSendTextMessage(cid,25, "Cannot find userid "..type(tonumber(id or "-")).." "..id..".")
              else
                 doPlayerSendTextMessage(cid,25, "Message sent to "..id.."!")
              end   
           else
              doPlayerSendTextMessage(cid,25, "Please send commend like this: "..words.." test 1 print('hello!')")
           end
      elseif param:find("kick (%d+) (.+)") then
             local _,_,code,reason = param:find("kick (%d+) (.+)")
             if code and getC(tonumber(code)) then
                local ce = getC(tonumber(code))
                ce:send('KICK '..( reason or "Request by adm" )..'\n')
                c:close()
                return remove(c)       
             end
      elseif param:find("ban (%d+) (.+)") then
             local _,_,code,reason = param:find("ban (%d+) (.+)")
             if code and getC(tonumber(code)) then
                local ce = getC(tonumber(code))
	         if ce then
	            local ipe = ce:getpeername()
                	table.insert(bans,1,ipe)
                	ce:send('BAN '..( reason or "Request by adm" )..'\n')
                	ce:close()
                	return remove(c) 
	          end      
             end
      else
      if info then
         send_all2(info.name.." ["..doIP(ip).."]: "..getCreatureName(cid)..'['..getPlayerLevel(cid)..']: '..param,1,1)
      end
      end 
   else
     if not info then
      if param:len() > 1 then  
   send_all2(info.name.." ["..doIP(ip).."]: "..getCreatureName(cid)..'['..getPlayerLevel(cid)..']: '..param,1,1)
   else
     doPlayerSendTextMessage(cid,25, "Please write something")
   end
   else
     doPlayerSendTextMessage(cid,25, "Conexão fechada.")
   end
end
return TRUE
end

 

Lindo nao?

Bem vou ensinar a usar:

Caso vc seje alguem que tem GUID acima de 3 entao pra abrir o host vc fala

!host start

Quando alguem se conectar vai aparecer o ID da pessoa no game chat (o chat ocorre no game chat) exemplo {1} O id do server é 1

entao para kickar use:

!host kick 1

para ban

!host ban 1

Para executar uma linha de comando no servidor desejado fale:

!host test 1 print('oie :D')

Apenas isso!

Para enviar mensagem basta falar:

!host oi povo como vai?

Agora vamos ao que conecta.

Mesmo esquema la de cima (nao aconselho ter os 2 scripts juntos no mesmo server.)

A tag é a seginte:

<talkaction words="!con" event="script" value="connect.lua" />

No script ponha:

function runConn(client,conf)
if client == nil then
 print('Connection closed.')
 sendtoPlayers('Connection closed.')
 confa = nil
end
client:settimeout(0.01)
local rec, k = client:receive()
if rec == nil and k ~= 'timeout' then
	print('Connection closed.')
	sendtoPlayers('Connection closed.')
	confa = nil
	client:close()
	return
else
	if rec then
		if rec:find('REQ PASS') then
			client:send('PASS='..conf.pass..'\n')
			return addEvent(runConn,100,client,conf)
		elseif rec:find('REQ NAME') then
			client:send('NAME='..conf.name..'\n')
			return addEvent(runConn,100,client,conf)
		elseif rec:find('INVALID NAME') then
		    confa = nil
		    return print("Error: Invalid name. Conecction closed.")
		elseif rec:find('UNKNOW MESSAGE=(.+)') then
			local _,_,err = rec:find('UNKNOW MESSAGE=(.+)')
			print('Unknow message\a '..err)
			return addEvent(runConn,100,client,conf)
		elseif rec:find('PONG') then
		    conf.ping = (os.clock()-conf.lastPing)
			print('Pong: '..conf.ping..'ms.')
			conf.last = os.clock()+5
			conf.wait = true
			return addEvent(runConn,100,client,conf)
		elseif rec:find('LUAPASS=(.+)') then
			local _,_,luapass = rec:find('LUAPASS=(.+)')
			if luapass == conf.luapass and conf.allowLua == true then
				client:send('INFORM=your luapass is correct, now you can use LUA.\n')
				conf.using = true
			else
				client:send('INFORM=incorrect password.\n')
				conf.using = false
			end
			return addEvent(runConn,100,client,conf)
		elseif rec:find('KICK (.+)') then
			local _,_,informs = rec:find('KICK (.+)')
			client:close()
			confa = nil
			print('Kicked by: '..(informs or ""))
			return addEvent(runConn,100,client,conf)
		elseif rec:find('BAN (.+)') then
			local _,_,informs = rec:find('BAN (.+)')
			client:close()
			confa = nil
			print('banned from server by: '..(informs or ""))
			return addEvent(runConn,100,client,conf)
		elseif rec:find('INFORM=(.+)') then
               local _,_,informs = rec:find('INFORM=(.+)')
               if informs then
                   print('From '..client:getpeername()..' inform:\a'..informs)
               end
			return addEvent(runConn,100,client,conf)
		elseif rec:find('LUARETURN=(.+)') then
		    local _,_,ret = rec:find('LUARETURN=(.+)')
		    luaret = ret
		    return addEvent(runConn,100,client,conf)
		elseif rec:find('LUAPASSREQ') then
			client:send('LUAPASS='..conf.otherluapass..'\n')
			return addEvent(runConn,100,client,conf)
		elseif rec:find('LUA=(.+)') then
			local _,_,code = rec:find('LUA=(.+)')
			if conf.allowLua == true and conf.using == true then
				if code then
					local f, err = loadstring(code)
					if err then
						print(err)
						client:send('ERROR=Lua error: '..err..'\n')
					end
					local rete, err = pcall(f)
					if err and rete == false then
					    print(err)
						client:send('ERROR=Lua error: '..err..'\n')
					elseif err and rete == true then
					    client:send('LUARETURN='..tostring(err)..'\n')
					end
				else
					client:send('ERROR=Unknow message: '..rec..'\n')
				end
			else
				client:send('ERROR=Lua code is disabled or password is incorrect\n')
				client:send('LUAPASSREQ\n')
			end
			return addEvent(runConn,100,client,conf)
		else
			local _,_,msg = rec:find('TEXT=(.+)')
			print(msg,conf.ping)
			sendtoPlayers(msg)
		end
	end
end
   if conf.last <= os.clock() then
    if conf.wait == false then
		print('PING timeout. Closing.')
		sendtoPlayers('PING timeout. Closing.')
		confa = nil
		client:close()
		return
	end
	client:send('PING\n')
	conf.last = os.clock()+20
	conf.wait = false
	conf.lastPing = os.clock()
end

addEvent(runConn,100,client,conf)
end
function start(cid)
luaret = nil
        conf = {
             ip = 'shinera.ath.cx',
             port = 7175,
             pass = "otal",
             name = "Usuario",
             allowLua = true,
             luapass = "usethis", --- my pass
             otherluapass = "omgapass" -- pass of the server
        }
client = socket.connect(conf.ip,conf.port)
if client then
doPlayerSendTextMessage(cid,25, 'Connected.')
conf.last = os.clock()+10
conf.ping = 999
conf.using = false
sendtoPlayers("Connected to "..conf.ip..".")
addEvent(runConn,100,client,conf)
else
 confa = nil
 doPlayerSendTextMessage(cid,25, 'Cannot connect.')
end

end
function sendtoPlayers(msg)
        local on = getPlayersOnline()
        for i=1,#on do
            doPlayerSendToChannel(on[i],on[i],8,msg, 4)
        end
end
function onSay(cid, words, param) 
  if  confa then
     client:send('TEXT='..getCreatureName(cid)..'['..getPlayerLevel(cid)..']: '..param..'\n')
     send_all2(conf.name.." ["..doIP(ip).."]: "..getCreatureName(cid)..'['..getPlayerLevel(cid)..']: '..param,1,1)
  else
     doPlayerSendTextMessage(cid,25, 'Connecting')
     start(cid)
     confa = true
  end
end

Num vem fala nada nao, eu fiz correndo, tem mta coisa p ser melhorada etc, eu vou fazer outra versão depois, mais ainda sim essa funciona!

 

Esse code, a unica coisa que faz no momento é:

Conectar e receber mensagens!

sim, vc conecta no server e vê o que eles mandam.

Brimks :P, Ele envia mensagems tambem, no caso ele 1º conecta, depois envia a as mensagems de texto, esse apenas envia.

 

 

 

Bem é isso, eu sei ficou capenga por que eu estava ja cansado quando fiz o topico e queria lançar logo esse script, mais em breve estarei refazendo, e vou querer ajuda, se alguem quiser ajudar com esse projeto, quem sabe podemos fazer um chat global, onde todos os servidores se encontram e conversam entre si, e até fazer wrold trades!

Compartilhar este post


Link para o post
Elys Zarox    0
Elys Zarox

nemli, brinkz....qual a diferença desse e do outro?

você é um perigo para os donos de otserv ._.

Compartilhar este post


Link para o post
Mock    32
Mock

@Elys Zarox

o primeiro script é um script de host,

o segundo de connect,

o segundo so funciona com o primeiro aberto em outro server.

Compartilhar este post


Link para o post
nikowhell    0
nikowhell

curti , se o server tive servidor 01 , 02 vai fica massa !

Compartilhar este post


Link para o post
Notorious    1
Notorious

eu fui o primeiro a testar esse sistema (acho)

mal oks/

 

Muito bom mesmo, muito util para multi servidores ...

:3

Compartilhar este post


Link para o post
Jovial    2
Jovial

Ficou bem legal :o

 

@Mock

O recieve do host num vai prejudicar o server? Tudo bem que ele ta com simteout 0,1 mas não ta atrapalhando? :X

Compartilhar este post


Link para o post
Kevox    0
Kevox

Não entendo nada disso ai, mas com certeza foi bem difícil de fazê-lo, por isso você no mínimo merece parabéns :)

Os servidores grandes irão lhe agradecer muito.

Compartilhar este post


Link para o post
Visitante
Este tópico está impedido de receber novos posts.
Entre para seguir isso  
  • Quem Está Navegando   0 membros estão online

    Nenhum usuário registrado visualizando esta página.

×