rakbot как достать переменную из тг

bigg. baby

Новичок
Автор темы
1
0
Версия MoonLoader
.026-beta
задача такова, в основном скрипте есть к примеру команда бан, мне нужно достать ее переменные, и передать их в скрипт с тг для выполнения прямиком из него
 
Решение
для сампа:
ffi                 = require 'ffi'
inicfg              = require 'inicfg'
effil               = require("effil")
encoding            = require("encoding")
encoding.default    = 'CP1251'
u8 = encoding.UTF8

local Telegram = {
   Token = "", -- токен
   ChatId = "" -- твой айди в телеге
}
local updateid

function main()
    while not isSampAvailable() do wait(0) end
    getLastUpdate()
    lua_thread.create(get_telegram_updates)
    while true do
        wait(0)
    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 wait(100)...

why ega

РП игрок
Модератор
2,548
2,241

hinazuki

Потрачен
346
95
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
для сампа:
ffi                 = require 'ffi'
inicfg              = require 'inicfg'
effil               = require("effil")
encoding            = require("encoding")
encoding.default    = 'CP1251'
u8 = encoding.UTF8

local Telegram = {
   Token = "", -- токен
   ChatId = "" -- твой айди в телеге
}
local updateid

function main()
    while not isSampAvailable() do wait(0) end
    getLastUpdate()
    lua_thread.create(get_telegram_updates)
    while true do
        wait(0)
    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 wait(100)
       url = 'https://api.telegram.org/bot' .. Telegram.Token .. '/getUpdates?chat_id='.. Telegram.ChatId..'&offset=-1' -- создаем ссылку
       threadHandle(runner, url, args, processing_telegram_messages, reject)
      -- wait(0)
   end
end

function processing_telegram_messages(result) -- #CMDS
   --print(tostring(result))
   if result then
       local proc_table = decodeJson(result)
       --print(tostring(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 res_table.message.chat.id == tonumber(Telegram.ChatId) then
                              if text:find("/ban") then -- #SEND
                                 if text:find("/ban (.+) (.+) (.+)") then
                                    id, arg, prichina = text:match("/ban (.+) (.+) (.+)")
                                    print(id)
                                    if #arg > 0 then
                                       otprav = "/ban " .. id .. " " .. arg .. " " .. prichina
                                       sendTelegramNotification('[Отправлено]:\n' .. otprav)
                                       sampSendChat(otprav)
                                    else
                                       sendTelegramNotification('Введите /send [id] [дней] [причина]')
                                    end
                                 else
                                    sendTelegramNotification('Введите /send [id] [дней] [причина]')
                                 end
                              end
                           end                               
                       end
                   end
               end
           end
       end
   end
end

function getLastUpdate() -- тут мы получаем последний ID сообщения, если же у вас в коде будет настройка токена и chat_id, вызовите эту функцию для того чтоб получить последнее сообщение
   async_http_request('https://api.telegram.org/bot' .. Telegram.Token .. '/getUpdates?chat_id='..Telegram.ChatId..'&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 sendTelegramNotification(msg) -- функция для отправки сообщения юзеру
   msg = msg:gsub('{......}', '') --тут типо убираем цвет
   msg = encodeUrl(msg) -- ну тут мы закодируем строку
   async_http_request('https://api.telegram.org/bot' .. Telegram.Token .. '/sendMessage?chat_id=' .. Telegram.ChatId .. '&text='..msg,'', function(result) end) -- а тут уже отправка
end

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

для ракбота:
package.path = "./scripts/libs/?.lua";
package.cpath = "./scripts/libs/?.dll";

local token = "" -- твой токен

local tgbot = require("lua-bot-api").configure(token)
local lanes = require("lanes").configure()
local linda = lanes.linda()
local from_id = ""

function updateThread(token)
    local bot, ext = require("lua-bot-api").configure(token)

    ext.onTextReceive = function(msg)
        linda:send("tg_message_recv", { from = msg.from.id, text = msg.text })
    end

    ext.run()
end

function onTelegramMessage(from, text)
    if text:find("/ban") then
      if text:find("/ban (.+) (.+) (.+)") then
        id, arg, prichina = text:match("/ban (.+) (.+) (.+)")
        if #arg > 0 then
           otprav = "/ban " .. id .. " " .. arg .. " " .. prichina
           tgbot.sendMessage(from_id, AnsiToUtf8('[Отправлено]:\n' .. otprav))
           sendInput(otprav)
        else
           tgbot.sendMessage(from_id, AnsiToUtf8('Введите /send [id] [дней] [причина]'))
        end
     else
        tgbot.sendMessage(from_id, AnsiToUtf8('Введите /send [id] [дней] [причина]'))
     end
    end
end

function onScriptUpdate()
    local eventName, eventData = linda:receive(0, "tg_message_recv")
    if eventName == "tg_message_recv" then
        onTelegramMessage(eventData.from, eventData.text)
    end
end

local ansi_decode={ -- ниже смотрите
     [128]='\208\130',[129]='\208\131',[130]='\226\128\154',[131]='\209\147',[132]='\226\128\158',[133]='\226\128\166',
     [134]='\226\128\160',[135]='\226\128\161',[136]='\226\130\172',[137]='\226\128\176',[138]='\208\137',[139]='\226\128\185',
     [140]='\208\138',[141]='\208\140',[142]='\208\139',[143]='\208\143',[144]='\209\146',[145]='\226\128\152',
     [146]='\226\128\153',[147]='\226\128\156',[148]='\226\128\157',[149]='\226\128\162',[150]='\226\128\147',[151]='\226\128\148',
     [152]='\194\152',[153]='\226\132\162',[154]='\209\153',[155]='\226\128\186',[156]='\209\154',[157]='\209\156',
     [158]='\209\155',[159]='\209\159',[160]='\194\160',[161]='\209\142',[162]='\209\158',[163]='\208\136',
     [164]='\194\164',[165]='\210\144',[166]='\194\166',[167]='\194\167',[168]='\208\129',[169]='\194\169',
     [170]='\208\132',[171]='\194\171',[172]='\194\172',[173]='\194\173',[174]='\194\174',[175]='\208\135',
     [176]='\194\176',[177]='\194\177',[178]='\208\134',[179]='\209\150',[180]='\210\145',[181]='\194\181',
     [182]='\194\182',[183]='\194\183',[184]='\209\145',[185]='\226\132\150',[186]='\209\148',[187]='\194\187',
     [188]='\209\152',[189]='\208\133',[190]='\209\149',[191]='\209\151'
}

function AnsiToUtf8(s)
     local r, b = ''
     for i = 1, s and s:len() or 0 do
       b = s:byte(i)
       if b < 128 then
         r = r..string.char(b)
       else
      if b > 239 then
           r = r..'\209'..string.char(b - 112)
         elseif b > 191 then
           r = r..'\208'..string.char(b - 48)
         elseif ansi_decode[b] then
           r = r..ansi_decode[b]
         else
           r = r..'_'
         end
       end
     end
  return r
end

function onScriptStart()
    lanes.gen("*", updateThread)(token)
end
либу прикрепил ниже
 

Вложения

  • rak tg.rar
    310 KB · Просмотры: 8
Последнее редактирование:

coldplugg.

Участник
180
22
для сампа:
ffi                 = require 'ffi'
inicfg              = require 'inicfg'
effil               = require("effil")
encoding            = require("encoding")
encoding.default    = 'CP1251'
u8 = encoding.UTF8

local Telegram = {
   Token = "", -- токен
   ChatId = "" -- твой айди в телеге
}
local updateid

function main()
    while not isSampAvailable() do wait(0) end
    getLastUpdate()
    lua_thread.create(get_telegram_updates)
    while true do
        wait(0)
    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 wait(100)
       url = 'https://api.telegram.org/bot' .. Telegram.Token .. '/getUpdates?chat_id='.. Telegram.ChatId..'&offset=-1' -- создаем ссылку
       threadHandle(runner, url, args, processing_telegram_messages, reject)
      -- wait(0)
   end
end

function processing_telegram_messages(result) -- #CMDS
   --print(tostring(result))
   if result then
       local proc_table = decodeJson(result)
       --print(tostring(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 res_table.message.chat.id == tonumber(Telegram.ChatId) then
                              if text:find("/ban") then -- #SEND
                                 if text:find("/ban (.+) (.+) (.+)") then
                                    id, arg, prichina = text:match("/ban (.+) (.+) (.+)")
                                    print(id)
                                    if #arg > 0 then
                                       otprav = "/ban " .. id .. " " .. arg .. " " .. prichina
                                       sendTelegramNotification('[Отправлено]:\n' .. otprav)
                                       sampSendChat(otprav)
                                    else
                                       sendTelegramNotification('Введите /send [id] [дней] [причина]')
                                    end
                                 else
                                    sendTelegramNotification('Введите /send [id] [дней] [причина]')
                                 end
                              end
                           end                              
                       end
                   end
               end
           end
       end
   end
end

function getLastUpdate() -- тут мы получаем последний ID сообщения, если же у вас в коде будет настройка токена и chat_id, вызовите эту функцию для того чтоб получить последнее сообщение
   async_http_request('https://api.telegram.org/bot' .. Telegram.Token .. '/getUpdates?chat_id='..Telegram.ChatId..'&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 sendTelegramNotification(msg) -- функция для отправки сообщения юзеру
   msg = msg:gsub('{......}', '') --тут типо убираем цвет
   msg = encodeUrl(msg) -- ну тут мы закодируем строку
   async_http_request('https://api.telegram.org/bot' .. Telegram.Token .. '/sendMessage?chat_id=' .. Telegram.ChatId .. '&text='..msg,'', function(result) end) -- а тут уже отправка
end

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

для ракбота:
package.path = "./scripts/libs/?.lua";
package.cpath = "./scripts/libs/?.dll";

local token = "" -- твой токен

local tgbot = require("lua-bot-api").configure(token)
local lanes = require("lanes").configure()
local linda = lanes.linda()
local from_id = ""

function updateThread(token)
    local bot, ext = require("lua-bot-api").configure(token)

    ext.onTextReceive = function(msg)
        linda:send("tg_message_recv", { from = msg.from.id, text = msg.text })
    end

    ext.run()
end

function onTelegramMessage(from, text)
    if text:find("/ban") then
      if text:find("/ban (.+) (.+) (.+)") then
        id, arg, prichina = text:match("/ban (.+) (.+) (.+)")
        if #arg > 0 then
           otprav = "/ban " .. id .. " " .. arg .. " " .. prichina
           tgbot.sendMessage(from_id, AnsiToUtf8('[Отправлено]:\n' .. otprav))
           sendInput(otprav)
        else
           tgbot.sendMessage(from_id, AnsiToUtf8('Введите /send [id] [дней] [причина]'))
        end
     else
        tgbot.sendMessage(from_id, AnsiToUtf8('Введите /send [id] [дней] [причина]'))
     end
    end
end

function onScriptUpdate()
    local eventName, eventData = linda:receive(0, "tg_message_recv")
    if eventName == "tg_message_recv" then
        onTelegramMessage(eventData.from, eventData.text)
    end
end

local ansi_decode={ -- ниже смотрите
     [128]='\208\130',[129]='\208\131',[130]='\226\128\154',[131]='\209\147',[132]='\226\128\158',[133]='\226\128\166',
     [134]='\226\128\160',[135]='\226\128\161',[136]='\226\130\172',[137]='\226\128\176',[138]='\208\137',[139]='\226\128\185',
     [140]='\208\138',[141]='\208\140',[142]='\208\139',[143]='\208\143',[144]='\209\146',[145]='\226\128\152',
     [146]='\226\128\153',[147]='\226\128\156',[148]='\226\128\157',[149]='\226\128\162',[150]='\226\128\147',[151]='\226\128\148',
     [152]='\194\152',[153]='\226\132\162',[154]='\209\153',[155]='\226\128\186',[156]='\209\154',[157]='\209\156',
     [158]='\209\155',[159]='\209\159',[160]='\194\160',[161]='\209\142',[162]='\209\158',[163]='\208\136',
     [164]='\194\164',[165]='\210\144',[166]='\194\166',[167]='\194\167',[168]='\208\129',[169]='\194\169',
     [170]='\208\132',[171]='\194\171',[172]='\194\172',[173]='\194\173',[174]='\194\174',[175]='\208\135',
     [176]='\194\176',[177]='\194\177',[178]='\208\134',[179]='\209\150',[180]='\210\145',[181]='\194\181',
     [182]='\194\182',[183]='\194\183',[184]='\209\145',[185]='\226\132\150',[186]='\209\148',[187]='\194\187',
     [188]='\209\152',[189]='\208\133',[190]='\209\149',[191]='\209\151'
}

function AnsiToUtf8(s)
     local r, b = ''
     for i = 1, s and s:len() or 0 do
       b = s:byte(i)
       if b < 128 then
         r = r..string.char(b)
       else
      if b > 239 then
           r = r..'\209'..string.char(b - 112)
         elseif b > 191 then
           r = r..'\208'..string.char(b - 48)
         elseif ansi_decode[b] then
           r = r..ansi_decode[b]
         else
           r = r..'_'
         end
       end
     end
  return r
end

function onScriptStart()
    lanes.gen("*", updateThread)(token)
end
либу прикрепил ниже
как понять для сампа, а так спасибо мужик)

как понять для сампа, а так спасибо мужик)
получается для сампа в тг, а для ракбота в ракбота, или как

щас с того акка залечу дам галочку

а все дошло, для ракбота в тг, а для сампа в скрипт ракбота, от души

а зачем мне для сампа
 
Последнее редактирование: