raksamp stats

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

Известный
Автор темы
515
159
Версия MoonLoader
.026-beta
как правильно использовать эту хуйню?
RakSamp cods:
elseif text:match('^!статистика') then
    idbot, server, nick, spawn = getBotId(), getServerName(), getBotNick(), isBotSpawned()
    STM('%F0%9F%9A%B6 Cтатистика бота\nСервер: '..server.. ' \nНик: '..nick..''..idbot.. ' \n'..spawn)
    return

типо я выкупаю что надо наверное
LUA:
local ev = require 'samp.events'
function ev.getBotId()
end
но что сюда писать и т.д не ебу в душе
 

why ega

РП игрок
Модератор
2,541
2,233
как правильно использовать эту хуйню?
RakSamp cods:
elseif text:match('^!статистика') then
    idbot, server, nick, spawn = getBotId(), getServerName(), getBotNick(), isBotSpawned()
    STM('%F0%9F%9A%B6 Cтатистика бота\nСервер: '..server.. ' \nНик: '..nick..''..idbot.. ' \n'..spawn)
    return

типо я выкупаю что надо наверное
LUA:
local ev = require 'samp.events'
function ev.getBotId()
end
но что сюда писать и т.д не ебу в душе
чет вообще не понятно, шо те надо
 
  • Нравится
Реакции: qdIbp

why ega

РП игрок
Модератор
2,541
2,233
когда написал в тг !статистика оно мне вывело Сервер, id, nick, и заспавнен ли бот
Недавно писал класс для удобного взаимодействия с ТГ, но пока так и не дописал, вот крч, где-то есть говнокод
Lua:
-- объявляем прототипы экземпляров
local telegram
local utils

local Utils = {} -- создаем класс
function Utils:new() -- функция-конструктор класса
    -- прототипы модификаторов доступа
    local public
    local private
    private = {}
        
    public = {}
        -- методы класса       
        function public:encodeUrl(str)
            str = str:gsub(" ", "%+")
            str = str:gsub("\n", "%%0A")
            return u8:encode(str, "CP1251")
        end       
    
    setmetatable(public, self)
    self.__index = self; return public
end

local Telegram = {}
function Telegram:new(token, chatId)
    local public
    local private
    private = {}
        -- поля класса
        private.token = token
        private.chatId = chatId
        private.updateId = nil   
        private.commands = { -- список команд для ТГ, если будешь добавлять, то добавляй в эту таблицу в таком же формате
            {command = "^!статистика $", callback = function()                                 
                public:sendMessage(("Сервер: %s\nID: %s\nNick: %s\nSpawned: %s"):format(getServerName(), getBotId(), getBotNick(), getServerName()))                                               
            end}
        }       
    
    public = {}
        function public:sendMessage(text) -- отправка сообщения
            text = text:gsub("{......}", "")
            local params = {
                chat_id = private.chatId,
                text = utils:encodeUrl(text)
            }
            local url = ("https://api.telegram.org/bot%s/sendMessage"):format(private.token)
            local status, result = pcall(requests.get, {url = url, params = params})
            print(("%s telegram message"):format((status and (result.status_code == 200)) and
                "successfully sended" or "error while sending"
            ))           
        end

        function public:processingTelegramMessages(result) -- проверка текста принимаемого сообщения
            if result then               
                local table = json.decode(result.text)
                if table.ok then
                    if #table.result > 0 then
                        local res_table = table.result[1]
                        if res_table then
                            if res_table.update_id ~= private.updateId then
                                private.updateId = res_table.update_id
                                local message_from_user = res_table.message.text
                                if message_from_user then                                                                   
                                    local text = ("%s "):format(u8:decode(message_from_user))
                                    for _, data in ipairs(private.commands) do                                       
                                        if text:find(data.command) then                                                                                   
                                            data.callback(text:match(data.command))
                                            break                                       
                                        end
                                    end                                   
                                end
                            end
                        end
                    end
                end
            end
        end

        function public:getTelegramUpdates() -- получение сообщений от юзера
            while not private.updateId do wait(1) end -- ждем, пока не узнаем последний ID           
            while true do wait(0)
                local url = ("https://api.telegram.org/bot%s/getUpdates?chat_id=%s&offset=-1"):format(private.token, private.chatId)

                local status, result = pcall(requests.get, {url = url, params = nil})
                if status and (result.status_code == 200) then
                    self:processingTelegramMessages(result)                                           
                end
            end
        end

        function public:getLastUpdate() -- получаем последний ID сообщения
            local url = ("https://api.telegram.org/bot%s/getUpdates?chat_id=%s&offset=-1"):format(private.token, private.chatId)
            local status, result = pcall(requests.get, {url = url, params = nil})
            if status and (result.status_code == 200) then               
                local table = json.decode(result.text)               
                if table.ok then   
                    if #table.result > 0 then
                        local res_table = table.result[1]
                        if res_table then
                            private.updateId = res_table.update_id                       
                        end
                    else
                        private.updateId = 1
                    end
                end   
            end           
        end       
    
    setmetatable(public, self)
    self.__index = self; return public
end

-- создание экземпляров классов
utils = Utils:new()
telegram = Telegram:new("token", "chatId")

newTask(function() -- поток, вызываемый при запуске скрипта
    telegram:getLastUpdate()
    newTask(telegram:getTelegramUpdates())
end)
 

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

Известный
Автор темы
515
159
Недавно писал класс для удобного взаимодействия с ТГ, но пока так и не дописал, вот крч, где-то есть говнокод
Lua:
-- объявляем прототипы экземпляров
local telegram
local utils

local Utils = {} -- создаем класс
function Utils:new() -- функция-конструктор класса
    -- прототипы модификаторов доступа
    local public
    local private
    private = {}
       
    public = {}
        -- методы класса      
        function public:encodeUrl(str)
            str = str:gsub(" ", "%+")
            str = str:gsub("\n", "%%0A")
            return u8:encode(str, "CP1251")
        end      
   
    setmetatable(public, self)
    self.__index = self; return public
end

local Telegram = {}
function Telegram:new(token, chatId)
    local public
    local private
    private = {}
        -- поля класса
        private.token = token
        private.chatId = chatId
        private.updateId = nil  
        private.commands = { -- список команд для ТГ, если будешь добавлять, то добавляй в эту таблицу в таком же формате
            {command = "^!статистика $", callback = function()                                
                public:sendMessage(("Сервер: %s\nID: %s\nNick: %s\nSpawned: %s"):format(getServerName(), getBotId(), getBotNick(), getServerName()))                                              
            end}
        }      
   
    public = {}
        function public:sendMessage(text) -- отправка сообщения
            text = text:gsub("{......}", "")
            local params = {
                chat_id = private.chatId,
                text = utils:encodeUrl(text)
            }
            local url = ("https://api.telegram.org/bot%s/sendMessage"):format(private.token)
            local status, result = pcall(requests.get, {url = url, params = params})
            print(("%s telegram message"):format((status and (result.status_code == 200)) and
                "successfully sended" or "error while sending"
            ))          
        end

        function public:processingTelegramMessages(result) -- проверка текста принимаемого сообщения
            if result then              
                local table = json.decode(result.text)
                if table.ok then
                    if #table.result > 0 then
                        local res_table = table.result[1]
                        if res_table then
                            if res_table.update_id ~= private.updateId then
                                private.updateId = res_table.update_id
                                local message_from_user = res_table.message.text
                                if message_from_user then                                                                  
                                    local text = ("%s "):format(u8:decode(message_from_user))
                                    for _, data in ipairs(private.commands) do                                      
                                        if text:find(data.command) then                                                                                  
                                            data.callback(text:match(data.command))
                                            break                                      
                                        end
                                    end                                  
                                end
                            end
                        end
                    end
                end
            end
        end

        function public:getTelegramUpdates() -- получение сообщений от юзера
            while not private.updateId do wait(1) end -- ждем, пока не узнаем последний ID          
            while true do wait(0)
                local url = ("https://api.telegram.org/bot%s/getUpdates?chat_id=%s&offset=-1"):format(private.token, private.chatId)

                local status, result = pcall(requests.get, {url = url, params = nil})
                if status and (result.status_code == 200) then
                    self:processingTelegramMessages(result)                                          
                end
            end
        end

        function public:getLastUpdate() -- получаем последний ID сообщения
            local url = ("https://api.telegram.org/bot%s/getUpdates?chat_id=%s&offset=-1"):format(private.token, private.chatId)
            local status, result = pcall(requests.get, {url = url, params = nil})
            if status and (result.status_code == 200) then              
                local table = json.decode(result.text)              
                if table.ok then  
                    if #table.result > 0 then
                        local res_table = table.result[1]
                        if res_table then
                            private.updateId = res_table.update_id                      
                        end
                    else
                        private.updateId = 1
                    end
                end  
            end          
        end      
   
    setmetatable(public, self)
    self.__index = self; return public
end

-- создание экземпляров классов
utils = Utils:new()
telegram = Telegram:new("token", "chatId")

newTask(function() -- поток, вызываемый при запуске скрипта
    telegram:getLastUpdate()
    newTask(telegram:getTelegramUpdates())
end)
в каких местах тут надо токен и чат ид вставлять?
 

accord-

Потрачен
437
79
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
в каких местах тут надо токен и чат ид вставлять?
1680438425357.png


vrode
 
  • Нравится
Реакции: why ega

why ega

РП игрок
Модератор
2,541
2,233
в каких местах тут надо токен и чат ид вставлять?
в 115 строке, во время создания экземпляра класса Telegram в качестве параметра передаешь токен и чат ид

да я вишу видел ещёПосмотреть вложение 195982 поэтому спрашиваю
тут значения переформирутся, класс никак не надо менять, если только не меняешь команды (надо будет как-нибудь добавить штуку для добавления команд вне класса, чтобы не надо было лезть в его код).
И еще тебе надо вот эти либы:
Lua:
require("addon")
local requests = require("requests")
local encoding = require("encoding")
local json = require("cjson")
 

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

Известный
Автор темы
515
159
Недавно писал класс для удобного взаимодействия с ТГ, но пока так и не дописал, вот крч, где-то есть говнокод
Lua:
-- объявляем прототипы экземпляров
local telegram
local utils

local Utils = {} -- создаем класс
function Utils:new() -- функция-конструктор класса
    -- прототипы модификаторов доступа
    local public
    local private
    private = {}
       
    public = {}
        -- методы класса      
        function public:encodeUrl(str)
            str = str:gsub(" ", "%+")
            str = str:gsub("\n", "%%0A")
            return u8:encode(str, "CP1251")
        end      
   
    setmetatable(public, self)
    self.__index = self; return public
end

local Telegram = {}
function Telegram:new(token, chatId)
    local public
    local private
    private = {}
        -- поля класса
        private.token = token
        private.chatId = chatId
        private.updateId = nil  
        private.commands = { -- список команд для ТГ, если будешь добавлять, то добавляй в эту таблицу в таком же формате
            {command = "^!статистика $", callback = function()                                
                public:sendMessage(("Сервер: %s\nID: %s\nNick: %s\nSpawned: %s"):format(getServerName(), getBotId(), getBotNick(), getServerName()))                                              
            end}
        }      
   
    public = {}
        function public:sendMessage(text) -- отправка сообщения
            text = text:gsub("{......}", "")
            local params = {
                chat_id = private.chatId,
                text = utils:encodeUrl(text)
            }
            local url = ("https://api.telegram.org/bot%s/sendMessage"):format(private.token)
            local status, result = pcall(requests.get, {url = url, params = params})
            print(("%s telegram message"):format((status and (result.status_code == 200)) and
                "successfully sended" or "error while sending"
            ))          
        end

        function public:processingTelegramMessages(result) -- проверка текста принимаемого сообщения
            if result then              
                local table = json.decode(result.text)
                if table.ok then
                    if #table.result > 0 then
                        local res_table = table.result[1]
                        if res_table then
                            if res_table.update_id ~= private.updateId then
                                private.updateId = res_table.update_id
                                local message_from_user = res_table.message.text
                                if message_from_user then                                                                  
                                    local text = ("%s "):format(u8:decode(message_from_user))
                                    for _, data in ipairs(private.commands) do                                      
                                        if text:find(data.command) then                                                                                  
                                            data.callback(text:match(data.command))
                                            break                                      
                                        end
                                    end                                  
                                end
                            end
                        end
                    end
                end
            end
        end

        function public:getTelegramUpdates() -- получение сообщений от юзера
            while not private.updateId do wait(1) end -- ждем, пока не узнаем последний ID          
            while true do wait(0)
                local url = ("https://api.telegram.org/bot%s/getUpdates?chat_id=%s&offset=-1"):format(private.token, private.chatId)

                local status, result = pcall(requests.get, {url = url, params = nil})
                if status and (result.status_code == 200) then
                    self:processingTelegramMessages(result)                                          
                end
            end
        end

        function public:getLastUpdate() -- получаем последний ID сообщения
            local url = ("https://api.telegram.org/bot%s/getUpdates?chat_id=%s&offset=-1"):format(private.token, private.chatId)
            local status, result = pcall(requests.get, {url = url, params = nil})
            if status and (result.status_code == 200) then              
                local table = json.decode(result.text)              
                if table.ok then  
                    if #table.result > 0 then
                        local res_table = table.result[1]
                        if res_table then
                            private.updateId = res_table.update_id                      
                        end
                    else
                        private.updateId = 1
                    end
                end  
            end          
        end      
   
    setmetatable(public, self)
    self.__index = self; return public
end

-- создание экземпляров классов
utils = Utils:new()
telegram = Telegram:new("token", "chatId")

newTask(function() -- поток, вызываемый при запуске скрипта
    telegram:getLastUpdate()
    newTask(telegram:getTelegramUpdates())
end)
1680438800210.png
 
  • Вау
Реакции: why ega

qdIbp

Автор темы
Проверенный
1,386
1,141

why ega

РП игрок
Модератор
2,541
2,233
Добавил все таки регистрацию команд вне класса:
Lua:
-- объявляем прототипы экземпляров
local utils
local telegram

local Utils = {} -- создаем класс
function Utils:new() -- функция-конструктор класса
    -- прототипы модификаторов доступа
    local public
    local private
    private = {}
        
    public = {}
        -- методы класса
        function public:formattedNumber(num)
            return tostring(num):reverse():gsub("(%d%d%d)","%1."):gsub("%.$",""):reverse()
        end     

        function public:encodeUrl(str)
            for c in str:gmatch("[%c%p%s]") do
                if c ~= "%" then
                    local find = str:find(c, 1, true)
                    if find then
                        wait(0)
                        local char = str:sub(find, find)
                        str = str:gsub(string.format("%%%s", char), ("%%%%%02X"):format(char:byte()))
                    end
                end
            end
            return u8(str)
        end

        function public:err()
            rep = false
            packet = {}
            counter = 1
            print("an error has occured while writing data")
        end
    
    setmetatable(public, self)
    self.__index = self; return public
end

local Telegram = {}
function Telegram:new(token, chatId)
    local public
    local private
    private = {}
        -- поля класса
        private.token = token
        private.chatId = chatId
        private.updateId = nil   
        private.commands = {}       
    
    public = {}
        function public:sendMessage(text) -- отправка сообщения
            text = text:gsub("{......}", "")
            text = text:gsub("_", " ")
            local params = {
                chat_id = private.chatId,
                text = utils:encodeUrl(text)
            }
            local url = ("https://api.telegram.org/bot%s/sendMessage"):format(private.token)
            local status, result = pcall(requests.get, {url = url, params = params})
            print(("%s telegram message"):format((status and (result.status_code == 200)) and
                "successfully sended" or "error while sending"
            ))           
        end

        function public:registerCommand(command, callback) -- регистрация новой команды
            print(("a new command has been registered: \"%s\". Adress: %s"):format(command, tostring(callback):gsub("function: ", "")))
            table.insert(private.commands, {command = command, callback = callback})       
        end

        function public:processingTelegramMessages(result) -- проверка текста принимаемого сообщения
            if result then               
                local table = json.decode(result.text)
                if table.ok then
                    if #table.result > 0 then
                        local res_table = table.result[1]
                        if res_table then
                            if res_table.update_id ~= private.updateId then
                                private.updateId = res_table.update_id
                                local message_from_user = res_table.message.text
                                if message_from_user then                                                                   
                                    local text = ("%s "):format(u8:decode(message_from_user))
                                    for _, data in ipairs(private.commands) do                                                                               
                                        if text:find(data.command) then                                                                                   
                                            data.callback(text:match(data.command))
                                            break                                       
                                        end
                                    end                                   
                                end
                            end
                        end
                    end
                end
            end
        end

        function public:getTelegramUpdates() -- получение сообщения от юзера
            while not private.updateId do wait(1) end       
            while true do wait(0)
                local url = ("https://api.telegram.org/bot%s/getUpdates?chat_id=%s&offset=-1"):format(private.token, private.chatId)

                local status, result = pcall(requests.get, {url = url, params = nil})
                if status and (result.status_code == 200) then
                    self:processingTelegramMessages(result)                                           
                end
            end
        end

        function public:getLastUpdate() -- получение последнего ID сообщения
            local url = ("https://api.telegram.org/bot%s/getUpdates?chat_id=%s&offset=-1"):format(private.token, private.chatId)
            local status, result = pcall(requests.get, {url = url, params = nil})
            if status and (result.status_code == 200) then               
                local table = json.decode(result.text)               
                if table.ok then   
                    if #table.result > 0 then
                        local res_table = table.result[1]
                        if res_table then
                            private.updateId = res_table.update_id                       
                        end
                    else
                        private.updateId = 1
                    end
                end   
            end           
        end       
    
    setmetatable(public, self)
    self.__index = self; return public
end

-- создание экземпляров классов
utils = Utils:new()
telegram = Telegram:new("token", "chatId")

newTask(function() -- поток, вызываемый при запуске скрипта   
    telegram:registerCommand("^!send (.+)$", function(text) -- вызываем метод registerCommand, у которого первйы параметр - паттерн команды, а второй функция-каллбек, которая вызывается при получение команды из первого параметра       
        sendInput(text)
        telegram:sendMessage(("Сообщение успешно отправлено: %s"):format(text))       
    end)
    telegram:registerCommand("^!stats $", function() -- знак $ (окончание строки) надо ставить через пробел, т.к. скрипт видит команду как "/stats ", т.е. с пробелом
        telegram:sendMessage((Моя крутая статистика: %s"):format("..."))   
    end)

    telegram:getLastUpdate()
    newTask(telegram:getTelegramUpdates())
end)