Broadcaster

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,767
11,220
Как избежать краш скрипта при запуске двух гта с одним и тем же скриптом? Выдает ошибку что хендлер уже зарегестрирован
 
  • Злость
Реакции: lorgon

r4nx

Известный
Автор темы
Друг
202
261
Короче обновил я эту хуету, оказывается ей кто-то пользуется лол. Из важного - теперь не будет ацкого флуда в консоль, ну вот прям совсем никакого, оставил только регистрацию хендлеров и ещё чет по мелочи. Кроме того, теперь с помощью
Lua:
broadcaster.disableContentLengthLimit()
можно отключить полностью ограничение на длину передаваемого сообщения. Делать этого не советую, потому что могут засрать вам память зафлудив пакетами, но возможность есть. Переименовал также метод proto.sendData в proto.packData потому что второе название более подходящее, но всё равно все пользуются высокоуровневым API так что похуй

и бля насыпьте что ли звездочек на гитхабе, будет хоть что на собесах показывать
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,767
11,220
Иногда крашатся ВСЕ скрипты после перезагрузки через Ctrl + r, как это пофиксить? Проблема возникает из-за скриптов с этой которые используют эту либу.
Скрипт:
Lua:
--[[
           _                       
          | |                     
       ___| |__   __ _ _ __   ___ 
      / __| '_ \ / _` | '_ \ / _ \
     | (__| | | | (_| | |_) | (_) |
      \___|_| |_|\__,_| .__/ \___/
                      | |         
                      |_|         
    https://www.blast.hk/members/112329/

]]

local broadcaster = import('lib/broadcaster.lua')
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local inicfg = require 'inicfg'
local directIni = 'BroadSosByChapo.ini'
local ini = inicfg.load(inicfg.load({
    main = {
        room = 'SOS',
        debug = false,
        ignore = false,
        myColor = '{ff004d}',
        colorIndex = 2,
        showSosTag = true,
    },
}, directIni))
inicfg.save(ini, directIni)


local colors = {
    {'RED', 0xff0000FF},
    {'Green', 0x03cc00FF},
    {'White', 0xffffffFF},
    {'Black', 0x000000FF},
    {'Purple', 0x7f00ffFF},
    {'Pink', 0xff00c8FF},
    {'Cyan', 0x00d0ffFF},
    {'Orange', 0xffa114FF},
    {'Yellow', 0xffe814FF},
    --{'#ff004d', 0xff004dFF},
}

local room = ini.main.room
local DEBUG = ini.main.debug
local ignore = ini.main.ignore
local colorIndex = ini.main.colorIndex
local showSosTag = ini.main.showSosTag

local font = renderCreateFont('Tahoma', 13, 5)
local tag = '{ff0000}(!) SOS: {ffffff}'
local enabled = false
local handler = room
local blips = {} -- list of blips
local players = {} -- list of players (for texts)
local myColor = colors[colorIndex][2]
local wait_for_response = {
    ['getUsers'] = false,
}


function save()
    ini.main.room = room
    ini.main.debug = DEBUG
    ini.main.ignore = ignore
    ini.main.colorIndex = colorIndex
    inicfg.save(ini, directIni)
end

function main()
    while not isSampAvailable() do wait(0) end
    while sampGetCurrentServerName() == 'SA-MP' do wait(0) end
    wait(100)
    
    --REG BROADCASTER HANDLER
    broadcaster.registerHandler(handler, myHandler)
    send('sos_login[login=true, id='..tostring(select(2, sampGetPlayerIdByCharHandle(PLAYER_PED)))..', color='..colors[colorIndex][2]..']')
    
    sampAddChatMessage(tag..'connected to "'..tostring(handler)..'"!') -- string надо перевести в string!

    --CMDS
    sampRegisterChatCommand('sosc', function(arg)
        chat(arg)
    end)
    sampRegisterChatCommand('sos', function(arg)
        enabled = not enabled
        if enabled then
            if #arg > 1 then
                chat('>>SOS: '..arg)
                sampAddChatMessage(tag..'sending your location with code:'..arg, -1)
            else
                sampAddChatMessage(tag..'sending your location to users!', -1)
            end
        else
            sampAddChatMessage(tag..'stopped!', -1)
        end
    end)
    sampRegisterChatCommand('sos.debug', function()
        DEBUG = not DEBUG
        sampAddChatMessage(tag..'debug mode: '..(DEBUG and 'enabled' or 'disabled'))
        save()
    end)
    sampRegisterChatCommand('sos.menu', function()
        showMenuDialog()   
    end)
    sendCycleNetBlyatMotocicl()
    while true do
        wait(0)
        if enabled then
            local resX, resY = getScreenResolution()
            renderFontDrawText(font, '{ff0000}(!) SOS:{ffffff} Active', 50, resY - 50, 0xFFFFFFFF, 0x90000000)
        end
        if showSosTag and not ignore then
            for k, v in pairs(getAllChars()) do
                _, id = sampGetPlayerIdByCharHandle(v)
                if players[id] ~= nil then
                    local data = players[id]
                    local pedx, pedy, pedz = getCharCoordinates(PLAYER_PED)
                    if isPointOnScreen(data.x, data.y, data.z, 1) and getDistanceBetweenCoords3d(pedx, pedy, pedz, data.x, data.y, data.z) < 30 then
                        local rx, ry = convert3DCoordsToScreen(data.x, data.y, data.z)
                        local text = '{ff0000}(!) SOS (!)'
                        local len = renderGetFontDrawTextLength(font, text)
                        renderFontDrawText(font, text, rx - len / 2, ry, 0xFFffffff, 0x90000000)

                        --NAME + ID
                        
                        --'{'..string.sub(tostring(bit.tohex(data.color)), 1, 6)..'}'
                        local text = 'From: '..getUserColor(data.color)..sampGetPlayerNickname(id)..' ['..id..']'
                        local len = renderGetFontDrawTextLength(font, text)
                        renderFontDrawText(font, text, rx - len / 2, ry + 20, 0xFFffffff, 0x90000000)
                    end
                end
            end
        end
        local digs = {1980, 1981, 1982}
        for i = 1, #digs do
            result, button, list, input = sampHasDialogRespond(digs[i])
            if result then
                save()
                if button == 1 then
                    if i == 1 then
                        if list == 0 then
                            enabled = not enabled
                            sampAddChatMessage(tag..(enabled and 'sending your location to users!' or 'stopped!'), -1)
                            showMenuDialog()
                        elseif list == 1 then
                            showRoomConnectDialog()
                        elseif list == 2 then
                            ignore = not ignore
                            sampAddChatMessage('Ingore = '..tostring(ignore), -1)
                            showMenuDialog()
                        elseif list == 3 then
                            showColorSelectorDialog()
                        elseif list == 4 then
                            showSosTag = not showSosTag
                            
                            showMenuDialog()
                        end
                        --sampAddChatMessage('menu dig ans', -1)
                    elseif i == 2 then
                        if #input > 3 then
                            local arg = input -- лень менять
                            sampAddChatMessage(tag..'connecting to room "'..arg..'", please wait...', -1)
                            send('sos_login[login=false, id='..select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))..', color='..colors[colorIndex][2]..']')
                            broadcaster.unregisterHandler(handler)
                            room = arg
                            handler = arg
                            save()
                            broadcaster.registerHandler(handler, myHandler)
                            send('sos_login[login=true, id='..select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))..', color='..colors[colorIndex][2]..']')
                            showMenuDialog()
                        else
                            sampAddChatMessage(tag..'Room id must be longer than 3 chars!', -1)
                            showRoomConnectDialog()
                        end
                    elseif i == 3 then
                        colorIndex = list + 1
                        sampAddChatMessage(tag..'new color: '..'{'..string.sub(tostring(bit.tohex(colors[colorIndex][2])), 1, 6)..'}'..colors[colorIndex][1], -1)
                        showMenuDialog()
                    end
                elseif button == 0 then
                    if i == 2 then
                        showMenuDialog()
                    end
                end
            end
        end
        
    end
end

function showMenuDialog()
    sampShowDialog(1980, 'SOS MENU', 'Send SOS: '..(enabled and '{35ba32}on' or '{ff004d}off')..'\nRoom: {a3a3a3}'..handler..' {454545}(click to change){ffffff}\nIgnore: '..(ignore and '{35ba32}on' or '{ff004d}off')..'\nMy color: '..'{'..string.sub(tostring(bit.tohex(colors[colorIndex][2])), 1, 6)..'}'..colors[colorIndex][1]..'\nShow "SOS" text on player: '..(showSosTag and '{35ba32}on' or '{ff004d}off'), 'Ok', 'Close', 4)
end

function showRoomConnectDialog()
    sampShowDialog(1981, 'SOS: connect to room', '{ffffff}Current room: {a3a3a3}'..room..'\n{ffffff}Enter room id\n{ff004d}Room id must be longer than 3 chars!', 'Connect', 'Cancel', 1)
end

function showColorSelectorDialog()
    local text = ''
    for i = 1, #colors do
        
        local hex_value = '{'..string.sub(tostring(bit.tohex(colors[i][2])), 1, 6)..'}'..colors[i][1]..'\n'
        text = text..hex_value
    end
    sampShowDialog(1982, 'SOS: your blip color', text, 'Select', 'Cancel', 4)
end

function getRoomUsers()
    wait_for_response['getUsers'] = true
    send('sos_request=getUsers')
end

function sendCycleNetBlyatMotocicl()
    lua_thread.create(function()
        while true do
            wait(5000)
            local x, y, z = getCharCoordinates(PLAYER_PED)
            if enabled then
                debugmsg('sended!')
                send('sos[create=true, id='..select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))..', x='..x..', y='..y..', z='..z..', color='..colors[colorIndex][2]..']')
            else
                send('sos[create=false, id='..select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))..', x='..x..', y='..y..', z='..z..', color='..colors[colorIndex][2]..']')
            end
        end
    end)
end

function send(text)
    broadcaster.sendMessage(u8(text), handler)
end

function onScriptTerminate(scr)
    if scr == thisScript() then
        removeAllBlips()
        send('sos_login[login=false, id='..select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))..', color='..colors[colorIndex][2]..']')
        broadcaster.unregisterHandler(handler)
    end
end

function removeAllBlips()
    for k, v in pairs(blips) do
        removeBlip(v)
        blips[k] = nil
        debugmsg('Blip for '..k..' was removed!')
    end
end

function getUserColor(col)
    return '{'..string.sub(tostring(bit.tohex(col)), 1, 6)..'}'
end

function chat(text)
    send('sos_chat[id='..tostring(select(2, sampGetPlayerIdByCharHandle(PLAYER_PED)))..', text='..text..', color='..colors[colorIndex][2]..']')
end

function myHandler(text)
    if text:find('sos%[create=(.+), id=(.+), x=(.+), y=(.+), z=(.+), color=(.+)%]') then
        local create, _id, _x, _y, _z, color = text:match('sos%[create=(.+), id=(.+), x=(.+), y=(.+), z=(.+), color=(.+)%]')
        local playerId, x, y, z = tonumber(_id), tonumber(_x), tonumber(_y), tonumber(_z)
        if sampIsPlayerConnected(playerId) and not ignore then
            if create == 'true' then
                if blips[playerId] == nil then
                    sampAddChatMessage(tag..'user '..getUserColor(color)..sampGetPlayerNickname(playerId)..' ['.._id..']{ffffff} send SOS', -1)
                    --printStringNow('~r~Player '.._id..' send SOS!', 2000)
                    blips[playerId] = addBlipForCoord(x, y, z)
                    players[playerId] = {x = x, y = y, z = z, color = color}
                else
                    removeBlip(blips[playerId])
                    blips[playerId] = addBlipForCoord(x, y, z)
                    players[playerId] = {x = x, y = y, z = z, color = color}
                end
                changeBlipColour(blips[playerId], color)
            else
                if blips[playerId] ~= nil then
                    sampAddChatMessage(tag..'user '..sampGetPlayerNickname(playerId)..' ['.._id..']{ffffff} don\'t need help anymore!', -1)
                    players[playerId] = nil
                    removeBlip(blips[playerId])
                    blips[playerId] = nil
                end
            end

            debugmsg('received: '..text)
            for k, v in pairs(blips) do
                debugmsg('k = '..tostring(k)..', v = '..tostring(v))
            end
        end
    elseif text:find('sos_login%[login=(.+), id=(.+), color=(.+)%]') then
        local state, id, color = text:match('sos_login%[login=(.+), id=(.+), color=(.+)%]')
        if state == 'true' then
            sampAddChatMessage(tag..'user '..getUserColor(color)..sampGetPlayerNickname(tonumber(id))..' ['..id..'] {ffffff}connected to {a3a3a3}"'..handler..'{ffffff}"!', -1)
        else
            sampAddChatMessage(tag..'user '..getUserColor(color)..sampGetPlayerNickname(tonumber(id))..' ['..id..'] {ffffff}disconnected from {a3a3a3}"'..handler..'{ffffff}"!', -1)
        end
        debugmsg('>>login')
    elseif text:find('sos_request=(.+)') then
        local request = text:match('sos_request=(.+)')
        if request == 'getUsers' then
            send('sos_request_answer[to=getUsers, data='..tostring(select(2, sampGetPlayerIdByCharHandle(PLAYER_PED)))..']')
        end
    elseif text:find('sos_request_answer[to=(.+), data=(.+)') then
        local request, data = text:match('sos_request_answer[to=(.+), data=(.+)')
        if wait_for_response[request] == true then
            debugmsg('Response for '..request..' = '..data)
            wait_for_response[request] = false
        end
    elseif text:find('sos_chat%[id=(.+), text=(.+), color=(.+)%]') then
        local id, text, color = text:match('sos_chat%[id=(.+), text=(.+), color=(.+)%]')
        sampAddChatMessage(tag..getUserColor(color)..sampGetPlayerNickname(tonumber(id))..' ['..id..']: {ffffff}'..u8:decode(text))
    else
        sampAddChatMessage(tag..'ERROR_INCORRECT_DATA_TYPE:invalid response text', -1)
        print(text)
    end
end

function debugmsg(text)
    if DEBUG then
        print(tag..'[DEBUG]: '..text)
        sampAddChatMessage(tag..'[DEBUG]: '..text, -1)
    end
end
 

r4nx

Известный
Автор темы
Друг
202
261
Иногда крашатся ВСЕ скрипты после перезагрузки через Ctrl + r, как это пофиксить? Проблема возникает из-за скриптов с этой которые используют эту либу.
Скрипт:
Lua:
--[[
           _                      
          | |                    
       ___| |__   __ _ _ __   ___
      / __| '_ \ / _` | '_ \ / _ \
     | (__| | | | (_| | |_) | (_) |
      \___|_| |_|\__,_| .__/ \___/
                      | |        
                      |_|        
    https://www.blast.hk/members/112329/

]]

local broadcaster = import('lib/broadcaster.lua')
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local inicfg = require 'inicfg'
local directIni = 'BroadSosByChapo.ini'
local ini = inicfg.load(inicfg.load({
    main = {
        room = 'SOS',
        debug = false,
        ignore = false,
        myColor = '{ff004d}',
        colorIndex = 2,
        showSosTag = true,
    },
}, directIni))
inicfg.save(ini, directIni)


local colors = {
    {'RED', 0xff0000FF},
    {'Green', 0x03cc00FF},
    {'White', 0xffffffFF},
    {'Black', 0x000000FF},
    {'Purple', 0x7f00ffFF},
    {'Pink', 0xff00c8FF},
    {'Cyan', 0x00d0ffFF},
    {'Orange', 0xffa114FF},
    {'Yellow', 0xffe814FF},
    --{'#ff004d', 0xff004dFF},
}

local room = ini.main.room
local DEBUG = ini.main.debug
local ignore = ini.main.ignore
local colorIndex = ini.main.colorIndex
local showSosTag = ini.main.showSosTag

local font = renderCreateFont('Tahoma', 13, 5)
local tag = '{ff0000}(!) SOS: {ffffff}'
local enabled = false
local handler = room
local blips = {} -- list of blips
local players = {} -- list of players (for texts)
local myColor = colors[colorIndex][2]
local wait_for_response = {
    ['getUsers'] = false,
}


function save()
    ini.main.room = room
    ini.main.debug = DEBUG
    ini.main.ignore = ignore
    ini.main.colorIndex = colorIndex
    inicfg.save(ini, directIni)
end

function main()
    while not isSampAvailable() do wait(0) end
    while sampGetCurrentServerName() == 'SA-MP' do wait(0) end
    wait(100)
   
    --REG BROADCASTER HANDLER
    broadcaster.registerHandler(handler, myHandler)
    send('sos_login[login=true, id='..tostring(select(2, sampGetPlayerIdByCharHandle(PLAYER_PED)))..', color='..colors[colorIndex][2]..']')
   
    sampAddChatMessage(tag..'connected to "'..tostring(handler)..'"!') -- string надо перевести в string!

    --CMDS
    sampRegisterChatCommand('sosc', function(arg)
        chat(arg)
    end)
    sampRegisterChatCommand('sos', function(arg)
        enabled = not enabled
        if enabled then
            if #arg > 1 then
                chat('>>SOS: '..arg)
                sampAddChatMessage(tag..'sending your location with code:'..arg, -1)
            else
                sampAddChatMessage(tag..'sending your location to users!', -1)
            end
        else
            sampAddChatMessage(tag..'stopped!', -1)
        end
    end)
    sampRegisterChatCommand('sos.debug', function()
        DEBUG = not DEBUG
        sampAddChatMessage(tag..'debug mode: '..(DEBUG and 'enabled' or 'disabled'))
        save()
    end)
    sampRegisterChatCommand('sos.menu', function()
        showMenuDialog()  
    end)
    sendCycleNetBlyatMotocicl()
    while true do
        wait(0)
        if enabled then
            local resX, resY = getScreenResolution()
            renderFontDrawText(font, '{ff0000}(!) SOS:{ffffff} Active', 50, resY - 50, 0xFFFFFFFF, 0x90000000)
        end
        if showSosTag and not ignore then
            for k, v in pairs(getAllChars()) do
                _, id = sampGetPlayerIdByCharHandle(v)
                if players[id] ~= nil then
                    local data = players[id]
                    local pedx, pedy, pedz = getCharCoordinates(PLAYER_PED)
                    if isPointOnScreen(data.x, data.y, data.z, 1) and getDistanceBetweenCoords3d(pedx, pedy, pedz, data.x, data.y, data.z) < 30 then
                        local rx, ry = convert3DCoordsToScreen(data.x, data.y, data.z)
                        local text = '{ff0000}(!) SOS (!)'
                        local len = renderGetFontDrawTextLength(font, text)
                        renderFontDrawText(font, text, rx - len / 2, ry, 0xFFffffff, 0x90000000)

                        --NAME + ID
                       
                        --'{'..string.sub(tostring(bit.tohex(data.color)), 1, 6)..'}'
                        local text = 'From: '..getUserColor(data.color)..sampGetPlayerNickname(id)..' ['..id..']'
                        local len = renderGetFontDrawTextLength(font, text)
                        renderFontDrawText(font, text, rx - len / 2, ry + 20, 0xFFffffff, 0x90000000)
                    end
                end
            end
        end
        local digs = {1980, 1981, 1982}
        for i = 1, #digs do
            result, button, list, input = sampHasDialogRespond(digs[i])
            if result then
                save()
                if button == 1 then
                    if i == 1 then
                        if list == 0 then
                            enabled = not enabled
                            sampAddChatMessage(tag..(enabled and 'sending your location to users!' or 'stopped!'), -1)
                            showMenuDialog()
                        elseif list == 1 then
                            showRoomConnectDialog()
                        elseif list == 2 then
                            ignore = not ignore
                            sampAddChatMessage('Ingore = '..tostring(ignore), -1)
                            showMenuDialog()
                        elseif list == 3 then
                            showColorSelectorDialog()
                        elseif list == 4 then
                            showSosTag = not showSosTag
                           
                            showMenuDialog()
                        end
                        --sampAddChatMessage('menu dig ans', -1)
                    elseif i == 2 then
                        if #input > 3 then
                            local arg = input -- лень менять
                            sampAddChatMessage(tag..'connecting to room "'..arg..'", please wait...', -1)
                            send('sos_login[login=false, id='..select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))..', color='..colors[colorIndex][2]..']')
                            broadcaster.unregisterHandler(handler)
                            room = arg
                            handler = arg
                            save()
                            broadcaster.registerHandler(handler, myHandler)
                            send('sos_login[login=true, id='..select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))..', color='..colors[colorIndex][2]..']')
                            showMenuDialog()
                        else
                            sampAddChatMessage(tag..'Room id must be longer than 3 chars!', -1)
                            showRoomConnectDialog()
                        end
                    elseif i == 3 then
                        colorIndex = list + 1
                        sampAddChatMessage(tag..'new color: '..'{'..string.sub(tostring(bit.tohex(colors[colorIndex][2])), 1, 6)..'}'..colors[colorIndex][1], -1)
                        showMenuDialog()
                    end
                elseif button == 0 then
                    if i == 2 then
                        showMenuDialog()
                    end
                end
            end
        end
       
    end
end

function showMenuDialog()
    sampShowDialog(1980, 'SOS MENU', 'Send SOS: '..(enabled and '{35ba32}on' or '{ff004d}off')..'\nRoom: {a3a3a3}'..handler..' {454545}(click to change){ffffff}\nIgnore: '..(ignore and '{35ba32}on' or '{ff004d}off')..'\nMy color: '..'{'..string.sub(tostring(bit.tohex(colors[colorIndex][2])), 1, 6)..'}'..colors[colorIndex][1]..'\nShow "SOS" text on player: '..(showSosTag and '{35ba32}on' or '{ff004d}off'), 'Ok', 'Close', 4)
end

function showRoomConnectDialog()
    sampShowDialog(1981, 'SOS: connect to room', '{ffffff}Current room: {a3a3a3}'..room..'\n{ffffff}Enter room id\n{ff004d}Room id must be longer than 3 chars!', 'Connect', 'Cancel', 1)
end

function showColorSelectorDialog()
    local text = ''
    for i = 1, #colors do
       
        local hex_value = '{'..string.sub(tostring(bit.tohex(colors[i][2])), 1, 6)..'}'..colors[i][1]..'\n'
        text = text..hex_value
    end
    sampShowDialog(1982, 'SOS: your blip color', text, 'Select', 'Cancel', 4)
end

function getRoomUsers()
    wait_for_response['getUsers'] = true
    send('sos_request=getUsers')
end

function sendCycleNetBlyatMotocicl()
    lua_thread.create(function()
        while true do
            wait(5000)
            local x, y, z = getCharCoordinates(PLAYER_PED)
            if enabled then
                debugmsg('sended!')
                send('sos[create=true, id='..select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))..', x='..x..', y='..y..', z='..z..', color='..colors[colorIndex][2]..']')
            else
                send('sos[create=false, id='..select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))..', x='..x..', y='..y..', z='..z..', color='..colors[colorIndex][2]..']')
            end
        end
    end)
end

function send(text)
    broadcaster.sendMessage(u8(text), handler)
end

function onScriptTerminate(scr)
    if scr == thisScript() then
        removeAllBlips()
        send('sos_login[login=false, id='..select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))..', color='..colors[colorIndex][2]..']')
        broadcaster.unregisterHandler(handler)
    end
end

function removeAllBlips()
    for k, v in pairs(blips) do
        removeBlip(v)
        blips[k] = nil
        debugmsg('Blip for '..k..' was removed!')
    end
end

function getUserColor(col)
    return '{'..string.sub(tostring(bit.tohex(col)), 1, 6)..'}'
end

function chat(text)
    send('sos_chat[id='..tostring(select(2, sampGetPlayerIdByCharHandle(PLAYER_PED)))..', text='..text..', color='..colors[colorIndex][2]..']')
end

function myHandler(text)
    if text:find('sos%[create=(.+), id=(.+), x=(.+), y=(.+), z=(.+), color=(.+)%]') then
        local create, _id, _x, _y, _z, color = text:match('sos%[create=(.+), id=(.+), x=(.+), y=(.+), z=(.+), color=(.+)%]')
        local playerId, x, y, z = tonumber(_id), tonumber(_x), tonumber(_y), tonumber(_z)
        if sampIsPlayerConnected(playerId) and not ignore then
            if create == 'true' then
                if blips[playerId] == nil then
                    sampAddChatMessage(tag..'user '..getUserColor(color)..sampGetPlayerNickname(playerId)..' ['.._id..']{ffffff} send SOS', -1)
                    --printStringNow('~r~Player '.._id..' send SOS!', 2000)
                    blips[playerId] = addBlipForCoord(x, y, z)
                    players[playerId] = {x = x, y = y, z = z, color = color}
                else
                    removeBlip(blips[playerId])
                    blips[playerId] = addBlipForCoord(x, y, z)
                    players[playerId] = {x = x, y = y, z = z, color = color}
                end
                changeBlipColour(blips[playerId], color)
            else
                if blips[playerId] ~= nil then
                    sampAddChatMessage(tag..'user '..sampGetPlayerNickname(playerId)..' ['.._id..']{ffffff} don\'t need help anymore!', -1)
                    players[playerId] = nil
                    removeBlip(blips[playerId])
                    blips[playerId] = nil
                end
            end

            debugmsg('received: '..text)
            for k, v in pairs(blips) do
                debugmsg('k = '..tostring(k)..', v = '..tostring(v))
            end
        end
    elseif text:find('sos_login%[login=(.+), id=(.+), color=(.+)%]') then
        local state, id, color = text:match('sos_login%[login=(.+), id=(.+), color=(.+)%]')
        if state == 'true' then
            sampAddChatMessage(tag..'user '..getUserColor(color)..sampGetPlayerNickname(tonumber(id))..' ['..id..'] {ffffff}connected to {a3a3a3}"'..handler..'{ffffff}"!', -1)
        else
            sampAddChatMessage(tag..'user '..getUserColor(color)..sampGetPlayerNickname(tonumber(id))..' ['..id..'] {ffffff}disconnected from {a3a3a3}"'..handler..'{ffffff}"!', -1)
        end
        debugmsg('>>login')
    elseif text:find('sos_request=(.+)') then
        local request = text:match('sos_request=(.+)')
        if request == 'getUsers' then
            send('sos_request_answer[to=getUsers, data='..tostring(select(2, sampGetPlayerIdByCharHandle(PLAYER_PED)))..']')
        end
    elseif text:find('sos_request_answer[to=(.+), data=(.+)') then
        local request, data = text:match('sos_request_answer[to=(.+), data=(.+)')
        if wait_for_response[request] == true then
            debugmsg('Response for '..request..' = '..data)
            wait_for_response[request] = false
        end
    elseif text:find('sos_chat%[id=(.+), text=(.+), color=(.+)%]') then
        local id, text, color = text:match('sos_chat%[id=(.+), text=(.+), color=(.+)%]')
        sampAddChatMessage(tag..getUserColor(color)..sampGetPlayerNickname(tonumber(id))..' ['..id..']: {ffffff}'..u8:decode(text))
    else
        sampAddChatMessage(tag..'ERROR_INCORRECT_DATA_TYPE:invalid response text', -1)
        print(text)
    end
end

function debugmsg(text)
    if DEBUG then
        print(tag..'[DEBUG]: '..text)
        sampAddChatMessage(tag..'[DEBUG]: '..text, -1)
    end
end
скинь лог при краше
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,767
11,220
скинь лог при краше
кину когда еще раз "словлю" этот баг.
Еще пару вопросов:
1. будет ли добавлена функция на проверку хендлера на существование? Или фикс краша скрипта если хендлер который я пытаюсь зарегать уже есть?
2. почему при отправке
Lua:
            local x, y, z = getCharCoordinates(PLAYER_PED)
            data = 'sos[create='..tostring(enabled)..', id='..select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))..', x='..x..', y='..y..', z='..z..', color='..colors[colorIndex][2]..']'
            debugmsg('SENDED DATA: '..data)
            send(data)
пользователь получает sos[create=false, id=23, x=1352.1287841797,7]?
я предполагал что есть некая максимальная длина "сообщения", однако часть не обрывается (там есть "]"), а так же broadcaster.disableContentLengthLimit() после регистрации хендлера не помогло
Lua:
function send(text)
    broadcaster.sendMessage(text, handler)
end
даже такое сообщение не обрезается:
Lua:
[ML] (script) BroadSOS by chapo.lua: (!) SOS: [ERROR:ERROR_INCORRECT_DATA_TYPE]: len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.1

upd. словил ошибку, после нажатия ctrl + r все скрипты выгрузились, ошибок в мунлоге вроде как нет
 

Вложения

  • moonloader.log
    102.8 KB · Просмотры: 5
Последнее редактирование:

r4nx

Известный
Автор темы
Друг
202
261
кину когда еще раз "словлю" этот баг.
Еще пару вопросов:
1. будет ли добавлена функция на проверку хендлера на существование? Или фикс краша скрипта если хендлер который я пытаюсь зарегать уже есть?
2. почему при отправке
Lua:
            local x, y, z = getCharCoordinates(PLAYER_PED)
            data = 'sos[create='..tostring(enabled)..', id='..select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))..', x='..x..', y='..y..', z='..z..', color='..colors[colorIndex][2]..']'
            debugmsg('SENDED DATA: '..data)
            send(data)
пользователь получает sos[create=false, id=23, x=1352.1287841797,7]?
я предполагал что есть некая максимальная длина "сообщения", однако часть не обрывается (там есть "]"), а так же broadcaster.disableContentLengthLimit() после регистрации хендлера не помогло
Lua:
function send(text)
    broadcaster.sendMessage(text, handler)
end
даже такое сообщение не обрезается:
Lua:
[ML] (script) BroadSOS by chapo.lua: (!) SOS: [ERROR:ERROR_INCORRECT_DATA_TYPE]: len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.len_test.1

upd. словил ошибку, после нажатия ctrl + r все скрипты выгрузились, ошибок в мунлоге вроде как нет
Насчет того как фиксить краш при регистрации уже зареганого хендлера - вызывай broadcaster.registerHandler() с помощью pcall, то есть что-то вроде local status, err = pcall(broadcaster.registerHandler(...)) и дальше чекаешь - если status равен true то всё ок, если нет то нет, соответственно.
По поводу обрывания сообщения звучит как-то очень странно и вероятнее всего проблема не в броадкастере, потому что у меня такого лично не было ни разу и никто подобное не репортил ещё, да и в логах у тебя сообщения полностью приходят.
Ну, а краш - подозреваю тут дело либо в реге/анреге хендлеров, либо в порядке выгрузки скриптов, гляну как будет время. Добавлю функцию проверки существования хендлера - можешь попробовать вызывать её перед регистрацией и разрегистрацией, мб что-то прояснится
 
  • Нравится
Реакции: chapo

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,767
11,220
По поводу обрывания сообщения звучит как-то очень странно и вероятнее всего проблема не в броадкастере, потому что у меня такого лично не было ни разу и никто подобное не репортил ещё, да и в логах у тебя сообщения полностью приходят.
Я кинул скрипт челу, он в свою очередь кинул скрипт своим друзьям, и иногда у него приходят "сломанные" сообщения, я не думаю что кто-то из них менял код. В коде скрипта прописано что если переданный текст не подходит (text:find), то через принт выводить сообщение которое вызвало ошибку, вот оно:
Lua:
[20:06:01.551448] (script)    broadcaster.lua: [DEBUG 20:06:01] ...tar Games\GTA San Andreas\moonloader\lib\broadcaster.lua:111: got handler id: "SOS"
[20:06:01.551448] (script)    BroadSOS by chapo.lua: sos[create=true, id=146,59, color=63701247]
. Как оно обрезаться не в конце и не в начале, а в середине? (146- ид, 59 - фрагмент координат игрока с 146 идом)



1637959474407.png
 

Kuharz

Известный
401
153
Попробовал ща на ерп и аризоне свой старый скрипт с этой либой заюзать, а он перестал работать. Я думал у меня косяк, но скачал из темы файл case, он тоже не робит. Ну т.е. отправляю сообщение, но оно не доходит до второго юзера. @chapo твои скрипты с этой либой работают до сих пор?
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,767
11,220
Попробовал ща на ерп и аризоне свой старый скрипт с этой либой заюзать, а он перестал работать. Я думал у меня косяк, но скачал из темы файл case, он тоже не робит. Ну т.е. отправляю сообщение, но оно не доходит до второго юзера. @chapo твои скрипты с этой либой работают до сих пор?
на арз больше не работает, подтверждаю
Lua:
local broadcaster = import('lib/broadcaster.lua')
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

function main()
    while not isSampAvailable() do wait(0) end
    wait(100)
    broadcaster.registerHandler('myhndl', myHandler)
    sampRegisterChatCommand('brc', function(arg)
        broadcaster.sendMessage(u8(arg), 'myhndl')
    end)
    wait(-1)
end

function myHandler(message)
    sampAddChatMessage('New message: ' .. u8:decode(message), 0xAAAAAA)
end

function onScriptTerminate(scr)
    if scr == thisScript() then
        broadcaster.unregisterHandler('myhndl')
    end
end
 

qdIbp

Автор темы
Проверенный
1,386
1,139
как с помощью этой библии, прогрузить зону стрима друга/товарища, если он не в моей зоне стрима?
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,767
11,220
как с помощью этой библии, прогрузить зону стрима друга/товарища, если он не в моей зоне стрима?
Можешь в сообщении передавать всю структуру playerSync, потом создавать педа через createChar и устанавливать ему положение и т.д. из полученного сообщения