Вопросы по Lua скриптингу

Общая тема для вопросов по разработке скриптов на языке программирования Lua, в частности под MoonLoader.
  • Задавая вопрос, убедитесь, что его нет в списке частых вопросов и что на него ещё не отвечали (воспользуйтесь поиском).
  • Поищите ответ в теме посвященной разработке Lua скриптов в MoonLoader
  • Отвечая, убедитесь, что ваш ответ корректен.
  • Старайтесь как можно точнее выразить мысль, а если проблема связана с кодом, то обязательно прикрепите его к сообщению, используя блок [code=lua]здесь мог бы быть ваш код[/code].
  • Если вопрос связан с MoonLoader-ом первым делом желательно поискать решение на wiki.

Частые вопросы

Как научиться писать скрипты? С чего начать?
Информация - Гайд - Всё о Lua скриптинге для MoonLoader(https://blast.hk/threads/22707/)
Как вывести текст на русском? Вместо русского текста у меня какие-то каракули.
Изменить кодировку файла скрипта на Windows-1251. В Atom: комбинация клавиш Ctrl+Shift+U, в Notepad++: меню Кодировки -> Кодировки -> Кириллица -> Windows-1251.
Как получить транспорт, в котором сидит игрок?
Lua:
local veh = storeCarCharIsInNoSave(PLAYER_PED)
Как получить свой id или id другого игрока?
Lua:
local _, id = sampGetPlayerIdByCharHandle(PLAYER_PED) -- получить свой ид
local _, id = sampGetPlayerIdByCharHandle(ped) -- получить ид другого игрока. ped - это хендл персонажа
Как проверить, что строка содержит какой-то текст?
Lua:
if string.find(str, 'текст', 1, true) then
-- строка str содержит "текст"
end
Как эмулировать нажатие игровой клавиши?
Lua:
local game_keys = require 'game.keys' -- где-нибудь в начале скрипта вне функции main

setGameKeyState(game_keys.player.FIREWEAPON, -1) -- будет сэмулировано нажатие клавиши атаки
Все иды клавиш находятся в файле moonloader/lib/game/keys.lua.
Подробнее о функции setGameKeyState здесь: lua - setgamekeystate | BlastHack — DEV_WIKI(https://www.blast.hk/wiki/lua:setgamekeystate)
Как получить id другого игрока, в которого целюсь я?
Lua:
local valid, ped = getCharPlayerIsTargeting(PLAYER_HANDLE) -- получить хендл персонажа, в которого целится игрок
if valid and doesCharExist(ped) then -- если цель есть и персонаж существует
  local result, id = sampGetPlayerIdByCharHandle(ped) -- получить samp-ид игрока по хендлу персонажа
  if result then -- проверить, прошло ли получение ида успешно
    -- здесь любые действия с полученным идом игрока
  end
end
Как зарегистрировать команду чата SAMP?
Lua:
-- До бесконечного цикла/задержки
sampRegisterChatCommand("mycommand", function (param)
     -- param будет содержать весь текст введенный после команды, чтобы разделить его на аргументы используйте string.match()
    sampAddChatMessage("MyCMD", -1)
end)
Крашит игру при вызове sampSendChat. Как это исправить?
Это происходит из-за бага в SAMPFUNCS, когда производится попытка отправки пакета определенными функциями изнутри события исходящих RPC и пакетов. Исправления для этого бага нет, но есть способ не провоцировать его. Вызов sampSendChat изнутри обработчика исходящих RPC/пакетов нужно обернуть в скриптовый поток с нулевой задержкой:
Lua:
function onSendRpc(id)
  -- крашит:
  -- sampSendChat('Send RPC: ' .. id)

  -- норм:
  lua_thread.create(function()
    wait(0)
    sampSendChat('Send RPC: ' .. id)
  end)
end
 
Последнее редактирование:

KOLBASKA@

Участник
35
0
Lua:
local inicfg = require 'inicfg'
local directIni = 'filename.ini'
local ini = inicfg.load(inicfg.load({
    cfg = {
        selected_item = 0
    },
}, directIni))
inicfg.save(ini, directIni)

selected_item = imgui.ImInt(0)
local itemlist = {u8'Первая', u8'Вторая', u8'Третья'}
selected_item.v = ini.cfg.selected_item

--OnDrawFrame
if imgui.Combo(u8'', selected_item, itemlist, #itemlist) then style() ini.cfg.selected_item = selected_item.v inicfg.save(ini, directIni) end

function style()
    if selected_item.v == 0 then

    end
    if selected_item.v == 1 then
      
    end

    if selected_item.v == 2 then

    end
end
style()
как мне это сшить с этим? я просто вообще хз
Lua:
require'lib.moonloader'
local colr = 0xfc05cf
local tag = "{34deeb}[Your Stats]: "
local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.dafault = 'CP1251'
u8 = encoding.UTF8
local themes = import "resource/imgui_themes.lua"
local fa = require 'faIcons'
local fa_glyph_ranges = imgui.ImGlyphRanges({ fa.min_range, fa.max_range })
local main_window_state = imgui.ImBool(false)
local text_buffer = imgui.ImBuffer(256)
function imgui.BeforeDrawFrame()
  if fa_font == nil then
      local font_config = imgui.ImFontConfig()
      font_config.MergeMode = true
      fa_font = imgui.GetIO().Fonts:AddFontFromFileTTF('moonloader/resource/fonts/fontawesome-webfont.ttf', 14.0, font_config, fa_glyph_ranges)
  end
end
function imgui.TextColoredRGB(text, render_text)
  local max_float = imgui.GetWindowWidth()
  local style = imgui.GetStyle()
  local colors = style.Colors
  local ImVec4 = imgui.ImVec4
  local explode_argb = function(argb)
      local a = bit.band(bit.rshift(argb, 24), 0xFF)
      local r = bit.band(bit.rshift(argb, 16), 0xFF)
      local g = bit.band(bit.rshift(argb, 8), 0xFF)
      local b = bit.band(argb, 0xFF)
      return a, r, g, b
  end
  local getcolor = function(color)
      if color:sub(1, 6):upper() == 'SSSSSS' then
          local r, g, b = colors[1].x, colors[1].y, colors[1].z
          local a = tonumber(color:sub(7, 8), 16) or colors[1].w * 255
          return ImVec4(r, g, b, a / 255)
      end
      local color = type(color) == 'string' and tonumber(color, 16) or color
      if type(color) ~= 'number' then return end
      local r, g, b, a = explode_argb(color)
      return imgui.ImColor(r, g, b, a):GetVec4()
  end
  local render_text = function(text_)
      for w in text_:gmatch('[^\r\n]+') do
          local text, colors_, m = {}, {}, 1
          w = w:gsub('{(......)}', '{%1FF}')
          while w:find('{........}') do
              local n, k = w:find('{........}')
              local color = getcolor(w:sub(n + 1, k - 1))
              if color then
                  text[#text], text[#text + 1] = w:sub(m, n - 1), w:sub(k + 1, #w)
                  colors_[#colors_ + 1] = color
                  m = n
              end
              w = w:sub(1, n - 1) .. w:sub(k + 1, #w)
          end
          local length = imgui.CalcTextSize(w)
          if render_text == 2 then
              imgui.NewLine()
              imgui.SameLine(max_float / 2 - ( length.x / 2 ))
          elseif render_text == 3 then
              imgui.NewLine()
              imgui.SameLine(max_float - length.x - 5 )
          end
          if text[0] then
              for i = 0, #text do
                  imgui.TextColored(colors_[i] or colors[1], text[i])
                  imgui.SameLine(nil, 0)
              end
              imgui.NewLine()
          else imgui.Text(w) end

      end
  end
  render_text(text)
end
imgui.SwitchContext()
local style = imgui.GetStyle()
local colors = style.Colors
local clr = imgui.Col
local ImVec4 = imgui.ImVec4
style.Alpha = 1.0
style.ChildWindowRounding = 3
style.WindowRounding = 3
style.GrabRounding = 1
style.GrabMinSize = 20
style.FrameRounding = 3
colors[clr.Text] = ImVec4(0.00, 1.00, 1.00, 1.00)
colors[clr.TextDisabled] = ImVec4(0.00, 0.40, 0.41, 1.00)
colors[clr.WindowBg] = ImVec4(0.00, 0.00, 0.00, 1.00)
colors[clr.ChildWindowBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.Border] = ImVec4(0.00, 1.00, 1.00, 0.65)
colors[clr.BorderShadow] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.FrameBg] = ImVec4(0.44, 0.80, 0.80, 0.18)
colors[clr.FrameBgHovered] = ImVec4(0.44, 0.80, 0.80, 0.27)
colors[clr.FrameBgActive] = ImVec4(0.44, 0.81, 0.86, 0.66)
colors[clr.TitleBg] = ImVec4(0.14, 0.18, 0.21, 0.73)
colors[clr.TitleBgCollapsed] = ImVec4(0.00, 0.00, 0.00, 0.54)
colors[clr.TitleBgActive] = ImVec4(0.00, 1.00, 1.00, 0.27)
colors[clr.MenuBarBg] = ImVec4(0.00, 0.00, 0.00, 0.20)
colors[clr.ScrollbarBg] = ImVec4(0.22, 0.29, 0.30, 0.71)
colors[clr.ScrollbarGrab] = ImVec4(0.00, 1.00, 1.00, 0.44)
colors[clr.ScrollbarGrabHovered] = ImVec4(0.00, 1.00, 1.00, 0.74)
colors[clr.ScrollbarGrabActive] = ImVec4(0.00, 1.00, 1.00, 1.00)
colors[clr.ComboBg] = ImVec4(0.16, 0.24, 0.22, 0.60)
colors[clr.CheckMark] = ImVec4(0.00, 1.00, 1.00, 0.68)
colors[clr.SliderGrab] = ImVec4(0.00, 1.00, 1.00, 0.36)
colors[clr.SliderGrabActive] = ImVec4(0.00, 1.00, 1.00, 0.76)
colors[clr.Button] = ImVec4(0.00, 0.65, 0.65, 0.46)
colors[clr.ButtonHovered] = ImVec4(0.01, 1.00, 1.00, 0.43)
colors[clr.ButtonActive] = ImVec4(0.00, 1.00, 1.00, 0.62)
colors[clr.Header] = ImVec4(0.00, 1.00, 1.00, 0.33)
colors[clr.HeaderHovered] = ImVec4(0.00, 1.00, 1.00, 0.42)
colors[clr.HeaderActive] = ImVec4(0.00, 1.00, 1.00, 0.54)
colors[clr.ResizeGrip] = ImVec4(0.00, 1.00, 1.00, 0.54)
colors[clr.ResizeGripHovered] = ImVec4(0.00, 1.00, 1.00, 0.74)
colors[clr.ResizeGripActive] = ImVec4(0.00, 1.00, 1.00, 1.00)
colors[clr.CloseButton] = ImVec4(0.00, 0.78, 0.78, 0.35)
colors[clr.CloseButtonHovered] = ImVec4(0.00, 0.78, 0.78, 0.47)
colors[clr.CloseButtonActive] = ImVec4(0.00, 0.78, 0.78, 1.00)
colors[clr.PlotLines] = ImVec4(0.00, 1.00, 1.00, 1.00)
colors[clr.PlotLinesHovered] = ImVec4(0.00, 1.00, 1.00, 1.00)
colors[clr.PlotHistogram] = ImVec4(0.00, 1.00, 1.00, 1.00)
colors[clr.PlotHistogramHovered] = ImVec4(0.00, 1.00, 1.00, 1.00)
colors[clr.TextSelectedBg] = ImVec4(0.00, 1.00, 1.00, 0.22)
colors[clr.ModalWindowDarkening] = ImVec4(0.04, 0.10, 0.09, 0.51)

local checked1 = imgui.ImBool(false)
local checked2 = imgui.ImBool(false)
local checked3 = imgui.ImBool(false)
local checked4 = imgui.ImBool(false)
local checked5 = imgui.ImBool(false)
local checked6 = imgui.ImBool(false)
local checked7 = imgui.ImBool(false)
local checked8 = imgui.ImBool(false)
local checked9 = imgui.ImBool(false)
local checked10 = imgui.ImBool(false)
local checked11 = imgui.ImBool(false)
local checked_radio = imgui.ImInt(1)
function main()
    if not isSampLoaded() or not  isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampAddChatMessage("{FFFD00}SCRIPT AVAIBLE", -1)
    sampRegisterChatCommand("stat", cmd_imgui)
    sampRegisterChatCommand("/stat", cmd_ch)
   
    imgui.Process = false
    while true do
        wait(0)
      
      _, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
      nick = sampGetPlayerNickname(id)
      money = getPlayerMoney(int, id)
      ping = sampGetPlayerPing(id)
      score = sampGetPlayerScore(id)
      armor = sampGetPlayerArmor(id)
      health = sampGetPlayerHealth(id)
      animid = sampGetPlayerAnimationId(int, id)
      count = sampGetPlayerCount(bool, false)
      interior = getActiveInterior()
      counts = sampGetPlayerCount(true)
      if main_window_state.v == false then
        imgui.Process = false
      end
    end
end
function cmd_imgui(arg)
  main_window_state.v = not main_window_state.v 
  imgui.Process = main_window_state.v
end
function cmd_ch(arg)
  x, y, z = getCharCoordinates(PLAYER_PED)
  if checked1.v then
    sampAddChatMessage(tag .. "{2ed947}ID: {FFFFFF}" .. id, -1)
  end
  if checked2.v then
    sampAddChatMessage(tag .. "{2ed947}Nick: {FFFFFF}" .. nick, -1)
  end
  if checked3.v then
    sampAddChatMessage(tag .. "{2ed947}Ping: {FFFFFF}" .. ping, -1)
  end
  if checked4.v then
    sampAddChatMessage(tag .. "{2ed947}Money: {FFFFFF}" .. money, -1)
  end
  if checked5.v then
    sampAddChatMessage(tag .. "{2ed947}LVL: {FFFFFF}" .. score, -1)
  end
  if checked6.v then
    sampAddChatMessage(tag .. "{2ed947}Health: {FFFFFF}" .. health, -1)
  end
  if checked7.v then
    sampAddChatMessage(tag .. "{2ed947}Armour: {FFFFFF}" .. armor, -1)
  end
  if checked8.v then
    sampAddChatMessage(tag .. "{2ed947}Players: {FFFFFF}" .. count, -1)
  end
  if checked9.v then
    sampAddChatMessage(tag .. "{2ed947}Streaming: {FFFFFF}" .. counts, -1)
  end
  if checked10.v then
    sampAddChatMessage(tag .. "{2ed947}Interior: {FFFFFF}" .. interior, -1)
  end
  if checked11.v then
    sampAddChatMessage(tag .. "{2ed947}Coordinates {FFFFFF}X: ".. math.floor(x) .. " | Y: {FFFFFF}" .. math.floor(y) .. " | Z: {FFFFFF}" .. math.floor(z), -1)
  end
end
function imgui.OnDrawFrame()
  local sw, sh = getScreenResolution()
    imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.SetNextWindowSize(imgui.ImVec2(650, 470), imgui.Cond.FirstUseEver)
    imgui.Begin(fa.ICON_TOGGLE_ON .. " Script Avaible - By Pablo", main_window_state)
    imgui.BeginChild("WINDOW_1", imgui.ImVec2(300, 200), true)
      imgui.TextColoredRGB(fa.ICON_INFO_CIRCLE .. " You ID: {FFFFFF}" .. id)
      imgui.TextColoredRGB(fa.ICON_ADDRESS_BOOK .. " You nick {FFFFFF}" .. nick)
      imgui.TextColoredRGB(fa.ICON_MONEY .. " You money: {FFFFFF}$" .. money)
      imgui.TextColoredRGB(fa.ICON_WIFI .. " You ping: {FFFFFF}" .. ping .. " ms")
      imgui.TextColoredRGB(fa.ICON_LEVEL_UP .. " You lvl: {FFFFFF}" .. score)
      imgui.TextColoredRGB(fa.ICON_SHIELD .. " You armour: {FFFFFF}" .. armor)
      imgui.TextColoredRGB(fa.ICON_HEARTBEAT ..  " You health: {FFFFFF}" .. health)
      imgui.TextColoredRGB(fa.ICON_USERS .. " Server Players: {FFFFFF}" .. count)
      imgui.TextColoredRGB(fa.ICON_USER_PLUS .. " Players in zone streaming: {FFFFFF}" .. counts)
      x, y, z = getCharCoordinates(PLAYER_PED)
      imgui.TextColoredRGB(fa.ICON_MAP_MARKER .. " Coordinates {FFFFFF}X: " .. math.floor(x) .. " | Y: {FFFFFF}" .. math.floor(y) .. " | Z: {FFFFFF}" .. math.floor(z))
    imgui.EndChild()
    imgui.SetCursorPos(imgui.ImVec2(320, 29.5))
    imgui.BeginChild("Window_2", imgui.ImVec2(300, 200), true)
      if imgui.Button(fa.ICON_ADDRESS_BOOK_O .. " CHECK STATS IN GLOBAL CHAT ;)") then
        sampAddChatMessage(tag .."{2ed947}You id: {FFFFFF}" .. id, -1)  
        sampAddChatMessage(tag .."{2ed947}You nick: {FFFFFF}" .. nick, -1)
        sampAddChatMessage(tag .. "{2ed947}You money:  {FFFFFF}$" .. money, -1)
        sampAddChatMessage(tag .. "{2ed947}You ping: {FFFFFF}" .. ping .. " {FFFFFF}ms", -1)
        sampAddChatMessage(tag .. "{2ed947}You LVL: {FFFFFF}" .. score, -1)
        sampAddChatMessage(tag .. "{2ed947}You armour: {FFFFFF}" .. armor, -1)
        sampAddChatMessage(tag .. "{2ed947}You health: {FFFFFF}" .. health, -1)
        sampAddChatMessage(tag .. "{2ed947}Server Players: {FFFFFF}" .. count, -1)
        sampAddChatMessage(tag .. "{2ed947}Player in zone streaming {FFFFFF}" .. counts, -1)
        sampAddChatMessage(tag .. "{2ed947}Interior: {FFFFFF} пїЅ " .. interior, -1)
        sampAddChatMessage(tag .. "{2ed947}Coordinates {FFFFFF}X: ".. math.floor(x) .. " | Y: {FFFFFF}" .. math.floor(y) .. " | Z: {FFFFFF}" .. math.floor(z), -1)
      end
    imgui.Columns(2, "TABLE_1", true)
    imgui.Separator()
      if imgui.Button(fa.ICON_INFO_CIRCLE .. " ID") then 
        sampAddChatMessage(tag .. "{2ed947}You ID: {FFFFFF}" .. id, -1)
      end
      imgui.NextColumn()
      if imgui.Button(fa.ICON_ADDRESS_BOOK .. " NICK") then
        sampAddChatMessage(tag .. "{2ed947}You Nick: {FFFFFF}" .. nick, -1)
      end
      imgui.Separator()
      imgui.NextColumn()
      if imgui.Button(fa.ICON_WIFI .. " PING") then
        sampAddChatMessage(tag .. "{2ed947}You Ping: {FFFFFF}" .. ping .. " ms", -1)
      end
      imgui.NextColumn()
      if imgui.Button(fa.ICON_MONEY .. "  MONEY") then
        sampAddChatMessage(tag .. "{2ed947}You money: {FFFFFF} $" .. money, -1)
      end
      imgui.Separator()
      imgui.NextColumn()
      if imgui.Button(fa.ICON_LEVEL_UP .. " LVL") then
        sampAddChatMessage(tag .. "{2ed947}You LVL: {FFFFFF}" .. score, -1)
      end
      imgui.NextColumn()
      if imgui.Button(fa.ICON_HEARTBEAT ..  " HEALTH") then
        sampAddChatMessage(tag .. "{2ed947}You Health: {FFFFFF}" .. health, -1)
      end
      imgui.Separator()
      imgui.NextColumn()
      if imgui.Button(fa.ICON_SHIELD .. " ARMOUR") then
        sampAddChatMessage(tag .. "{2ed947}You Armour: {FFFFFF}" .. armor, -1)
      end
      imgui.NextColumn()
      if imgui.Button(fa.ICON_USERS .. " PLAYERS") then
        sampAddChatMessage(tag .. "{2ed947}Server Players: {FFFFFF}" .. count, -1)
      end
      imgui.Separator()
      imgui.NextColumn()
      if imgui.Button(fa.ICON_USER_PLUS .. " STREAMING") then
        sampAddChatMessage(tag .. "{2ed947}Player in zone streaming: {FFFFFF}" .. counts, -1)
      end
      imgui.SetCursorPos(imgui.ImVec2(6.5, 176))
      if imgui.Button(fa.ICON_PLUS_SQUARE .. " INTERIOR") then
        sampAddChatMessage(tag .. "{2ed947}Interior: {FFFFFF} пїЅ " .. interior, -1)
      end
      imgui.NextColumn()
      if imgui.Button(fa.ICON_MAP_MARKER ..  " Coordinates") then
        sampAddChatMessage(tag .. "{2ed947}Coordinates X: {FFFFFF}".. math.floor(x) .. " | Y: {FFFFFF}" .. math.floor(y) .. " | Z: {FFFFFF}" .. math.floor(z), -1)
      end
    imgui.Separator()
    imgui.Columns(1)
    imgui.EndChild()
    imgui.Text("")
    imgui.SetCursorPos(imgui.ImVec2(110, 235))
    imgui.BeginChild("Window_3", imgui.ImVec2(430, 135), true)
      imgui.SetCursorPos(imgui.ImVec2(10, 10))
      imgui.Checkbox("Show ID         ", checked1)
      imgui.SetCursorPos(imgui.ImVec2(120, 10))
      imgui.Checkbox("Show_Nick       ", checked2)
      imgui.SetCursorPos(imgui.ImVec2(230, 10))
      imgui.Checkbox("Show_Ping       ", checked3)
      imgui.SetCursorPos(imgui.ImVec2(10, 35))
      imgui.Checkbox("Show_Money      ", checked4)
      imgui.SetCursorPos(imgui.ImVec2(120, 35))
      imgui.Checkbox("Show_LVL        ", checked5)
      imgui.SetCursorPos(imgui.ImVec2(230, 35))
      imgui.Checkbox("Show Health     ", checked6)
      imgui.SetCursorPos(imgui.ImVec2(10, 60))
      imgui.Checkbox("Show Armour     ", checked7)
      imgui.SetCursorPos(imgui.ImVec2(120, 60))
      imgui.Checkbox("Show Players    ", checked8)
      imgui.SetCursorPos(imgui.ImVec2(230, 60))
      imgui.Checkbox("Show Streaming  ", checked9)
      imgui.SetCursorPos(imgui.ImVec2(10, 85))
      imgui.Checkbox("Show_Interior   ", checked10)
      imgui.SetCursorPos(imgui.ImVec2(120, 85))
      imgui.Checkbox("Show_Coordinates", checked11)

    imgui.EndChild()
    if imgui.Button("1") then
      themes.SwitchColorTheme(1)
    end
    imgui.SameLine()
    if imgui.Button("2") then
      themes.SwitchColorTheme(2)
    end
    if imgui.Button("3") then
      themes.SwitchColorTheme(3)
    end
    imgui.SameLine()
    if imgui.Button("4") then
      themes.SwitchColorTheme(4)
    end
    if imgui.Button("5") then
      themes.SwitchColorTheme(5)
    end
    imgui.SameLine()
    if imgui.Button("6") then
      themes.SwitchColorTheme(6)
    end
    if imgui.Button("7") then
      themes.SwitchColorTheme(7)
    end
    imgui.SameLine()
    if imgui.Button("8") then
      themes.SwitchColorTheme(8)
    end
    
    imgui.End()
end
 
  • Эм
Реакции: qdIbp

Sherlok Kholmes

Участник
32
9
Поч не работает?(
Lua:
function ilovegays()
    if sampGetCurrentDialogId() == 10411 and sampIsDialogActive() then
        sampAddChatMessage("sdasa")
    else
        wait(-1)
    end
end
 

RoAB

Потрачен
102
36
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Помогите со скриптом луа(РАКБОТ!!!), когда переодевается, как я понял даже не отвечает на диалог и потом при произведении следующего маршрута
!play pereod-reyss, перезаписывал даже маршрут, ничего не помогает, все просто намертво зависает(ракбот)
 

Вложения

  • !autorun.lua
    2.5 KB · Просмотры: 2

Sadow

Известный
1,438
589
Как можно ловить все сообщения с чата (Серверные, клиента) и отправлять в телеграмм?
 

qdIbp

Автор темы
Проверенный
1,387
1,143
Как можно ловить все сообщения с чата (Серверные, клиента) и отправлять в телеграмм?
а так на
Lua:
script_name('Telegram Notifications Source')
script_authors('ronnyscripts, ronny_evans')

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

chat_id = '' -- чат ID юзера
token = '' -- токен бота

local updateid -- ID последнего сообщения для того чтобы не было флуда

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 calc(str) --это тестовая функция, её не требуется переносить в ваш код
    return assert(load("return "..str))()
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) .. ' ' --добавляем в конец пробел дабы не произошли тех. шоколадки с командами(типо чтоб !q не считалось как !qq)
                            if text:match('^!qq') then
                                sendTelegramNotification('Ку')
                            elseif text:match('^!q') then
                                sendTelegramNotification('Привет!')
                            elseif text:match('^!stats') then
                                sendTelegramNotification('Это тестовая версия блин')
                            elseif text:match('^!calc') then
                                local arg = text:gsub('!calc ','',1) -- вот так мы получаем аргумент команды
                                if #arg > 0 then
                                    local result_calc = calc(arg)
                                    if result_calc then
                                        sendTelegramNotification('Вы ввели пример: '..arg..'\nОтвет: '..result_calc)
                                    else
                                        sendTelegramNotification('Неверный пример!')
                                    end
                                      
                                else
                                    sendTelegramNotification('Эм, ты не ввел аргумент')
                                end
                            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
    sampChatHook = hook.new('void(__thiscall *)(void *this, uint32_t type, const char* text, const char* prefix, uint32_t color, uint32_t pcolor)', ChatHook, getModuleHandle('samp.dll') + 0x64010)
    getLastUpdate() -- вызываем функцию получения последнего ID сообщения
    lua_thread.create(get_telegram_updates) -- создаем нашу функцию получения сообщений от юзера
    while true do
        wait(0)
    end
end

local ffi = require 'ffi'
local hook = {hooks = {}}
addEventHandler('onScriptTerminate', function(scr)
    if scr == script.this then
        for i, hook in ipairs(hook.hooks) do
            if hook.status then
                hook.stop()
            end
        end
    end
end)

ffi.cdef [[
    int VirtualProtect(void* lpAddress, unsigned long dwSize, unsigned long flNewProtect, unsigned long* lpflOldProtect);
]]

function hook.new(cast, callback, hook_addr, size)
    local size = size or 5
    local new_hook = {}
    local detour_addr = tonumber(ffi.cast('intptr_t', ffi.cast('void*', ffi.cast(cast, callback))))
    local void_addr = ffi.cast('void*', hook_addr)
    local old_prot = ffi.new('unsigned long[1]')
    local org_bytes = ffi.new('uint8_t[?]', size)
    ffi.copy(org_bytes, void_addr, size)
    local hook_bytes = ffi.new('uint8_t[?]', size, 0x90)
    hook_bytes[0] = 0xE9
    ffi.cast('uint32_t*', hook_bytes + 1)[0] = detour_addr - hook_addr - 5
    new_hook.call = ffi.cast(cast, hook_addr)
    new_hook.status = false
    local function set_status(bool)
        new_hook.status = bool
        ffi.C.VirtualProtect(void_addr, size, 0x40, old_prot)
        ffi.copy(void_addr, bool and hook_bytes or org_bytes, size)
        ffi.C.VirtualProtect(void_addr, size, old_prot[0], old_prot)
    end
    new_hook.stop = function() set_status(false) end
    new_hook.start = function() set_status(true) end
    new_hook.start()
    table.insert(hook.hooks, new_hook)
    return setmetatable(new_hook, {
        __call = function(self, ...)
            self.stop()
            local res = self.call(...)
            self.start()
            return res
        end
    })
end


function ChatHook(HOOKED_CHAT_THIS, HOOKED_CHAT_TYPE, HOOKED_CHAT_TEXT, HOOKED_CHAT_PREFIX, HOOKED_CHAT_COLOR, HOOKED_CHAT_PCOLOR)
    local text = ffi.string(HOOKED_CHAT_TEXT)
        sendTelegramNotification(text)--тут крч работай
    sampChatHook(HOOKED_CHAT_THIS, HOOKED_CHAT_TYPE, HOOKED_CHAT_TEXT, HOOKED_CHAT_PREFIX, HOOKED_CHAT_COLOR, HOOKED_CHAT_PCOLOR)
end
 

RoAB

Потрачен
102
36
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Делаю скрипт на ракбот, бота трамвайщика, в общем он тепается к депо, заходит, переодевается, берет рейс, и в начале рейса когда его сажает в трамвай его просто кикает за игнорирование функций(дальше кода нет, просто принятие рейса и все)

UPD: Чел подсказал вроде как нужно добавить InCar sync, только вопрос, как это сделать(на ракботе)
 
Последнее редактирование:

artie

Участник
70
20
помогите пожалуйста с регулярками, чтобы потом можно было получить название города, который в ' '
Код:
Johny_Power[216]{FFFFFF} с города 'San Fierro', вызывает полицию, местоположение: {B03131}армия сф{FFFFFF}.
получилось так, но не работает
Lua:
if text:find('^%S+%[%d+%]{FFFFFF}%sс%sгорода%s(.+)%p%sвызывает%sполицию%p%sместоположение%p%s.+') then
   local city = text:match('города%s(.+)%p%s')
   sampAddChatMessage(city,-1)
end
 

accord-

Потрачен
437
79
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
помогите пожалуйста с регулярками, чтобы потом можно было получить название города, который в ' '
Код:
Johny_Power[216]{FFFFFF} с города 'San Fierro', вызывает полицию, местоположение: {B03131}армия сф{FFFFFF}.
получилось так, но не работает
Lua:
if text:find('^%S+%[%d+%]{FFFFFF}%sс%sгорода%s(.+)%p%sвызывает%sполицию%p%sместоположение%p%s.+') then
   local city = text:match('города%s(.+)%p%s')
   sampAddChatMessage(city,-1)
end
Lua:
    if text:find(".+ с города '.+', вызывает полицию, местоположение%: .+") then
        local gorod = text:match(".+ с города '(.+)', вызывает полицию, местоположение%: .+")
        sampAddChatMessage(gorod,-1) 
    end
 
  • Влюблен
Реакции: artie

Anti...

Активный
262
26
Возможно сделать такую imgui.Button? или только с imgui.ImageButton

спаро.png
 

xanndiane

Известный
521
148
Как тут сделать чтобы выходило из игры когда почти взорвался? Пол часа дрочусь уже не понимаю что не так сделал (автор скрипта chapo)
 

Вложения

  • antiexp.lua
    1.9 KB · Просмотры: 4

YarikVL

Известный
Проверенный
4,796
1,813
Как тут сделать чтобы выходило из игры когда почти взорвался? Пол часа дрочусь уже не понимаю что не так сделал (автор скрипта chapo)
28 строку замени на sampProcessChatInput("/q")
Ещё можешь после 28 строки дописать перезагрузку скрипта, что-то похожее на это: thisScript():unload()
Чтобы не багался скрипт ( вдруг будет такое )
 

Anti...

Активный
262
26
Как style.WindowRounding засунть в imgui.PushStyleColor()? Мне нужно что бы закругление было только на 1 имгуи окне