помогите с кодом

- |2347| -

Активный
Автор темы
177
43
Версия MoonLoader
.026-beta
не приходят увидамление о покупке и продажи в TG


Снимок экрана 2024-01-17 163609.png



code:
local bank_check = false
local payday_notification_str = '%E2%9D%97__________Банковский чек__________%E2%9D%97\n'
local function collectAndSendPayDayData(text)
    local ptrs = {
        "Организационная зарплата: %$[%d%.]+",
        "Депозит в банке: %$[%d%.]+",
        "Сумма к выплате: %$[%d%.]+",
        "Текущая сумма в банке: %$[%d%.]+",
        "Текущая сумма на депозите: %$[%d%.]+"
    }

    local text = text:gsub("{%x+}", "")
    for _, v in ipairs(ptrs) do
        if text:find(v) then
            payday_notification_str = ("%s\n%s"):format(payday_notification_str, text)
        end
    end

    if text:find("В данный момент у вас %d") then
        payday_notification_str = ("%s\n%s"):format(payday_notification_str, text)
        if bank_check then
            sendTelegramNotification(("%s"):format(payday_notification_str)) -- copy string
            payday_notification_str = '%E2%9D%97__________Банковский чек__________%E2%9D%97\n'
        end
        bank_check = false
    end
end

function sampev.onServerMessage(color, text)
    if text:find('{FFFFFF}Вы успешно арендовали лавку для продажи/покупки товара!') then
      sendTelegramNotification('Ебать молодец словил лавку')
       end
    if text:find('^%[Информация%] {FFFFFF}Ваша лавка была закрыта') then
            sendTelegramNotification('Вас выкинули с вашей лавки!')
        end
        if text:find('^.+ купил у вас .+, вы получили %$%d+ от продажи %(комиссия %d процент%(а%)%)') then
            local name, product, money = text:match('^(.+) купил у вас (.+), вы получили %$([%d.,]+) от продажи %(комиссия %d процент%(а%)%)')
            local reg_text = 'Вы продали: "'..product..'" за '..money..'$ Игроку: '..name..'.'
                sendTelegramNotification(reg_text)
            end
        if text:find('^Вы купили .+ у игрока .+ за %$%d+') then
            local product, name, money = text:match('^Вы купили (.+) у игрока (.+) за %$([%d.,]+)')
            local reg_text = 'Вы купили: "'..product..'" за '..money..'$ У игрока: '..name..'.'
                sendTelegramNotification(reg_text)
            end
            if text:find('{FFFFFF}У вас есть 3 минуты, чтобы настроить товар, иначе аренда ларька будет отменена.') then
            lavka = new.bool(false)       
            end
                if text:find('Банковский чек') then bank_check = true end
               if bank_check then collectAndSendPayDayData(text) end
                end
            if Chesttimer[0] then
            if text:find('1') then
            notification = true
            end
    
end
 
  • Эм
Реакции: YarikVL

genius.company

Известный
612
286
не приходят увидамление о покупке и продажи в TG


Посмотреть вложение 229127


code:
local bank_check = false
local payday_notification_str = '%E2%9D%97__________Банковский чек__________%E2%9D%97\n'
local function collectAndSendPayDayData(text)
    local ptrs = {
        "Организационная зарплата: %$[%d%.]+",
        "Депозит в банке: %$[%d%.]+",
        "Сумма к выплате: %$[%d%.]+",
        "Текущая сумма в банке: %$[%d%.]+",
        "Текущая сумма на депозите: %$[%d%.]+"
    }

    local text = text:gsub("{%x+}", "")
    for _, v in ipairs(ptrs) do
        if text:find(v) then
            payday_notification_str = ("%s\n%s"):format(payday_notification_str, text)
        end
    end

    if text:find("В данный момент у вас %d") then
        payday_notification_str = ("%s\n%s"):format(payday_notification_str, text)
        if bank_check then
            sendTelegramNotification(("%s"):format(payday_notification_str)) -- copy string
            payday_notification_str = '%E2%9D%97__________Банковский чек__________%E2%9D%97\n'
        end
        bank_check = false
    end
end

function sampev.onServerMessage(color, text)
    if text:find('{FFFFFF}Вы успешно арендовали лавку для продажи/покупки товара!') then
      sendTelegramNotification('Ебать молодец словил лавку')
       end
    if text:find('^%[Информация%] {FFFFFF}Ваша лавка была закрыта') then
            sendTelegramNotification('Вас выкинули с вашей лавки!')
        end
        if text:find('^.+ купил у вас .+, вы получили %$%d+ от продажи %(комиссия %d процент%(а%)%)') then
            local name, product, money = text:match('^(.+) купил у вас (.+), вы получили %$([%d.,]+) от продажи %(комиссия %d процент%(а%)%)')
            local reg_text = 'Вы продали: "'..product..'" за '..money..'$ Игроку: '..name..'.'
                sendTelegramNotification(reg_text)
            end
        if text:find('^Вы купили .+ у игрока .+ за %$%d+') then
            local product, name, money = text:match('^Вы купили (.+) у игрока (.+) за %$([%d.,]+)')
            local reg_text = 'Вы купили: "'..product..'" за '..money..'$ У игрока: '..name..'.'
                sendTelegramNotification(reg_text)
            end
            if text:find('{FFFFFF}У вас есть 3 минуты, чтобы настроить товар, иначе аренда ларька будет отменена.') then
            lavka = new.bool(false)      
            end
                if text:find('Банковский чек') then bank_check = true end
               if bank_check then collectAndSendPayDayData(text) end
                end
            if Chesttimer[0] then
            if text:find('1') then
            notification = true
            end
   
end
Прикрепи фулл кол
 
  • Клоун
Реакции: Air_Official

- |2347| -

Активный
Автор темы
177
43
Прикрепи фулл кол
полный код не могу прикрепить так как не хочу сливать скрипт
все остальные текста он хукает

Предоставь функции где у тебя отправка сообщений телеграм. И ты все верно вписал ? Token, Chat id ?
все остальные сообщение приходят кроме этих
 
  • Эм
Реакции: tiktokpay и genius.company

7 СМЕРТНЫХ ГРЕХОВ

Известный
515
159
полный код не могу прикрепить так как не хочу сливать скрипт
все остальные текста он хукает


все остальные сообщение приходят кроме этих
У тебя в скрипте такая же табуляция ?
 

- |2347| -

Активный
Автор темы
177
43
Предоставь функции где у тебя отправка сообщений телеграм. И ты все верно вписал ? Token, Chat id ?
код:
function sendTelegramNotification(msg) -- функция для отправки сообщения юзеру
    msg = msg:gsub('{......}', '') --тут типо убираем цвет
    msg = encodeUrl(msg) -- ну тут мы закодируем строку
    async_http_request('https://api.telegram.org/bot' .. u8:decode(str(token)) .. '/sendMessage?chat_id=' .. u8:decode(str(chat_id)) .. '&text='..msg,'', function(result) end) -- а тут уже отправка
end

function get_telegram_updates() -- функция получения сообщений от юзера
    while not updateid do wait(1) end -- ждем пока не узнаем последний ID
    local runner = requestRunner()
    local reject = function() end
    local args = ''
    while true do
        url = 'https://api.telegram.org/bot'..u8:decode(str(token))..'/getUpdates?chat_id='..u8:decode(str(chat_id))..'&offset=-1' -- создаем ссылку
        threadHandle(runner, url, args, processing_telegram_messages, reject)
        wait(0)
    end
end

function calc(str) --это тестовая функция, её не требуется переносить в ваш код
    return assert(load("return "..str))()
end

function processing_telegram_messages(result) -- функция проверОчки того что отправил чел


        -- тута мы проверяем все ли верно
        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
                        user_idtg = res_table.message.from.id

                         if message_from_user then
                            -- и тут если чел отправил текст мы сверяем
                            local text = u8:decode(message_from_user) .. ' ' --добавляем в конец пробел дабы не произошли тех. шоколадки с командами(типо чтоб !q не считалось как !qq)
                          

                            if text:match('^/stats') then
                                telegrams()
                                elseif text:match('^/pcoff') then
                                sendTelegramNotification('компьютер будет автоматически выключен')
                                pcoffs()
                                elseif text:match('^/rec') then
                                sendTelegramNotification('переподключение к серверу 15 сек')
                                rec()
                                elseif text:match('^/status') then
                                sendStatusTg()
                                elseif text:match('^/help') then
                                sendTelegramNotification('Команды: /stats /pcoff /rec /status')     
                                else -- если же не найдется ни одна из команд выше, выведем сообщение
                                sendTelegramNotification('Неизвестная команда!')
                            
                            end
                        end
                    end
                
            end
        end
    end
end

function getLastUpdate() -- тут мы получаем последний ID сообщения, если же у вас в коде будет настройка токена и chat_id, вызовите эту функцию для того чтоб получить последнее сообщение
    async_http_request('https://api.telegram.org/bot'..u8:decode(str(token))..'/getUpdates?chat_id='..u8:decode(str(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 -- тут зададим значение 1, если таблица будет пустая
                end
            end
        end
    end)
end
 

7 СМЕРТНЫХ ГРЕХОВ

Известный
515
159
не приходят увидамление о покупке и продажи в TG


Посмотреть вложение 229127


code:
local bank_check = false
local payday_notification_str = '%E2%9D%97__________Банковский чек__________%E2%9D%97\n'
local function collectAndSendPayDayData(text)
    local ptrs = {
        "Организационная зарплата: %$[%d%.]+",
        "Депозит в банке: %$[%d%.]+",
        "Сумма к выплате: %$[%d%.]+",
        "Текущая сумма в банке: %$[%d%.]+",
        "Текущая сумма на депозите: %$[%d%.]+"
    }

    local text = text:gsub("{%x+}", "")
    for _, v in ipairs(ptrs) do
        if text:find(v) then
            payday_notification_str = ("%s\n%s"):format(payday_notification_str, text)
        end
    end

    if text:find("В данный момент у вас %d") then
        payday_notification_str = ("%s\n%s"):format(payday_notification_str, text)
        if bank_check then
            sendTelegramNotification(("%s"):format(payday_notification_str)) -- copy string
            payday_notification_str = '%E2%9D%97__________Банковский чек__________%E2%9D%97\n'
        end
        bank_check = false
    end
end

function sampev.onServerMessage(color, text)
    if text:find('{FFFFFF}Вы успешно арендовали лавку для продажи/покупки товара!') then
      sendTelegramNotification('Ебать молодец словил лавку')
       end
    if text:find('^%[Информация%] {FFFFFF}Ваша лавка была закрыта') then
            sendTelegramNotification('Вас выкинули с вашей лавки!')
        end
        if text:find('^.+ купил у вас .+, вы получили %$%d+ от продажи %(комиссия %d процент%(а%)%)') then
            local name, product, money = text:match('^(.+) купил у вас (.+), вы получили %$([%d.,]+) от продажи %(комиссия %d процент%(а%)%)')
            local reg_text = 'Вы продали: "'..product..'" за '..money..'$ Игроку: '..name..'.'
                sendTelegramNotification(reg_text)
            end
        if text:find('^Вы купили .+ у игрока .+ за %$%d+') then
            local product, name, money = text:match('^Вы купили (.+) у игрока (.+) за %$([%d.,]+)')
            local reg_text = 'Вы купили: "'..product..'" за '..money..'$ У игрока: '..name..'.'
                sendTelegramNotification(reg_text)
            end
            if text:find('{FFFFFF}У вас есть 3 минуты, чтобы настроить товар, иначе аренда ларька будет отменена.') then
            lavka = new.bool(false)    
            end
                if text:find('Банковский чек') then bank_check = true end
               if bank_check then collectAndSendPayDayData(text) end
                end
            if Chesttimer[0] then
            if text:find('1') then
            notification = true
            end
 
end
1705504643229.png

тут вообще лишний end вроде как

Так более лучше выглядит )
LUA:
function sampev.onServerMessage(color, text)
    if text:find('{FFFFFF}Вы успешно арендовали лавку для продажи/покупки товара!') then
        sendTelegramNotification('Ебать молодец словил лавку')
    end
    if text:find('^%[Информация%] {FFFFFF}Ваша лавка была закрыта') then
        sendTelegramNotification('Вас выкинули с вашей лавки!')
    end
    if text:find('^.+ купил у вас .+, вы получили %$%d+ от продажи %(комиссия %d процент%(а%)%)') then
        local name, product, money = text:match('^(.+) купил у вас (.+), вы получили %$([%d.,]+) от продажи %(комиссия %d процент%(а%)%)')
        local reg_text = 'Вы продали: "'..product..'" за '..money..'$ Игроку: '..name..'.'
        sendTelegramNotification(reg_text)
    end
    if text:find('^Вы купили .+ у игрока .+ за %$%d+') then
        local product, name, money = text:match('^Вы купили (.+) у игрока (.+) за %$([%d.,]+)')
        local reg_text = 'Вы купили: "'..product..'" за '..money..'$ У игрока: '..name..'.'
        sendTelegramNotification(reg_text)
    end
    if text:find('{FFFFFF}У вас есть 3 минуты, чтобы настроить товар, иначе аренда ларька будет отменена.') then
        lavka = new.bool(false)       
    end
    if text:find('Банковский чек') then bank_check = true end
    if bank_check then collectAndSendPayDayData(text) end
    if Chesttimer[0] then
        if text:find('1') then
            notification = true
        end
    end
end
 

- |2347| -

Активный
Автор темы
177
43
Посмотреть вложение 229149
тут вообще лишний end вроде как

Так более лучше выглядит )
LUA:
function sampev.onServerMessage(color, text)
    if text:find('{FFFFFF}Вы успешно арендовали лавку для продажи/покупки товара!') then
        sendTelegramNotification('Ебать молодец словил лавку')
    end
    if text:find('^%[Информация%] {FFFFFF}Ваша лавка была закрыта') then
        sendTelegramNotification('Вас выкинули с вашей лавки!')
    end
    if text:find('^.+ купил у вас .+, вы получили %$%d+ от продажи %(комиссия %d процент%(а%)%)') then
        local name, product, money = text:match('^(.+) купил у вас (.+), вы получили %$([%d.,]+) от продажи %(комиссия %d процент%(а%)%)')
        local reg_text = 'Вы продали: "'..product..'" за '..money..'$ Игроку: '..name..'.'
        sendTelegramNotification(reg_text)
    end
    if text:find('^Вы купили .+ у игрока .+ за %$%d+') then
        local product, name, money = text:match('^Вы купили (.+) у игрока (.+) за %$([%d.,]+)')
        local reg_text = 'Вы купили: "'..product..'" за '..money..'$ У игрока: '..name..'.'
        sendTelegramNotification(reg_text)
    end
    if text:find('{FFFFFF}У вас есть 3 минуты, чтобы настроить товар, иначе аренда ларька будет отменена.') then
        lavka = new.bool(false)      
    end
    if text:find('Банковский чек') then bank_check = true end
    if bank_check then collectAndSendPayDayData(text) end
    if Chesttimer[0] then
        if text:find('1') then
            notification = true
        end
    end
end
ничего не изменилось
 

7 СМЕРТНЫХ ГРЕХОВ

Известный
515
159
ничего не изменилось
Без фулл кода что то хз в чем проблема 😕

код:
function sendTelegramNotification(msg) -- функция для отправки сообщения юзеру
    msg = msg:gsub('{......}', '') --тут типо убираем цвет
    msg = encodeUrl(msg) -- ну тут мы закодируем строку
    async_http_request('https://api.telegram.org/bot' .. u8:decode(str(token)) .. '/sendMessage?chat_id=' .. u8:decode(str(chat_id)) .. '&text='..msg,'', function(result) end) -- а тут уже отправка
end

function get_telegram_updates() -- функция получения сообщений от юзера
    while not updateid do wait(1) end -- ждем пока не узнаем последний ID
    local runner = requestRunner()
    local reject = function() end
    local args = ''
    while true do
        url = 'https://api.telegram.org/bot'..u8:decode(str(token))..'/getUpdates?chat_id='..u8:decode(str(chat_id))..'&offset=-1' -- создаем ссылку
        threadHandle(runner, url, args, processing_telegram_messages, reject)
        wait(0)
    end
end

function calc(str) --это тестовая функция, её не требуется переносить в ваш код
    return assert(load("return "..str))()
end

function processing_telegram_messages(result) -- функция проверОчки того что отправил чел


        -- тута мы проверяем все ли верно
        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
                        user_idtg = res_table.message.from.id

                         if message_from_user then
                            -- и тут если чел отправил текст мы сверяем
                            local text = u8:decode(message_from_user) .. ' ' --добавляем в конец пробел дабы не произошли тех. шоколадки с командами(типо чтоб !q не считалось как !qq)
                        

                            if text:match('^/stats') then
                                telegrams()
                                elseif text:match('^/pcoff') then
                                sendTelegramNotification('компьютер будет автоматически выключен')
                                pcoffs()
                                elseif text:match('^/rec') then
                                sendTelegramNotification('переподключение к серверу 15 сек')
                                rec()
                                elseif text:match('^/status') then
                                sendStatusTg()
                                elseif text:match('^/help') then
                                sendTelegramNotification('Команды: /stats /pcoff /rec /status')   
                                else -- если же не найдется ни одна из команд выше, выведем сообщение
                                sendTelegramNotification('Неизвестная команда!')
                          
                            end
                        end
                    end
              
            end
        end
    end
end

function getLastUpdate() -- тут мы получаем последний ID сообщения, если же у вас в коде будет настройка токена и chat_id, вызовите эту функцию для того чтоб получить последнее сообщение
    async_http_request('https://api.telegram.org/bot'..u8:decode(str(token))..'/getUpdates?chat_id='..u8:decode(str(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 -- тут зададим значение 1, если таблица будет пустая
                end
            end
        end
    end)
end
Попробуй

LUA:
-- подключаем библиотеки
local effil = require("effil")
local encoding = require("encoding")
encoding.default = 'CP1251'
u8 = encoding.UTF8

chat_id = '' -- чат ID юзера
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 -- ждем пока не узнаем последний ID
    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('^!qq') then
                                sendTelegramNotification('Ку')
                            elseif text:match('xz') then
                                sendTelegramNotification('пАнимаю')
                            else -- если же не найдется ни одна из команд выше, выведем сообщение
                                sendTelegramNotification('Неизвестная команда!')
                            end
                        end
                    end
                end
            end
        end
    end
end

function getLastUpdate() -- тут мы получаем последний ID сообщения, если же у вас в коде будет настройка токена и chat_id, вызовите эту функцию для того чтоб получить последнее сообщение
    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 -- тут зададим значение 1, если таблица будет пустая
                end
            end
        end
    end)
end

function main()
    repeat wait(0) until isSampAvailable()
        lua_thread.create(get_telegram_updates)
        getLastUpdate()
    while true do wait(0)
    end
end

Возможно проблема в регуляркой, ты делал print?


LUA:
if text:find('^Вы купили .+ у игрока .+ за %$%d+') then
    print("Вижу текст")
    local product, name, money = text:match('^Вы купили (.+) у игрока (.+) за %$([%d.,]+)')
    local reg_text = 'Вы купили: "'..product..'" за '..money..'$ У игрока: '..name..'.'
    print(reg_text)
    sendTelegramNotification(reg_text)
end
 
Последнее редактирование:

Kvisk

Известный
205
209
Скорей всего проблема в кастомной функции encodeUrl.
В данной продаже\покупке, есть какой-то символ или не правильный перенос строки (и т.п.)
С чем функция не справляется, и возвращает пустоту. Ну, а апи тг, тебе уже пустое сообщение не отплавляет.