Ошибка при использовании цифрового текст буффера в imgui

Sadow

Известный
Автор темы
1,437
585
Версия MoonLoader
.026-beta
Скрипт и moonloader.log прикрепляю ниже.
Lua:
script_name('Stats Telegram')
script_author('Sadow')
script_description("Отправляет статистику аккаунта в телеграмм")
require 'lib.moonloader'
local sampev = require 'lib.samp.events'
local effil = require 'effil'
local imgui = require 'imgui'
local themes = import 'resource/imgui_themes.lua'
local inicfg = require 'inicfg'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local main_window_state = imgui.ImBool(false)
local text_buffer = imgui.ImBuffer(144)
local text_buffer_two = imgui.ImBuffer(144)
local text_buffer_three = imgui.ImBuffer(144)
local sw, sh = getScreenResolution()
local directIni = 'moonloader\\settings-stats-tg.ini'
local mainIni = inicfg.load(nil, directIni)
function main()
    while not isSampAvailable() do
     wait(0)
    end
    getLastUpdate()
 
    repeat
       wait(0)
    until sampIsLocalPlayerSpawned()
    getLastUpdate()
    lua_thread.create(get_telegram_updates)
 
 
     imgui.Process = false
     imgui.SwitchContext()
     themes.SwitchColorTheme(5)
 
     sampAddChatMessage("{5A90CE}[Telegram Stats] {FFFFFF}Скрипт успешно загружен!",-1)
     sampAddChatMessage("{5A90CE}[Telegram Stats] {FFFFFF}Активация: /tgstats",-1)
     sampAddChatMessage("{5A90CE}[Telegram Stats] {FFFFFF}Автор: Sadow",-1)
    sampRegisterChatCommand('tgstats', cmd_tgstats)
 
 
 
     while true do
         wait(0)
         _, idp = sampGetPlayerIdByCharHandle(PLAYER_PED)
         nick = sampGetPlayerNickname(idp)
         ip, port = sampGetCurrentServerAddress()
         name = sampGetCurrentServerName()
         score = sampGetPlayerScore(idp)
         money = getPlayerMoney()

         if main_window_state.v == false then
            imgui.Process = false
        end
    end
 end
 function cmd_tgstats(arg)
    main_window_state.v = not main_window_state.v
    imgui.Process = main_window_state.v
 end
 function imgui.Ques(text)
    imgui.SameLine()
    imgui.TextDisabled("(?)")
    if imgui.IsItemHovered() then
        imgui.BeginTooltip()
        imgui.TextUnformatted(u8(text))
        imgui.EndTooltip()
    end
end
 function imgui.OnDrawFrame()
    imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.SetNextWindowSize(imgui.ImVec2(560, 400), imgui.Cond.FirstUseEver)
    imgui.Begin(u8"Статистика Телеграмм", main_window_state, imgui.WindowFlags.NoResize)
    if imgui.InputText(u8'Токен', text_buffer) then
        mainIni.config.Token = text_buffer.v
        inicfg.save(mainIni, directIni)
    end
    imgui.SameLine(30)
    imgui.Ques("Чтобы получить токен необходимо найти в поиске @BotFather,\nзатем создать бота и в конце бот даст вам токен,\n его вставьте в это поле" )
    if imgui.InputText(u8'Чат айди', text_buffer_two) then
        mainIni.config.Chat_Id = text_buffer_two.v
        inicfg.save(mainIni, directIni)
    end
    imgui.SameLine(30)
    imgui.Ques("Чтобы получить чат айди необходимо найти в поиске @my_id_bot,\nЗатем нажать кнопку старт и вставить ID\n В это поле который дал бот" )
    if imgui.InputText(u8"Максимальное кол-во денег", text_buffer_three, imgui.InputTextFlags.CharsDecimal) then
        mainIni.config.MaxMoney = text_buffer_three.v
        inicfg.save(mainIni, directIni)
    end
    imgui.SameLine(30)
    imgui.Ques("Сюда необходимо ввести количество денег при котором\nСкрипт выйдет из игры" )
    imgui.Text(u8"Автор: Sadow")
    imgui.End()
end
chat_id = mainIni.config.Chat_Id
token = mainIni.config.Token
local updateid

function threadHandle(runner, url, args, resolve, reject)
    local t = runner(url, args)
    local r = t:get(0)
    while not r do
        r = t:get(0)
        wait(0)
    end
    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('^/start') then
                                sendTelegramNotification('Добро пожаловать!\nЕсли вы хотите узнать список команд введите: /help')
                            elseif text:match('^/help') then
                                sendTelegramNotification('Список команд:\n/stats - Узнать статистику персонажа\n/setmaxmoney - Установить кол-во денег при достижении которого персонаж выйдет из игры\n \nТакже обратите внимание!\nСкрипт работает ТОЛЬКО тогда когда вы находитесь в игре')
                            elseif text:match('^/stats') then
                                sendTelegramNotification('Ник игрока: ' .. nick .. '\nСервер: ' .. name .. '\nУровень: ' .. score .. '\nКоличество денег: ' .. money)
                                sampAddChatMessage('{5A90CE}[Telegram Stats] {FFFFFF}Была проверена ваша статистика! Убедитесь что вы не были взломаны!', -1)
                            elseif text:match('^/setmaxmoney') then
                                local arg = text:gsub('/setmaxmoney ','',1)
                                if #arg > 0 then
                                    mainIni.config.MaxMoney = arg
                                    if inicfg.save(mainIni, directIni) then
                                    sendTelegramNotification('Теперь при достижении суммы "' .. mainIni.config.MaxMoney .. '" скрипт выйдет из игры')
                                    end
                                else
                                    sendTelegramNotification('Введите количество денег при котором скрипт выйдет из игры')
                                end
                            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
lua_thread.create(function()
    while true do
        wait(0)
        money = getPlayerMoney()
        if money >= mainIni.config.MaxMoney then 
            sendTelegramNotification('Была достигнута сумма "' .. mainIni.config.MaxMoney .. '"\nСкрипт автоматически вышел из игры')
            wait(3000)
            sampSendChat('quit')
            break
        end
    end
end)
 

Вложения

  • moonloader.log
    9.7 KB · Просмотры: 6

Sadow

Известный
Автор темы
1,437
585
не совсем понял, после чего скрипт крашится?
Когда я ввожу символ в цифровой буффер сразу скрипт умирает. При этом он выполняет функцию которую должен. Сохранить в ini файл