бот с подключением к ТГ

rampage387

Новичок
Автор темы
10
1
Всем привет, нужно написать скрипт который будет кидать уведы в тг, когда выпала какая нибудь машина с ларца,
(пример выпадения) , пример уведа в тг: 21.08.2023 10:27:05 Nick испытал удачу при открытии "Ларец" и выиграл транспорт "Car"

Т.к я веб-разработчик, с этим есть трудности,
 

хромиус)

спокойно, это всего лишь слива
Друг
4,948
3,222
  • Ха-ха
Реакции: AERSQ137

AERSQ137

Активный
129
30
Всем привет, нужно написать скрипт который будет кидать уведы в тг, когда выпала какая нибудь машина с ларца,
(пример выпадения) , пример уведа в тг: 21.08.2023 10:27:05 Nick испытал удачу при открытии "Ларец" и выиграл транспорт "Car"

Т.к я веб-разработчик, с этим есть трудности,
Строчку из чатлога кинь сразу, кто за это возьмётся тот попросит:)
 

хромиус)

спокойно, это всего лишь слива
Друг
4,948
3,222
Lua:
script_name('Telegram Notifications Source')
script_authors('ronnyscripts, ronny_evans')

-- подключаем библиотеки
local effil = require("effil")
local encoding = require("encoding")
local sampev = require('sampev')
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()
    while not isSampAvailable() do wait(0) end
        lua_thread.create(get_telegram_updates)
        getLastUpdate()
    wait(-1)
end

function sampev.onServerMessage(color, msg)
    if text:find("[A-z0-9_] испытал удачу при открытии '(.+)' и выиграл транспорт: (.+)%.") then
        local larec,car = text:match("[A-z0-9_] испытал удачу при открытии '(.+)' и выиграл транспорт: (.+)%.")
        sendTelegramNotification((string.format('Ларец: %s,Транспорт:%s',larec,car)))
        end
    end
end
 

rampage387

Новичок
Автор темы
10
1
Lua:
script_name('Telegram Notifications Source')
script_authors('ronnyscripts, ronny_evans')

-- подключаем библиотеки
local effil = require("effil")
local encoding = require("encoding")
local sampev = require('sampev')
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()
    while not isSampAvailable() do wait(0) end
        lua_thread.create(get_telegram_updates)
        getLastUpdate()
    wait(-1)
end

function sampev.onServerMessage(color, msg)
    if text:find("[A-z0-9_] испытал удачу при открытии '(.+)' и выиграл транспорт: (.+)%.") then
        local larec,car = text:match("[A-z0-9_] испытал удачу при открытии '(.+)' и выиграл транспорт: (.+)%.")
        sendTelegramNotification((string.format('Ларец: %s,Транспорт:%s',larec,car)))
        end
    end
end
Script died due to an error
 

хромиус)

спокойно, это всего лишь слива
Друг
4,948
3,222
Script died due to an error
и все?больше никаких ошибок нет?

Script died due to an error
Lua:
script_name('Telegram Notifications Source')
script_authors('ronnyscripts, ronny_evans')

-- подключаем библиотеки
local effil = require("effil")
local encoding = require("encoding")
local sampev = require('lib.samp.events')
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()
    while not isSampAvailable() do wait(0) end
        lua_thread.create(get_telegram_updates)
        getLastUpdate()
    wait(-1)
end

function sampev.onServerMessage(color, msg)
    if text:find("[A-z0-9_] испытал удачу при открытии '(.+)' и выиграл транспорт: (.+)%.") then
        local larec,car = text:match("[A-z0-9_] испытал удачу при открытии '(.+)' и выиграл транспорт: (.+)%.")
        sendTelegramNotification((string.format('Ларец: %s,Транспорт:%s',larec,car)))
    end
end
 
Последнее редактирование:

rampage387

Новичок
Автор темы
10
1
и все?больше никаких ошибок нет?


Lua:
script_name('Telegram Notifications Source')
script_authors('ronnyscripts, ronny_evans')

-- подключаем библиотеки
local effil = require("effil")
local encoding = require("encoding")
local sampev = require('lib.samp.events')
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()
    while not isSampAvailable() do wait(0) end
        lua_thread.create(get_telegram_updates)
        getLastUpdate()
    wait(-1)
end

function sampev.onServerMessage(color, msg)
    if text:find("[A-z0-9_] испытал удачу при открытии '(.+)' и выиграл транспорт: (.+)%.") then
        local larec,car = text:match("[A-z0-9_] испытал удачу при открытии '(.+)' и выиграл транспорт: (.+)%.")
        sendTelegramNotification((string.format('Ларец: %s,Транспорт:%s',larec,car)))
    end
end
[ML] (error) openlarec: Script died due to an error. (79B2B5EC)

[ML] (error) Telegram Notifications Source: G:\arizona\moonloader\larec.lua:131: attempt to index global 'text' (a nil value)
stack traceback:
G:\arizona\moonloader\larec.lua:131: in function 'callback'
G:\arizona\moonloader\lib\samp\events\core.lua:79: in function <G:\arizona\moonloader\lib\samp\events\core.lua:53>
[ML] (error) Telegram Notifications Source: Script died due to an error. (79B2B8FC)
 

хромиус)

спокойно, это всего лишь слива
Друг
4,948
3,222
[ML] (error) openlarec: Script died due to an error. (79B2B5EC)

[ML] (error) Telegram Notifications Source: G:\arizona\moonloader\larec.lua:131: attempt to index global 'text' (a nil value)
stack traceback:
G:\arizona\moonloader\larec.lua:131: in function 'callback'
G:\arizona\moonloader\lib\samp\events\core.lua:79: in function <G:\arizona\moonloader\lib\samp\events\core.lua:53>
[ML] (error) Telegram Notifications Source: Script died due to an error. (79B2B8FC)
поменяй msg на text,или наоборот, как тебе удобнее
 

rampage387

Новичок
Автор темы
10
1
поменяй msg на text,или наоборот, как тебе удобнее
огромное спасибо, работает

не пришел увед

Возможно из-за этой строчки
async_http_request('https://api.telegram.org/bot' .. token .. '/sendMessage?chat_id=' .. chat_id .. '&msg='..msg,'', function(result) end) -- а тут уже отправка

чет не работает, всё сделал как ты говорил
 
Последнее редактирование:
  • Вау
Реакции: хромиус)