Вопросы по 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
 
Последнее редактирование:

XRLM

Известный
2,508
843
Для того, что бы понять, почему у тебя езда без двигателя и нитро по очереди работают нужен код. Смею предположить, что ты используешь elif, нужно if. Поток создавать не обязательно, можно все в одном цикле писать. А лучше не страдать хуйней и оставить все в разных файлах
дефолт езда без двига и дефолт нитро. elseif не использую, только if. а как тогда в одном цикле все писать, если такая хуйня получается, при чем не только с ездой и нитро, вообще со всеми фукнкциями, что присутствуют в цикле. тот же рендер при посадке в авто просто пропадает. а как не страдать хуйней, если к примеру на той же проверке на софт ты можешь выгрузить 1 скрипт со всем софтом, а с 15 файлами будешь ебаться дольше.
 

манку хлебал

Потрачен
305
120
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
дефолт езда без двига и дефолт нитро. elseif не использую, только if. а как тогда в одном цикле все писать, если такая хуйня получается, при чем не только с ездой и нитро, вообще со всеми фукнкциями, что присутствуют в цикле. тот же рендер при посадке в авто просто пропадает. а как не страдать хуйней, если к примеру на той же проверке на софт ты можешь выгрузить 1 скрипт со всем софтом, а с 15 файлами будешь ебаться дольше.
Скинь код, смотреть надо
 

Andrinall

Известный
677
529

Я это вижу как-то так, если через обычный рендер.
Lua:
function main()
    repeat wait(100) until isSampAvailable()

    while true do wait(0)
        local sw, sh = getScreenResolution()
        --[[
            -- Или так ->
            renderDrawCircle({ x = sw/2, y = sh/2.5 }, sw/8, 0xFF51B1C7, 64)
           
            -- Или так ->
            renderDrawCircle(Vector(sw/2, sh/2.5, 0), sw/8, 0xFF51B1C7, 64) -- local Vector = require 'vector3d' -- в начало кода
        ]]
    end
end
function renderDrawCircle(pos, radius, color, num_segments)
-- если устанавливать слишком низкие значения num_segments - можно сделать не круг, а многоугольник
    local last_point
    local a_min, a_max = 0, math.pi*2
    local pos = pos or { x = 0, y = 0 }
    local radius = radius or 50
    local color = color or 0xFFFFFFFF
    local num_segments = num_segments or 32

    renderSetRenderState(161 --[[D3DRS_MULTISAMPLEANTIALIAS]], 1)
    for i = 0, num_segments do
        local point = a_min + (i / num_segments) * (a_max - a_min) -- взято из сурсов dear imgui
        local x = pos.x + math.cos(point) * radius
        local y = pos.y + math.sin(point) * radius
        if not last_point then
            renderDrawLine(pos.x, pos.y, x, y, 0, color)
            last_point = { x = x, y = y }
        else
            renderDrawLine(last_point.x, last_point.y, x, y, 2, color)
            last_point.x = x
            last_point.y = y
        end
    end
end

mimgui:
Lua:
local imgui = require 'mimgui'
imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
    sw, sh = getScreenResolution()
end)

imgui.OnFrame(function() return true end, function(self)
    local dl = imgui.GetBackgroundDrawList()

    dl:PathArcTo(imgui.ImVec2( sw/2, sh/2.5 ), sw/8, -0.17, math.pi*2, 64) -- если рисовать от 0 до пи*2, - будет баг в правой части круга, при большом радиусе.
    dl:PathStroke(0xFFC1B151, 1, 2)
    dl:PathClear()

    self.HideCursor = true
end)

render:
1668579647365.png


mimgui:
1668579695365.png
 

Cypher

Активный
224
55
Что тут не так? пишет <= недопустимые символы хотя по тутору у типа всё ок
(то что заблюрено не обращайте внимания оно закомменечено)
 

Вложения

  • изображение_2022-11-16_125540797.png
    изображение_2022-11-16_125540797.png
    14.8 KB · Просмотры: 24
  • Эм
Реакции: qdIbp

why ega

РП игрок
Модератор
2,521
2,184
Что тут не так? пишет <= недопустимые символы хотя по тутору у типа всё ок
(то что заблюрено не обращайте внимания оно закомменечено)
Если ты и делаешь счетчик через while, то чтобы он правильно работал, в цикле к I прибавляй 1
i = i + 1
 

percheklii

Известный
672
239
@imring дороу, шо делаю не так? использую твоя библиотеку SFLua. Ествественно без cleo,sampfuncs

Код:
if fuelID then
        text = sampTextdrawGetString(fuelID)
        fuel = text.match("%d+")
        local text = string.format("fuel: %s", fuelID)
        renderFontDrawText(font, text, 1250, 95, -1)
        
        
Ошибка в moonloader.log
'char [801]' has no member named 'match'
 

ARMOR

kjor32 is legend
Модератор
4,827
6,011
@imring дороу, шо делаю не так? использую твоя библиотеку SFLua. Ествественно без cleo,sampfuncs

Код:
if fuelID then
        text = sampTextdrawGetString(fuelID)
        fuel = text.match("%d+")
        local text = string.format("fuel: %s", fuelID)
        renderFontDrawText(font, text, 1250, 95, -1)
       
       
Ошибка в moonloader.log
'char [801]' has no member named 'match'
Вместо text.match text:match
 

why ega

РП игрок
Модератор
2,521
2,184
Как получить длину char с мимгуи, то-ли я еблан, то-ли что, но вместо текста выводяться цифры в чат, когда отправляю сообщение от себя на сервер
Lua:
local value = u8:decode(RakNet.send_rpc.slots[i][3][0])
bs:writeUInt8(value:len())
bs:writeString(value)

RakNet.send_rpc.slots[#RakNet.send_rpc.slots+1] = {name, type, new.char[200]()}
 

imring

Ride the Lightning
Всефорумный модератор
2,353
2,512
@imring дороу, шо делаю не так? использую твоя библиотеку SFLua. Ествественно без cleo,sampfuncs

Код:
if fuelID then
        text = sampTextdrawGetString(fuelID)
        fuel = text.match("%d+")
        local text = string.format("fuel: %s", fuelID)
        renderFontDrawText(font, text, 1250, 95, -1)
       
       
Ошибка в moonloader.log
'char [801]' has no member named 'match'
видимо я забыл добавить ffi.string для sampTextdrawGetString. ffi.string(sampTextdrawGetString(fuelID))
 

Sklaets

Активный
222
35
почему не работает

Lua:
script_author("squizi")

script_name("tramBot")



IAH2_version_id = 2

supportOnlineFeatures = true

local imgui = require 'imgui'

local encoding = require 'encoding'

require 'lib.moonloader'

local as_action             = require('moonloader').audiostream_state

local dlstatus              = require('moonloader').download_status



local question = {"ты тут", "как дела", "вы тут", "вы здесь", "ты сдесь", "вы сдесь"}

local answer =   {"Да, Нормально",   "дя",    "угу?","ага", "я тут"}

local imgui = require 'imgui'

local encoding = require 'encoding'

local vector = require 'vector3d'

local zxc = require 'lib.samp.events'

local fa = require 'fAwesome5'

local inicfg = require 'inicfg'

local notf = import 'imgui_notf.lua'

local effil = require("effil")

local updateid

local ffi = require('ffi')



encoding.default = 'CP1251'

u8 = encoding.UTF8



local menu = 'list'

local window, window_stats, crash = imgui.ImBool(false), imgui.ImBool(false), imgui.ImBool(false)



local control = {

    

    telegramNotf = imgui.ImBool(false),



}





imgui.SwitchContext()

local style = imgui.GetStyle()

local colors = style.Colors

local clr = imgui.Col

local ImVec4 = imgui.ImVec4



local inicfg = require 'inicfg'

local hook = require 'samp.events'



encoding.default = 'CP1251'

local u8 = encoding.UTF8

local found,finding,active,pricesetup,collectcash,runtoc,slap = false,false,false,false,false,false,false

local ax,ay,tid,fx,fy,timer,totalLn,totalCtn,nextmatch,startime,countime = 0,0,0,0,0,0,0,0,1,os.time(),os.time()



local emx,emy = -257,-1362

local matches,fmatches,calcf = {},{},{}

local spx,spy = math.random(-1,1),math.random(-1,1)

local anti_admin = require'lib.samp.events'

if not doesDirectoryExist('moonloader/config/tramBot') then

    createDirectory('moonloader/config/TramBot')

end

local mainIni = inicfg.load({

    prices = {

        cotton = 526,

        len = 652

    }, Telegram =

    {

        chat_id = '',

        token = '',

    },

})



if not doesFileExist("moonloader/config/TramBotTramBot.ini") then inicfg.save(mainIni, "TramBot/TramBot.ini") end

inik = inicfg.load(nil, 'TramBot/TramBot')



buffer_token = imgui.ImBuffer(''..inik.Telegram.token, 128)

buffer_chatid = imgui.ImBuffer(''..inik.Telegram.chat_id, 128)



chat_id = inik.Telegram.chat_id

token = inik.Telegram.token



local font_flag = require('moonloader').font_flag

local my_font = renderCreateFont('Verdana', 12, font_flag.BOLD + font_flag.SHADOW)



local status = t:status()

if status == 'completed' then

    local ok, result = r[1], r[2]

    if ok then resolve(result) else reject(result) end

elseif err then

    reject(err)

elseif status == 'canceled' then

    reject(status)

end

t:cancel(0)

end



function requestRunner()

return effil.thread(function(u, a)

    local https = require 'ssl.https'

    local ok, result = pcall(https.request, u, a)

    if ok then

        return {true, result}

    else

        return {false, result}

    end

end)

end



function async_http_request(url, args, resolve, reject)

    local runner = requestRunner()

    if not reject then reject = function() end end

    lua_thread.create(function()

        threadHandle(runner, url, args, resolve, reject)

    end)

end



function encodeUrl(str)

    str = str:gsub(' ', '%+')

    str = str:gsub('\n', '%%0A')

    return u8:encode(str, 'CP1251')

end



function sendTelegramNotification(msg)

    msg = msg:gsub('{......}', '')

    msg = encodeUrl(msg)

    async_http_request('https://api.telegram.org/bot' .. token .. '/sendMessage?chat_id=' .. chat_id .. '&text='..msg,'', function(result) end)

end



function get_telegram_updates()

    while not updateid do wait(1) end

    local runner = requestRunner()

    local reject = function() end

    local args = ''

    while true do

        url = 'https://api.telegram.org/bot'..token..'/getUpdates?chat_id='..chat_id..'&offset=-1'

        threadHandle(runner, url, args, processing_telegram_messages, reject)

        wait(0)

    end

end



function processing_telegram_messages(result)

    if result then

        local proc_table = decodeJson(result)

        if proc_table.ok then

            if #proc_table.result > 0 then

                local res_table = proc_table.result[1]

                if res_table then

                    if res_table.update_id ~= updateid then

                        updateid = res_table.update_id

                        local message_from_user = res_table.message.text

                        if message_from_user then

                            local text = u8:decode(message_from_user) .. ' '

                           if text:match('^!send') then

                                local sendMessageTelegram = text:match('^!send (.+)')

                                sampSendChat(sendMessageTelegram)

                                sendTelegramNotification('Твое сообщение отправилось')

                            elseif text:match('^!exit') then

                                sampProcessChatInput('/q')

                                sendTelegramNotification('Вышел из РПг')

                            elseif text:match('^!close') then

                                sampSendDialogResponse(15039, 1, 0, nil)

                                sendTelegramNotification('ЗАкрытие диолога успешно')

                            else

                                sendTelegramNotification('Неизвестная команда')

                            end

                        end

                    end

                end

            end

        end

    end

end



function getLastUpdate()

    async_http_request('https://api.telegram.org/bot'..token..'/getUpdates?chat_id='..chat_id..'&offset=-1','',function(result)

        if result then

            local proc_table = decodeJson(result)

            if proc_table.ok then

                if #proc_table.result > 0 then

                    local res_table = proc_table.result[1]

                    if res_table then

                        updateid = res_table.update_id

                    end

                else

                    updateid = 1

                end

            end

        end

    end)

end



--RUN





local priceCotton = mainIni.prices.cotton

local priceLen = mainIni.prices.len



local show_main_window,second_main_window,tgbot_main_window,show_stats,jump_walk,go_free,get_cash,slave =imgui.ImBool(false),imgui.ImBool(false),imgui.ImBool(false),imgui.ImBool(false),imgui.ImBool(false),imgui.ImBool(false),imgui.ImBool(false), imgui.ImBool(false)

local jump_run,clctln,clctctn = imgui.ImBool(false),imgui.ImBool(false),imgui.ImBool(false)

local lap = imgui.ImInt(696969)



function sampev.onSetRaceCheckpoint(type, pos, nextpos, radius)

    if active then

        if (pos.x ~= chkx and pos.y ~= chky) and isCharInAnyCar(PLAYER_PED) then

            tramgoCmd()



        end

        chkx = pos.x

        chky = pos.y

    end

end



function tramCmd()

    active = not active

    if active then

        printStringNow('TramActivirovan by skalets', 1000)

    else

        printStringNow('ScriptOff by skalets', 1000)

    end

end



function tramgoCmd()

    printStringNow('Pon da', 1000)

    lua_thread.create(trgo)

end



function trgo()

    ldist = 1000

    if not isCharInAnyCar(PLAYER_PED) then

        return false

    end

    veh = storeCarCharIsInNoSave(PLAYER_PED)

    if findTrainDirection(veh) then

        way = -1

    else

        way = 1

    end

    for i = 1, 180 do

        if not isCharInAnyCar(PLAYER_PED) or not active then

            return false

        end

        setTrainSpeed(veh, way*i*0.15)

        wait(100)

        if not isCharInAnyCar(PLAYER_PED) or not active then

            return false

        end

        x, y, z = getCarCoordinates(veh)

        if (getDistanceBetweenCoords2d(x, y, chkx, chky) < getCarSpeed(veh)*getCarSpeed(veh)/5) then

            currspd = getCarSpeed(veh)

            break

        end

    end

    while (active and isCharInAnyCar(PLAYER_PED) and getDistanceBetweenCoords2d(x, y, chkx, chky) > getCarSpeed(veh)*getCarSpeed(veh)/10) do

        if (chkx == -2001 or chkx >= -2003 or chkx <= -2269 or chkx == -1584  or chkx <= -2264 or chkx == -2254

        or chkx == -2050 or   (chkx < -1533 and chkx > -1534)) then

            setTrainSpeed(veh, way*7)

        else setTrainSpeed(veh, way*6)

        end

        wait(50)

        currspd = 1000

        if not isCharInAnyCar(PLAYER_PED) or not active then

            return false

        end

        x, y, z = getCarCoordinates(veh)

    end

    while (active and isCharInAnyCar(PLAYER_PED) and getDistanceBetweenCoords2d(x, y, chkx, chky) < ldist) do

        spd = math.sqrt(getDistanceBetweenCoords2d(x, y, chkx, chky)*2)

        setTrainSpeed(veh, way*spd)

        ldist = getDistanceBetweenCoords2d(x, y, chkx, chky)

        wait(25)

        if not isCharInAnyCar(PLAYER_PED) or not active then

            return false

        end

        x, y, z = getCarCoordinates(veh)

    end

    if (active and isCharInAnyCar(PLAYER_PED) and getCarSpeed(veh) > 1) then

        setTrainSpeed(veh, 0) else

        setVirtualKeyDown(0x53, true)

        wait(300)

        setVirtualKeyDown(0x53, false)

        wait(300)

        setVirtualKeyDown(0x57, true)

        wait(200)

        setVirtualKeyDown(0x57, false)

    end

end



function runToPoint(tox, toy)

    local x, y, z = getCharCoordinates(PLAYER_PED)

    local angle = getHeadingFromVector2d(tox - x, toy - y)

    local xAngle = math.random(-50, 50)/100

    setCameraPositionUnfixed(xAngle, math.rad(angle - 90))

    stopRun = false

    while getDistanceBetweenCoords2d(x, y, tox, toy) > 0.8 do

        setGameKeyState(1, -255)

        --setGameKeyState(16, 1)

        wait(1)

        x, y, z = getCharCoordinates(PLAYER_PED)

        angle = getHeadingFromVector2d(tox - x, toy - y)

        setCameraPositionUnfixed(xAngle, math.rad(angle - 90))

        if stopRun then

            stopRun = false

            break

        end

    end

end



function samp_create_sync_data(sync_type, copy_from_player)

    local ffi = require 'ffi'

    local sampfuncs = require 'sampfuncs'

    -- from SAMP.Lua

    local raknet = require 'samp.raknet'

    require 'samp.synchronization'



    copy_from_player = copy_from_player or true

    local sync_traits = {

        player = {'PlayerSyncData', raknet.PACKET.PLAYER_SYNC, sampStorePlayerOnfootData},

        vehicle = {'VehicleSyncData', raknet.PACKET.VEHICLE_SYNC, sampStorePlayerIncarData},

        passenger = {'PassengerSyncData', raknet.PACKET.PASSENGER_SYNC, sampStorePlayerPassengerData},

        aim = {'AimSyncData', raknet.PACKET.AIM_SYNC, sampStorePlayerAimData},

        trailer = {'TrailerSyncData', raknet.PACKET.TRAILER_SYNC, sampStorePlayerTrailerData},

        unoccupied = {'UnoccupiedSyncData', raknet.PACKET.UNOCCUPIED_SYNC, nil},

        bullet = {'BulletSyncData', raknet.PACKET.BULLET_SYNC, nil},

        spectator = {'SpectatorSyncData', raknet.PACKET.SPECTATOR_SYNC, nil}



local sync_info = sync_traits[sync_type]

local data_type = 'struct ' .. sync_info[1]

local data = ffi.new(data_type, {})

local raw_data_ptr = tonumber(ffi.cast('uintptr_t', ffi.new(data_type .. '*', data)))

-- copy player's sync data to the allocated memory

if copy_from_player then

    local copy_func = sync_info[3]

    if copy_func then

        local _, player_id

        if copy_from_player == true then

            _, player_id = sampGetPlayerIdByCharHandle(PLAYER_PED)

        else

            player_id = tonumber(copy_from_player)

        end

        copy_func(player_id, raw_data_ptr)

    end

end

-- function to send packet

local func_send = function()

    local bs = raknetNewBitStream()

    raknetBitStreamWriteInt8(bs, sync_info[2])

    raknetBitStreamWriteBuffer(bs, raw_data_ptr, ffi.sizeof(data))

    raknetSendBitStreamEx(bs, sampfuncs.HIGH_PRIORITY, sampfuncs.UNRELIABLE_SEQUENCED, 1)

    raknetDeleteBitStream(bs)

end

-- metatable to access sync data and 'send' function

local mt = {

    __index = function(t, index)

        return data[index]

    end,

    __newindex = function(t, index, value)

        data[index] = value

    end

}

return setmetatable({send = func_send}, mt)

end



function imgui.Link(label, description)



local size = imgui.CalcTextSize(label)

local p = imgui.GetCursorScreenPos()

local p2 = imgui.GetCursorPos()

local result = imgui.InvisibleButton(label, size)



imgui.SetCursorPos(p2)



if imgui.IsItemHovered() then

    if description then

        imgui.BeginTooltip()

        imgui.PushTextWrapPos(600)

        imgui.TextUnformatted(description)

        imgui.PopTextWrapPos()

        imgui.EndTooltip()



    end



    imgui.TextColored(imgui.GetStyle().Colors[imgui.Col.CheckMark], label)

    imgui.GetWindowDrawList():AddLine(imgui.ImVec2(p.x, p.y + size.y), imgui.ImVec2(p.x + size.x, p.y + size.y), imgui.GetColorU32(imgui.GetStyle().Colors[imgui.Col.CheckMark]))



else

    imgui.TextColored(imgui.GetStyle().Colors[imgui.Col.CheckMark], label)

end



return result

end



function imgui.OnDrawFrame()

    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(sw/2, sh/2), imgui.Cond.FirstUseEver)

    

if show_main_window.v then

    imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))

    imgui.SetNextWindowSize(imgui.ImVec2(526.0, 365.0), imgui.Cond.FirstUseEver)

    imgui.Begin('Bot Ferma', show_main_window, imgui.WindowFlags.NoResize )

    imgui.ShowCursor = true

    imgui.Checkbox(u8"Показывать статистику", show_stats)

    imgui.Checkbox(u8"Настройка Бота", second_main_window)

    imgui.Checkbox(u8'Анти админ', tgbot_main_window)

    if imgui.Button(u8'Включить/Выключить бота!') then

        sampProcessChatInput("/botmenu")

    end

    imgui.End()

end



if second_main_window.v then

    imgui.SetNextWindowSize(imgui.ImVec2(360, 330.0), imgui.Cond.FirstUseEver)

    imgui.Begin(u8"Настройка Бота", second_main_window, imgui.WindowFlags.NoResize )

    imgui.SliderInt(u8'Кол-во кругов', lap, 1, 1000000000, "%.0f")

    imgui.End()



if show_stats.v then

    local sw, sh = getScreenResolution()

   imgui.SetNextWindowPos(imgui.ImVec2(sw / 2 - sw / 2.75, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))

   imgui.SetNextWindowSize(imgui.ImVec2(sw/7, sh/4), imgui.Cond.FirstUseEver)

   imgui.Begin(u8'Статистика', show_stats)

   imgui.Text(u8'Работает бот уже как: '..SecondsToClock(countime - startime))

   if imgui.Button(u8"Очистить статистику") then

       totalLn,totalCtn,countime,startime = 0,0,os.time(),os.time()

   end

   imgui.End()

end



function hook.onServerMessage (color,text)

    if text:find('администратор') or text:find('ответил вам') or text:find('Администратор (.+) ответил вам%:') or text:find('%(%( Администратор (.+)%[%d+%]%:') or text:find('%(%( администратор .+%[(%d+)%]%:')  then

      sampAddChatMessage('{FF1800}[WARNING!!!]{A01515}[Tram{CA1111}L{FF0000}Bot]{FFFFFF}:АДМИН НАС СПАЛИЛ. ВНИМАНИЕ НА ЭКРАН', -1)

      sampAddChatMessage('{FF1800}[WARNING!!!]{A01515}[Tram{CA1111}L{FF0000}Bot]{FFFFFF}:АДМИН НАС СПАЛИЛ. ВНИМАНИЕ НА ЭКРАН', -1)

      sampAddChatMessage('{FF1800}[WARNING!!!]{A01515}[Tram{CA1111}L{FF0000}Bot]{FFFFFF}:АДМИН НАС СПАЛИЛ. ВНИМАНИЕ НА ЭКРАН', -1)

      sampAddChatMessage('{FF1800}[WARNING!!!]{A01515}[Tram{CA1111}L{FF0000}Bot]{FFFFFF}:АДМИН НАС СПАЛИЛ. ВНИМАНИЕ НА ЭКРАН', -1)

      sampAddChatMessage('{FF1800}[WARNING!!!]{A01515}[Tram{CA1111}L{FF0000}Bot]{FFFFFF}:АДМИН НАС СПАЛИЛ. ВНИМАНИЕ НА ЭКРАН', -1)

      sampAddChatMessage('{FF1800}[WARNING!!!]{A01515}[Tram{CA1111}L{FF0000}Bot]{FFFFFF}:АДМИН НАС СПАЛИЛ. ВНИМАНИЕ НА ЭКРАН', -1)

      sendTelegramNotification('походу нас админ спалил ВНИМАНИЕ на БОТА')

      sendTelegramNotification('походу нас админ спалил ВНИМАНИЕ на БОТА')

      sendTelegramNotification('походу нас админ спалил ВНИМАНИЕ на БОТА')

      sendTelegramNotification('походу нас админ спалил ВНИМАНИЕ на БОТА')

    end

 end



 function hook.onSendPlayerSync()

    if slap then

        return false

    end

end



function tgbot(arg)

    tgbot_main_window.v = not tgbot_main_window.v

end



function hook.onSetPlayerPos(pos)

    if active and found and not slap then

        slap = true

        sampAddChatMessage("{00FFC1}[Tram{00FF6C}L{00FF04}Bot] Кажется админ спалил бота! Выходим из игры!",-1)

        sampSendChat('/q')

        

    end

end

function main()

    if not isSampLoaded() or not isSampfuncsLoaded() then return end

    while not isSampAvailable() do wait(100) end

sampRegisterChatCommand('trams', tramCmd)

sampAddChatMessage("[ {f081ff} БОТ ТРАМВАЯ  {A6B8FF}  ЗАГРУЗИЛСЯ", -1)

sampAddChatMessage("[ {f081ff} АКТИВАЦИЯ {A6B8FF} - /trams", -1)

sampAddChatMessage("[ {ff2c1b} АВТОР ЭТОГО дерьма{f5ff7a}  Skalets ", -1)

sampRegisterChatCommand("botmenu", showupmenu)
 

percheklii

Известный
672
239
Кто шарит в адресах памяти? Пробовал найти адрес через CheatEngine, бездарно получилось
Как изменить кол-в строк чате через адрес памяти? Минимально 10, хочу 9. Такое возможно?
@ARMOR
 
Последнее редактирование:

kiyoshii

Новичок
26
15
хочу написать скрипт, чтобы автоматически качать ломку. Я уже его написал, но хочу сделать так, чтоб при появлении в чате текста "Недостаточно наркотиков" 2 раза нажимался энтер и продолжалась работа скрипта. Надеюсь кто-то поможет)

Вот код:

Lua:
local active = false
function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('lomka', function()
        active = not active
        sampAddChatMessage(active and 'AutoLomka ON' or 'AutoLomka OFF', -1)
    end)
    while true do
        wait(0)
        if active then
            sampSendChat("/usedrugs 3")
            wait(700)
        end
    end
end