Извлечь информацию с сайта в чат SAMP

SyLvy

Активный
Автор темы
231
25
Версия MoonLoader
.026-beta
Мне нужна помощь, я думаю, это сложно, но я не могу найти другого примера сценария, из которого я мог бы черпать вдохновение. Я объясню вам, что я хочу сделать: сценарий, в котором есть команда (/checklic <name>) который собирает некоторую информацию из https://www.rpg.b-zone.ro/players/general/<name>, а точнее лицензионные часы (эти):
Screenshot_2024-02-12-11-08-27-878.jpg

После сбора количества лицензионных часов скрипт вернет следующую строку:
через sampAddChatMessage:
Flying: X, Sailing: X, Fishing: X, Weapon: X, Materials: X.
Как я уже сказал, я искал множество lua-скриптов, использующих асинхронные HTTP-запросы, но они не соответствуют тому, что я ищу.
 
Решение
lib: https://github.com/TRIGONIM/lua-requests-async/

Lua:
local http = require("http_async")

function main()
    sampRegisterChatCommand("checklic", checklic)
    while true do
        wait(100)
        require("copas").step()
    end
end

function checklic(nickName)
    local url = "https://www.rpg.b-zone.ro/players/general/" .. nickName
    http.get(url, function(body, len, headers, code)
        local playerNotFound = body:find("Player not found")
        if code == 200 and not playerNotFound then
            local text = body:gsub("<.->", ""):gsub("\n",""):gsub("\t", ""):gsub("%s+", " ")
            local drivingLicense = text:match("Driving License (%d+) Hours")
            local flyingLicense = text:match("Flying License...

Rezbirp

Известный
72
69
lib: https://github.com/TRIGONIM/lua-requests-async/

Lua:
local http = require("http_async")

function main()
    sampRegisterChatCommand("checklic", checklic)
    while true do
        wait(100)
        require("copas").step()
    end
end

function checklic(nickName)
    local url = "https://www.rpg.b-zone.ro/players/general/" .. nickName
    http.get(url, function(body, len, headers, code)
        local playerNotFound = body:find("Player not found")
        if code == 200 and not playerNotFound then
            local text = body:gsub("<.->", ""):gsub("\n",""):gsub("\t", ""):gsub("%s+", " ")
            local drivingLicense = text:match("Driving License (%d+) Hours")
            local flyingLicense = text:match("Flying License (%d+) Hours")
            sampAddChatMessage(nickName .. " | Driving: " .. drivingLicense .. " Flying " .. flyingLicense, -1)
        elseif playerNotFound then
            sampAddChatMessage("Player ".. nickName .." not found", -1)
        else
            sampAddChatMessage("Error: " .. code, -1)
        end
    end)
end
 

SyLvy

Активный
Автор темы
231
25
lib: https://github.com/TRIGONIM/lua-requests-async/

Lua:
local http = require("http_async")

function main()
    sampRegisterChatCommand("checklic", checklic)
    while true do
        wait(100)
        require("copas").step()
    end
end

function checklic(nickName)
    local url = "https://www.rpg.b-zone.ro/players/general/" .. nickName
    http.get(url, function(body, len, headers, code)
        local playerNotFound = body:find("Player not found")
        if code == 200 and not playerNotFound then
            local text = body:gsub("<.->", ""):gsub("\n",""):gsub("\t", ""):gsub("%s+", " ")
            local drivingLicense = text:match("Driving License (%d+) Hours")
            local flyingLicense = text:match("Flying License (%d+) Hours")
            sampAddChatMessage(nickName .. " | Driving: " .. drivingLicense .. " Flying " .. flyingLicense, -1)
        elseif playerNotFound then
            sampAddChatMessage("Player ".. nickName .." not found", -1)
        else
            sampAddChatMessage("Error: " .. code, -1)
        end
    end)
end
[ML] (error) checklic.lua: ...top\GTA Folders\GTA MAINML\moonloader\lib\http_async.lua:109: attempt to call field 'addnamedthread' (a nil value)
stack traceback:
...top\GTA Folders\GTA MAINML\moonloader\lib\http_async.lua:109: in function 'request'
...top\GTA Folders\GTA MAINML\moonloader\lib\http_async.lua:113: in function 'get'
...i\Desktop\GTA Folders\GTA MAINML\moonloader\checklic.lua:13: in function <...i\Desktop\GTA Folders\GTA MAINML\moonloader\checklic.lua:11>
[ML] (error) checklic.lua: Script died due to an error. (2CE588DC)
1707845743866.png

Это библиотека, которую я выбрал, их было несколько, я не знаю, единственная ли она мне нужна, так как строка кода «require» такая.
 

Kenshi.

Известный
274
121
[ML] (error) checklic.lua: ...top\GTA Folders\GTA MAINML\moonloader\lib\http_async.lua:109: attempt to call field 'addnamedthread' (a nil value)
stack traceback:
...top\GTA Folders\GTA MAINML\moonloader\lib\http_async.lua:109: in function 'request'
...top\GTA Folders\GTA MAINML\moonloader\lib\http_async.lua:113: in function 'get'
...i\Desktop\GTA Folders\GTA MAINML\moonloader\checklic.lua:13: in function <...i\Desktop\GTA Folders\GTA MAINML\moonloader\checklic.lua:11>
[ML] (error) checklic.lua: Script died due to an error. (2CE588DC)
Посмотреть вложение 231958
Это библиотека, которую я выбрал, их было несколько, я не знаю, единственная ли она мне нужна, так как строка кода «require» такая.
мб старый copas у тебя, copas.addnamedthread не находится
 
  • Нравится
Реакции: Rezbirp

Kenshi.

Известный
274
121

SyLvy

Активный
Автор темы
231
25

copas.lua в lib
и папку copas в lib
с заменой, или удали сначала старую
[ML] (error) checklic.lua: ...i\Desktop\GTA Folders\GTA MAINML\moonloader\checklic.lua:1: module 'http_async' not found:
no field package.preload['http_async']
no file 'C:\Users\cristi\Desktop\GTA Folders\GTA MAINML\moonloader\lib\http_async.lua'
no file 'C:\Users\cristi\Desktop\GTA Folders\GTA MAINML\moonloader\lib\http_async\init.lua'
no file 'C:\Users\cristi\Desktop\GTA Folders\GTA MAINML\moonloader\http_async.lua'
no file 'C:\Users\cristi\Desktop\GTA Folders\GTA MAINML\moonloader\http_async\init.lua'
no file '.\http_async.lua'
no file 'C:\Users\cristi\Desktop\GTA Folders\GTA MAINML\moonloader\lib\http_async.luac'
no file 'C:\Users\cristi\Desktop\GTA Folders\GTA MAINML\moonloader\lib\http_async\init.luac'
no file 'C:\Users\cristi\Desktop\GTA Folders\GTA MAINML\moonloader\http_async.luac'
no file 'C:\Users\cristi\Desktop\GTA Folders\GTA MAINML\moonloader\http_async\init.luac'
no file '.\http_async.luac'
no file 'C:\Users\cristi\Desktop\GTA Folders\GTA MAINML\moonloader\lib\http_async.dll'
stack traceback:
[C]: in function 'require'
...i\Desktop\GTA Folders\GTA MAINML\moonloader\checklic.lua:1: in main chunk
[ML] (error) checklic.lua: Script died due to an error. (31479314)
Похоже, у меня были файлы copas, я удалил http_async, потому что раньше он не работал, в чем может быть проблема?
 

Kenshi.

Известный
274
121
[ML] (error) checklic.lua: ...i\Desktop\GTA Folders\GTA MAINML\moonloader\checklic.lua:1: module 'http_async' not found:
no field package.preload['http_async']
no file 'C:\Users\cristi\Desktop\GTA Folders\GTA MAINML\moonloader\lib\http_async.lua'
no file 'C:\Users\cristi\Desktop\GTA Folders\GTA MAINML\moonloader\lib\http_async\init.lua'
no file 'C:\Users\cristi\Desktop\GTA Folders\GTA MAINML\moonloader\http_async.lua'
no file 'C:\Users\cristi\Desktop\GTA Folders\GTA MAINML\moonloader\http_async\init.lua'
no file '.\http_async.lua'
no file 'C:\Users\cristi\Desktop\GTA Folders\GTA MAINML\moonloader\lib\http_async.luac'
no file 'C:\Users\cristi\Desktop\GTA Folders\GTA MAINML\moonloader\lib\http_async\init.luac'
no file 'C:\Users\cristi\Desktop\GTA Folders\GTA MAINML\moonloader\http_async.luac'
no file 'C:\Users\cristi\Desktop\GTA Folders\GTA MAINML\moonloader\http_async\init.luac'
no file '.\http_async.luac'
no file 'C:\Users\cristi\Desktop\GTA Folders\GTA MAINML\moonloader\lib\http_async.dll'
stack traceback:
[C]: in function 'require'
...i\Desktop\GTA Folders\GTA MAINML\moonloader\checklic.lua:1: in main chunk
[ML] (error) checklic.lua: Script died due to an error. (31479314)
Похоже, у меня были файлы copas, я удалил http_async, потому что раньше он не работал, в чем может быть проблема?
Код:
--[[
    ❗❗❗ THIS FILE STILL WORKS BUT DEPRECATED ❗❗❗
    ❗❗❗ PLEASE, USE require("http_v2") INSTEAD
    https://github.com/TRIGONIM/lua-requests-async/blob/main/lua/http_v2.lua
]]

local copas = require("copas")
local ht    = require("copas.http")

http_async.lua требует copas, если ты скачал последнюю версию copas с github`а, то возвращай http_async.lua в lib и пробуй опять делать запрос
 

SyLvy

Активный
Автор темы
231
25
Теперь это работает, спасибо.
Но когда он говорит «Истек срок действия», он показывает тот же номер, что и другие. Что делать? ( https://www.rpg.b-zone.ro/players/general/stan )
1707853668257.png


Еще вопросы, если хотите мне помочь:
- https://www.rpg.b-zone.ro/players/bunker/Stan Как получить такую информацию:
1707853771671.png

И отправить их в чат?
1707853806254.png

 

Rezbirp

Известный
72
69
Теперь это работает, спасибо.
Но когда он говорит «Истек срок действия», он показывает тот же номер, что и другие. Что делать? ( https://www.rpg.b-zone.ro/players/general/stan )

Lua:
--в методе
local sailingLicense = valueOrZero(text:match("Sailing License (%d+) Hours"))

--где-то в конец
function valueOrZero(arg)
    return (arg and arg or 0)
end
Еще вопросы, если хотите мне помочь:
- https://www.rpg.b-zone.ro/players/bunker/Stan Как получить такую информацию:

Регулярками, также +- как и часы в лицензиях.

 

SyLvy

Активный
Автор темы
231
25
Lua:
--in the method
local sailingLicense = valueOrZero(text:match("Sailing License (%d+) Hours"))

-- somewhere at the end
function valueOrZero(arg)
    return (arg and arg or 0)
end


Regular watches, as well as + - like the hours in the licenses.

Lua:
local http = require("http_async")
local copas = require("copas")
local ht    = require("copas.http")
function main()
    sampRegisterChatCommand("checklic", checklic)
    while true do
        wait(100)
        require("copas").step()
    end
end

function checklic(nickName)
sampAddChatMessage('[LVSI Helper]{ffffff} Searching for player license data..', 0xFF00FF78)
    local url = "https://www.rpg.b-zone.ro/players/general/"..nickName
    http.get(url, function(body, len, headers, code)
        local playerNotFound = body:find("Player not found")
        if code == 200 and not playerNotFound then
            local text = body:gsub("<.->", ""):gsub("\n",""):gsub("\t", ""):gsub("%s+", " ")
            local drivingLicense = valueOrZero(text:match("Driving License (%d+) Hours"))
            local flyingLicense = valueOrZero(text:match("Flying License (%d+) Hours"))
            local sailingLicense = valueOrZero(text:match("Sailing License (%d+) Hours"))
            local fishingLicense = valueOrZero(text:match("Fishing License (%d+) Hours"))
            local weaponLicense = valueOrZero(text:match("Weapons License (%d+) Hours"))
            local materialsLicense = valueOrZero(text:match("Materials License (%d+) Hours"))
            sampAddChatMessage("[LVSI Helper]{ffffff} "..nickName.." | Flying: "..flyingLicense.." | Sailing "..flyingLicense.." | Fishing: "..fishingLicense.." | Weapon: "..weaponLicense.." | Materials: "..materialsLicense, 0xFF00FF78)
        elseif playerNotFound then
            sampAddChatMessage("Player "..nickName.." not found", -1)
        else
            sampAddChatMessage("[LVSI Helper]{ffffff} Error: "..code, 0xFF00FF78)
        end
    end)
end
function valueOrZero(arg)
     return (arg and arg or 0)
end
1707855433806.png

1707855450736.png
До сих пор появляется вот так.