помощь по времени ввода команды и появления диалога

W1ll04eison

Участник
Автор темы
328
19
Версия MoonLoader
.026-beta
Вот код:
Lua:
adress = {
    ASupport = string.format("%s\\moonloader\\config\\ASupport", getGameDirectory()),
}
if not doesDirectoryExist(adress.ASupport) then createDirectory(adress.ASupport) end

require "lib.moonloader"
local encoding = require "encoding"
local inicfg = require "inicfg"
local keys = require "vkeys"
local directIni = "moonloader\\config\\ASupport\\otvets.ini"
local directIniii = "moonloader\\config\\ASupport\\pm.ini"
local sampev = require "lib.samp.events"
local imgui = require "imgui"
imgui.ToggleButton = require('imgui_addons').ToggleButton
local input = imgui.ImBuffer(256)
encoding.default = 'CP1251'
u8 = encoding.UTF8

local tag = "[Otvets]:"

local mainIni = inicfg.load({}, directIni)
if not doesFileExist("moonloader\\config\\ASupport\\otvets.ini") then
    local file = io.open("moonloader\\config\\ASupport\\otvets.ini", "w+")
    io.close(file)
end

local mainInii = inicfg.load({}, directIniii)
if not doesFileExist("moonloader\\config\\ASupport\\pm.ini") then
    local file = io.open("moonloader\\config\\ASupport\\pm.ini", "a")
    io.close(file)
end


local show_input = false

local sdutyRun = false
local sendsduty = 0
local sendSduty1 = false
local PMtext = {}
local PMid = -1
local WindowText = {}
local antiflood = 0

local w, h = getScreenResolution()

local slot = 0

local name = imgui.ImBuffer(50)
local text1 = imgui.ImBuffer(65536)


local config = {
    tag = {
        activeAutoSduty = true,
        active2 = false,
        active3 = false,
        active6 = false,
        active5 = false,
        color = 'FFFFFF',
        FontName = 'Arial',
        FontSize = '15',
        FontFlag = '13',
    },
    pos = {
        x = select(1, getScreenResolution()),
        y = select(2, getScreenResolution()),
    },
}

local cfg = inicfg.load(config, 'Otvets-settings.ini')
if not doesFileExist('config/ASupport/Otvets-settings.ini') then
    inicfg.save(config, 'Otvets-settings.ini')
end

local posX, posY = config.pos.x, config.pos.y

local array = {
    imgui_active = imgui.ImBool(false),
    imgui_active2 = imgui.ImBool(false),
    imgui_active3 = imgui.ImBool(false),
    imgui_active4 = imgui.ImBool(false),


    activeAutoSduty = imgui.ImBool(cfg.tag.activeAutoSduty),
    active2 = imgui.ImBool(cfg.tag.active2),
    active3 = imgui.ImBool(cfg.tag.active3),
    active6 = imgui.ImBool(cfg.tag.active6),
    active5 = imgui.ImBool(cfg.tag.active5),
    color = imgui.ImBuffer(tostring(cfg.tag.color), 250),
    FontName = imgui.ImBuffer(tostring(cfg.tag.FontName), 250),
    FontSize = imgui.ImBuffer(tostring(cfg.tag.FontSize), 250),
    FontFlag = imgui.ImBuffer(tostring(cfg.tag.FontFlag), 250),
    
}


function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(0) end
    sampAddChatMessage(tag.. " {FFFFFF} Скрипт успешно загружен. | by {008000}W1ll04eison", 0xFFA500)
    sampAddChatMessage(tag.. " {FFFFFF} Version 1.0.0. | Что бы открыть настройки скрипта, напишите: {FFE4B5}/pmmset", 0xFFA500)
    sampAddChatMessage(tag.. " {FFFFFF} Что бы открыть главное меню скрипта, напишите: {FFE4B5}/pmmsupport", 0xFFA500)
    sampAddChatMessage(tag.. " {FFFFFF} Что бы использовать скрипт, напишите: {FFE4B5}/pmm [id]", 0xFFA500)

    _, myID = sampGetPlayerIdByCharHandle(PLAYER_PED)
    myName = sampGetPlayerNickname(myID)
    
    sampRegisterChatCommand('pmm', function(arg)
        if arg:find('(.+)') then
            iddd = arg:match('(.+)')
            array.imgui_active2.v = true
        else
            sampAddChatMessage(tag.. ' {FF0000}Ошибка! {FFFFFF} /pmm {FFE4B5}[id]', 0xFFA500)
        end
    end)

    sampRegisterChatCommand('pmmset', function()
        array.imgui_active.v = not array.imgui_active.v
    end)

    sampRegisterChatCommand('support', function()
        array.imgui_active3.v = not array.imgui_active3.v
    end)

    font = renderCreateFont(FontName, FontSize, FontFlag)
    lua_thread.create(function()
        local res, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
        nickname = sampGetPlayerNickname(id)
        if sampGetPlayerScore(id) == 0 then sdutyRun = false end
        score = sampGetPlayerScore(id)
        if not sdutyRun and score ~= 0 and sendsduty == 0 and array.activeAutoSduty.v then
            sendsduty = 1
        end
        if array.active6.v then
            local text = sampGetChatInputText()
            if sampIsChatInputActive() and string.find(text, "%/pm (%d+)") then
                local id = string.match(text, "%/pm (%d+).+")
                if PMtext[id] ~= nil then
                    if KeyASK ~= '' then
                        ask = KeyASK
                    else
                        ask = PMtext[id]
                    end
                    renderFontDrawText(font, '{'..array.Color..'}'..ask, posX, posY, -1)
                end
            else
                KeyASK = ''
            end
        end


    end)


    while true do    --===============================[ВЫПОЛНЯЕТЬСЯ КАЖДЫЙ КАДР]==================--
    wait(0)

    inicfg.save(config, 'Otvets-settings.ini')
    config.tag.activeAutoSduty = array.activeAutoSduty.v
    config.tag.active2 = array.active2.v
    config.tag.active3 = array.active3.v
    config.tag.active6 = array.active6.v
    config.tag.active5 = array.active5.v
    config.tag.color = array.color.v
    config.tag.FontName = array.FontName.v
    config.tag.FontSize = array.FontSize.v
    config.tag.FontFlag = array.FontFlag.v



    ms = math.ceil(os.clock() * 1000 - antiflood)
    if ms > 1800  and sendsduty == 1 then
        sendsduty = 2
        sampSendChat("/sduty")
    end
    if editingPos and array.active6.v then
        showCursor(true)
        curX, curY = getCursorPos()
        posX, posY = curX, curY
        if wasKeyPressed(32) then
            sampAddChatMessage(tag..' {FFFFFF}Новое положение сохранено: {FFE4B5}Х: {00BFFF}'..curX..'{FFFFFF}, {FFE4B5}Y: {00BFFF}'..curY, 0xFFA500)
            editingPos = false
            save()
            showCursor(false)
            array.imgui_active3.v = true
        end
    end

    


    imgui.Process = array.imgui_active.v or array.imgui_active2.v or array.imgui_active3.v or array.imgui_active4.v
    end
end

function onWindowMessage(msg, wparam, lparam)
    if msg == 0x100 or msg == 0x101 then
        if (wparam == keys.VK_ESCAPE and (array.imgui_active.v or array.imgui_active2.v or array.imgui_active3.v)) and not isPauseMenuActive() then
            consumeWindowMessage(true, false)
            if msg == 0x101 then
                if array.imgui_active.v then
                    array.imgui_active.v = false;
                else array.imgui_active.v = false end

                if array.imgui_active2.v then
                    array.imgui_active2.v = false;
                else array.imgui_active2.v = false end

                if array.imgui_active3.v then
                    array.imgui_active3.v = false;
                else array.imgui_active3.v = false end
                
                if array.imgui_active4.v then
                    array.imgui_active4.v = false; array.imgui_active3.v = true;
                else array.imgui_active3.v = false end

            end
        end
    end
end

function sampev.onServerMessage(color, message)

    if message == ' Вы не саппорт' then
        array.activeAutoSduty.v = false
        sendsduty = 0
        inicfg.save(config, 'Otvets-settings.ini')
        sampAddChatMessage(tag.. ' {FFFFFF}AutoSduty {FF0000}отключен', 0xFFA500)
    end

    if message == " Рабочий день начат" and sendSduty1 then
        if sendsduty == 2 then
            sendsduty = 0
        end
        sdutyRun = true
        sendSduty1 = false
    end

    if message == " Рабочий день закончен" and sendSduty1 then
        if sendsduty == 2 then
            sendsduty = 1
        end
        sdutyRun = false
        sendSduty1 = false
    end

    if message == " Не флуди!" then
        if sendsduty == 2 then sendsduty = 1 end
    end

    if string.find(message, "..Вопрос .+%[(%d+)%].+") and color == -30648577 then
        QuestionIN = message
        local S1, S2 = string.match(message, "..Вопрос .+%[(%d+)%]<%d+>: (.+)")
        PMtext[PMid] = S2
        PMid = S1
        WindowText[#WindowText + 1] = '['..os.date("%X",os.time())..'] '..message
        IDtoWindow[#WindowText] = PMid
        if array.active2.v then
            return false
        end
    end

    if string.find(message, "...+%[.+%] to .+%[(%d+)%]: (.+)") then
        if array.active3.v and not message:find(myName) then
            return false
        end
    end

    if string.find(message, "%[(.+)|.+%] PayDay") then
        local file = io.open("moonloader\\config\\ASupport\\pm.ini", "r")
        local data, dataText, payday, strData, aHour, aOtvet = {}, {}, {}, "", 0, 0
        if file ~= nil then
            for line in file:lines() do
            local S1 = string.match(line, "%[(.+)|.+%] PayDay")
            if payday[S1] ~= nil then
                    payday[S1] = payday[S1] + 1
                else
                    payday[S1] = 1
                end
                aHour = aHour + 1
            end
            if string.find(message, "%[(.+)|.+%] .."..myName.."%[%d+%] to .+%[%d+%]: .+") then
                local S1, S2 = string.match(line, "%[(.+)|.+%] ..("..myName.."%[%d+%] to .+%[%d+%]: .+)")
                if strData == S1 then
                    data[#data] = data[#data] + 1
                else
                    strData = S1
                    data[#data + 1] = 1
                    dataText[#data] = S1
                end
                aOtvet = aOtvet + 1
            end
        end
        io.close(file)
    end   

end

function sampev.onSendChat(message) antiflood = os.clock() * 1000 end
function sampev.onSendCommand(cmd)

    if command == 'sduty' then
        sendSduty1 = true
    end


    antiflood = os.clock() * 1000
end

function imgui.OnDrawFrame()
    if array.imgui_active.v then
            imgui.ShowCursor = true
            imgui.SetNextWindowSize(imgui.ImVec2(950, 528), imgui.Cond.FirstUseEver)
            imgui.SetNextWindowPos(imgui.ImVec2(w / 2, h / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
            imgui.Begin(u8"  Настройка ответов", array.imgui_active)
            --imgui.BeginChild("", imgui.ImVec2(150, 440), true)
            if not show_input then
                if imgui.CollapsingHeader(u8'Список подпунктов') then
                    if #mainIni ~= 0 then
                        for i = 1, #mainIni do
                                if imgui.Selectable(u8(mainIni[i].name)) then
                                    name.v = u8(mainIni[i].name)
                                    text1.v = string.gsub(u8(mainIni[i].text1), "&", "\n")
                                    slot = i
                                end
                            
                        end
                    else
                        imgui.Text(u8"Тут пока ничего нет")
                    end
                    if imgui.Button(u8"Добавить в список новый подпункт") then
                        local tname = "Список ответов №" .. #mainIni+1
                        for k,v in pairs(mainIni) do
                            if mainIni[k].name == tname then
                                tname = tname .. " (1)"
                            end
                        end
                        table.insert(mainIni,{
                        name=tname,
                        text1="",})
                        inicfg.save(mainIni, directIni)
                    end
                end
            end
            imgui.Separator()
            --imgui.EndChild()
            --imgui.SameLine()
            --imgui.BeginChild(" ", imgui.ImVec2(579, 464), true)
            if slot ~= 0 then
                imgui.Text(u8"Название:")
                imgui.SameLine()
                if show_input then
                    imgui.PushItemWidth(150)
                    imgui.InputText(u8"", name)
                else
                    imgui.Text(name.v)
                end
                
                
                if show_input then
                    if imgui.Button(u8" Сохранить", imgui.ImVec2(125, 20)) then
                        mainIni[slot].name = u8:decode(name.v)
                        mainIni[slot].text1 = string.gsub(u8:decode(text1.v), "\n", "&")
                        show_input = false
                        inicfg.save(mainIni, directIni)
                        sampAddChatMessage(tag.. '{FFFFFF} Подпункт ответов {FFE4B5}"' .. u8:decode(name.v) .. '" {FFFF00}сохранен.', 0xFFA500)
                    end
                    imgui.InputTextMultiline("    ", text1, imgui.ImVec2(930, 423))
                end
                    
                
                if not show_input then
                    if imgui.Button(u8" Редактировать", imgui.ImVec2(110, 20)) then
                        show_input = true
                        inicfg.save(mainIni, directIni)
                    end
                end
                imgui.SameLine()
                if not show_input then
                    if imgui.Button(u8" Удалить", imgui.ImVec2(125, 20)) then
                        local kol = 0
                        for k, v in pairs(mainIni) do
                            kol = kol + 1
                        end
                        if kol ~= 1 then
                            table.remove(mainIni, slot)
                            inicfg.save(mainIni, directIni)
                        else
                            table.remove(mainIni, slot)
                            files = io.open('moonloader\\config\\ASupport\\otvets.ini', "w+")
                            files:close()
                        end
                        sampAddChatMessage(tag.. '{FFFFFF} Подпункт ответов {FFE4B5}"' .. u8:decode(name.v) .. '" {FF0000}удален.', 0xFFA500)
                        slot = 0
                    end
                end
                if not show_input then
                imgui.InputText(u8'Поиск', input)
                imgui.Separator()
                end
    
                if input.v ~= '' then
                    for line in text1.v:gmatch('[^\r\n]+') do
                        
                        if line:find(input.v) then
                            imgui.Text(line)
                        end
                    end
                else
                    if not show_input then
                        for line in text1.v:gmatch('[^\r\n]+') do
                        
                            if line:find(input.v) then
                                imgui.Text(line)
                            end
                        end
                    end
                end
    
            end
            --imgui.EndChild()
            --imgui.SetCursorPosY(475)
            imgui.End()
        --else
            --imgui.Process = false
        end
        
        if array.imgui_active2.v then
            imgui.ShowCursor = true
            imgui.SetNextWindowSize(imgui.ImVec2(950, 528), imgui.Cond.FirstUseEver)
            imgui.SetNextWindowPos(imgui.ImVec2(w / 2, h / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
            imgui.Begin(u8" Список ответов", array.imgui_active2)
            --imgui.BeginChild("", imgui.ImVec2(150, 440), true)
            if not show_input then
                if imgui.CollapsingHeader(u8'Список подпунктов') then
                    if #mainIni ~= 0 then
                        for i = 1, #mainIni do
                                if imgui.Selectable(u8(mainIni[i].name)) then
                                    name.v = u8(mainIni[i].name)
                                    text1.v = string.gsub(u8(mainIni[i].text1), "&", "\n")
                                    slot = i
                                end
                            
                        end
                    else
                        imgui.Text(u8"Тут пока ничего нет")
                    end

                end
            end
            imgui.Separator()
            --imgui.EndChild()
            --imgui.SameLine()
            --imgui.BeginChild(" ", imgui.ImVec2(579, 464), true)
            if slot ~= 0 then
                imgui.Text(u8"Название:")
                imgui.SameLine()
                if show_input then
                    imgui.PushItemWidth(150)
                    imgui.InputText(u8"", name)
                else
                    imgui.Text(name.v)
                end
                if not show_input then
                imgui.InputText(u8'Поиск', input)
                imgui.Separator()
                end
    
                if input.v ~= '' then
                    for line in text1.v:gmatch('[^\r\n]+') do
                        
                        if line:find(input.v) then
                            imgui.PushStyleColor(imgui.Col.HeaderHovered, 0)
                            imgui.PushStyleColor(imgui.Col.HeaderActive, 0)
                            imgui.PushStyleColor(imgui.Col.Header, 0)
                            if imgui.Selectable(line) then
                                array.imgui_active2.v = not array.imgui_active2.v
                                
                                tekst = u8:decode(line):match('^[%s]+(.+)$')
                                if tekst ~= nil then
                                    sampAddChatMessage(tekst, -1)
                                else
                                    sampSetChatInputText("/pm " .. iddd .. ' ' ..u8:decode(line))
                                    sampSetChatInputEnabled(true)
                                end
                            end
                            imgui.PopStyleColor(3)
                        end
                    end
                else
                    if not show_input then
                        for line in text1.v:gmatch('[^\r\n]+') do
                        
                            if line:find(input.v) then
                                imgui.PushStyleColor(imgui.Col.HeaderHovered, 0)
                                imgui.PushStyleColor(imgui.Col.HeaderActive, 0)
                                imgui.PushStyleColor(imgui.Col.Header, 0)
                                if imgui.Selectable(line) then
                                    array.imgui_active2.v = not array.imgui_active2.v
                                    
                                    tekst = u8:decode(line):match('^[%s]+(.+)$')
                                    if tekst ~= nil then
                                        sampAddChatMessage(tekst, -1)
                                    else
                                    sampSetChatInputText("/pm " .. iddd .. ' ' ..u8:decode(line))
                                    sampSetChatInputEnabled(true)
                                    end
                                end
                                imgui.PopStyleColor(3)
                            end
                        end
                    end
                end
    
            end
            --imgui.EndChild()
            --imgui.SetCursorPosY(475)
            imgui.End()
        --else
            --imgui.Process = false
        end

        if array.imgui_active3.v then
            _, myID = sampGetPlayerIdByCharHandle(PLAYER_PED)
            myName = sampGetPlayerNickname(myID)
            imgui.ShowCursor = true
            imgui.SetNextWindowSize(imgui.ImVec2(950, 528), imgui.Cond.FirstUseEver)
            imgui.SetNextWindowPos(imgui.ImVec2(w / 2, h / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
            imgui.Begin(u8" Список ответов", array.imgui_active3)

            imgui.Text(u8'Ваш NickName: ' .. myName) ---=============== [ + ] ========================--

            if imgui.ToggleButton(u8'AutoSduty', array.activeAutoSduty) then ---=============== [ + ] ========================--

            end

            if imgui.ToggleButton(u8'Скрывать вопросы из чата', array.active2) then ---=============== [ + ] ========================--

            end

            if imgui.ToggleButton(u8'Скрывать чужие ответы из чата', array.active3) then ---=============== [ + ] ========================--

            end

            if imgui.Button(u8'Счетчик ответов') then ---=============== [ + ] ========================--
                array.imgui_active4.v = not array.imgui_active4.v
            end

            ---------------------

            imgui.Text(u8'Тут надо будет сделать кнопку для ответа на последний вопрос')

            if imgui.ToggleButton(u8'Вопрос на экране при вводе ответа', array.active6) then

            end

            if imgui.Text(u8'Сменить позицию вопроса на экране ') then

                sampAddChatMessage(tag..' {FFFFFF}Для сохранения положения нажмите {ff004d}ПРОБЕЛ', 0xFFA500)
                editingPos = true
                showCursor(true)
                array.imgui_active3.v = false

            end


            ----------------

            imgui.Text(u8'Тут надо будет сделать кнопку показывать / скрывать окно с вопросами')

            imgui.Text(u8'Тут надо будет сделать кнопку для ответа')

            imgui.Text(u8'тут надо будет сделать Кол-во строк с вопросами')

            imgui.Text(u8'Тут надо будет сделать размер текста с воросами')

            if imgui.ToggleButton(u8'Окно с вопросами', array.active5) then

            end

            if imgui.Button('Сменить позицию окна с вопросами') then


            end

            ------------------------

            imgui.PushItemWidth(200)
            imgui.InputText(u8'##12123', array.FontName) ---=============== [ + ] ========================--

            imgui.PushItemWidth(200)
            imgui.InputText(u8'##17123', tonumber(array.FontSize)) ---=============== [ + ] ========================--

            imgui.PushItemWidth(200)
            imgui.InputText(u8'##12347123', tonumber(array.FontFlag)) ---=============== [ + ] ========================--

            imgui.PushItemWidth(200)
            imgui.InputText(u8'##123', array.color) ---=============== [ + ] ========================--

            imgui.Text(u8'Тут надо будет сделать команды скрипта')

            imgui.Text(u8'Тут надо будет сделать перехагрузку скрипта')


            imgui.End()
        end

        if array.imgui_active4.v then
            _, myID = sampGetPlayerIdByCharHandle(PLAYER_PED)
            myName = sampGetPlayerNickname(myID)
            imgui.ShowCursor = true
            imgui.SetNextWindowSize(imgui.ImVec2(950, 528), imgui.Cond.FirstUseEver)
            imgui.SetNextWindowPos(imgui.ImVec2(w / 2, h / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
            imgui.Begin(u8" Список ответов", array.imgui_active4)


            for k, v in pairs(data) do
                if payday[dataText[k]] == nil then payday[dataText[k]] = 0 end
                DiText[int] = ""

                DiText[int] = string.format("%s\t%s\t%s\t%s\n%s", dataText[k], data[k], payday[dataText[k]], (payday[dataText[k]] * 30000), DiText[int])
                DiText[int] = "Дата\tОтветы\tPayDay\tЗарплата\n"..DialogText[int]..'\nВсего:\t'..aOtvet..'\t'..aHour..'\t'..(aHour * 30000)
                imgui.Text('' .. DiText[int] .. '')


            end
            DialogText[int] = "Дата\tОтветы\tPayDay\tЗарплата\n"..DialogText[int]..'\nВсего:\t'..aOtvet..'\t'..aHour..'\t'..(aHour * 30000)




            imgui.End()
        end
end

function save()
    ini.pos.x, ini.pos.y = posX, posY
    inicfg.save(config, 'moonloader\\config\\ASupport\\otvets.txt')
end

1) При написании команды: "/support" должно открываться imgui окно "array.imgui_active3.v", но, при вводе данной команды крашит игру

2)После того как я зашел в игру, ввел пароль, то в чат автоматически должна вводится команда "/sduty".
т.е должна срабатывать функция:
Lua:
    ms = math.ceil(os.clock() * 1000 - antiflood)
    if ms > 1800  and sendsduty == 1 then
        sendsduty = 2
        sampSendChat("/sduty")
    end

Но почему то это не происходит.
Если же я в чат от руки напишу "/sduty" - то срабатывает функция:
Lua:
    if message == ' Вы не саппорт' then
        array.activeAutoSduty.v = false
        sendsduty = 0
        inicfg.save(config, 'Otvets-settings.ini')
        sampAddChatMessage(tag.. ' {FFFFFF}AutoSduty {FF0000}отключен', 0xFFA500)
    end
В принципе как и должно быть / задумывалось.
Но автоматически эта команда почему то не вводится в чат.


Буду благодарен кто поможет
 

Лебiгович

Известный
876
239
Возможные причины, почему команда "/support" крашит игру:

1. Ошибка где-то в логике обработки этой команды. Например, пытается обратиться к несуществующему индексу в массиве или передать некорректные данные в imgui.

2. Конфликт с каким-то другим скриптом.

Чтобы исправить, нужно проверить логику обработки этой команды и убедиться, что всё работает корректно. Также посмотреть логи на предмет ошибок.

По поводу автоматической команды /sduty:

Вероятные причины:

1. Условие `if ms > 1800 and sendsduty == 1` не выполняется. Например, `sendsduty` уже не равно 1 к этому моменту или `ms` меньше 1800. Нужно вывести эти значения в лог и посмотреть.

2. Ошибка при отправке команды `sampSendChat("/sduty")`. Возможно, она по какой-то причине не доходит до сервера. Нужно проверить, отправляется ли она вообще, например вывести лог при её вызове.

3. На сервере эта команда обрабатывается неправильно и поэтому не срабатывает автоматически. Нужно протестировать вручную.

В целом, нужно добавить больше логирования и отладочных выводов в скрипт, чтобы понять, где именно происходит сбой.