requests

Daniel_Govnocode

Активный
Автор темы
324
60
Версия MoonLoader
Другое
Не могу понять что не так. Постоянно возвращает nil
Lua:
function getGPT(message, token)
  local response = requests.post("https://ask.chadgpt.ru/api/public/gpt-4o-mini",
  {
        message = u8(message),
        api_key = token,
        history = {
            role = "system",
            content = u8"Ты должен проврять тексты на на нарушения. Если нарушений нет, то отвечай '-'. Если они есть, то ответь какой пункт нарушен. Отвечай кратко. Правила: "..u8(rules)
          }
        }
  )

  if response.status_code == 200 then
      print(response.is_success)
      
  else
      print('Ошибка...')
  end
end

Апи: https://chadgpt.ru/api-docs
 
Решение
Не могу понять что не так. Постоянно возвращает nil
Lua:
function getGPT(message, token)
  local response = requests.post("https://ask.chadgpt.ru/api/public/gpt-4o-mini",
  {
        message = u8(message),
        api_key = token,
        history = {
            role = "system",
            content = u8"Ты должен проврять тексты на на нарушения. Если нарушений нет, то отвечай '-'. Если они есть, то ответь какой пункт нарушен. Отвечай кратко. Правила: "..u8(rules)
          }
        }
  )

  if response.status_code == 200 then
      print(response.is_success)
    
  else
      print('Ошибка...')
  end
end

Апи: https://chadgpt.ru/api-docs
потому что is_success находится в ответе (в json который находится в response.text...

chapo

чопа сребдс // TG/IG: @moujeek
Модератор
9,042
11,895
Не могу понять что не так. Постоянно возвращает nil
Lua:
function getGPT(message, token)
  local response = requests.post("https://ask.chadgpt.ru/api/public/gpt-4o-mini",
  {
        message = u8(message),
        api_key = token,
        history = {
            role = "system",
            content = u8"Ты должен проврять тексты на на нарушения. Если нарушений нет, то отвечай '-'. Если они есть, то ответь какой пункт нарушен. Отвечай кратко. Правила: "..u8(rules)
          }
        }
  )

  if response.status_code == 200 then
      print(response.is_success)
    
  else
      print('Ошибка...')
  end
end

Апи: https://chadgpt.ru/api-docs
потому что is_success находится в ответе (в json который находится в response.text, а response это только информация содержащая данные об ответе.
Lua:
local data = decodeJson(response.text); -- или response.json()
print('is_success:', data.is_success);
 

Daniel_Govnocode

Активный
Автор темы
324
60
потому что is_success находится в ответе (в json который находится в response.text, а response это только информация содержащая данные об ответе.
Lua:
local data = decodeJson(response.text); -- или response.json()
print('is_success:', data.is_success);
Помогло, но теперь другая ошибка
Lua:
local response = requests.post("https://ask.chadgpt.ru/api/public/gpt-4o-mini",
  {
        message = message,
        api_key = token
        
        }
  )

  if response.status_code == 200 then
    local data = decodeJson(response.text)
    print('error:', data.error_message)     
  else
      print('Ошибка скачивания...')
  end
В консоль выводит
error: failed-parse-input-json

Что не так?
 

chapo

чопа сребдс // TG/IG: @moujeek
Модератор
9,042
11,895
Помогло, но теперь другая ошибка
Lua:
local response = requests.post("https://ask.chadgpt.ru/api/public/gpt-4o-mini",
  {
        message = message,
        api_key = token
       
        }
  )

  if response.status_code == 200 then
    local data = decodeJson(response.text)
    print('error:', data.error_message)    
  else
      print('Ошибка скачивания...')
  end
В консоль выводит
error: failed-parse-input-json

Что не так?
мб жсон невалидный, выведи response.text и скинь сюда
 

chapo

чопа сребдс // TG/IG: @moujeek
Модератор
9,042
11,895
  • Нравится
Реакции: qdIbp

Daniel_Govnocode

Активный
Автор темы
324
60
Lua:
function getGPT(message, token)
  local json = json.encode({
    message = message,
    api_key = token
  })
  local response = requests.post("https://ask.chadgpt.ru/api/public/gpt-4o-mini", json)
 


  if response.status_code == 200 then
    local data = decodeJson(response.text)
    print('response text:', response.text)
    print('error:', data.error_message)     
  else
      print('Ошибка...')
      print('status_code:', response.status_code)
      print('response text:', response.text)
  end
end

Короче сейчас вот так, но теперь скрипт вообще крашит с ошибкой:

Код:
[ML] (error) ChatRules.lua: ...b3664FfRk20kkzHol3gPg\samp03\moonloader\lib\requests.lua:72: attempt to index local 'request' (a string value)
stack traceback:
    ...b3664FfRk20kkzHol3gPg\samp03\moonloader\lib\requests.lua:72: in function 'post'
    ...lyIb3664FfRk20kkzHol3gPg\samp03\moonloader\ChatRules.lua:106: in function 'getGPT'
    ...lyIb3664FfRk20kkzHol3gPg\samp03\moonloader\ChatRules.lua:57: in function <...lyIb3664FfRk20kkzHol3gPg\samp03\moonloader\ChatRules.lua:55>
[ML] (error) ChatRules.lua: Script died due to an error. (3033994C)
 
  • Грустно
Реакции: qdIbp

Muzzle

Новичок
5
0
знатно ты заставил поебаться меня с этим, пробуй этот вариант
Lua:
    local https = require("ssl.https")
    local ltn12 = require("ltn12")

    local response = {}
    local json = json.encode({
            message = message,
            api_key = token
     })
    local result = https.request{
        url = 'https://ask.chadgpt.ru/api/public/gpt-4o-mini',
        method = "POST",
        headers = {
            ["Content-Type"] = "application/json",
            ["Content-Length"] = tostring(#json_data),
        },
        source = ltn12.source.string(json_data),
        sink = ltn12.sink.table(response),
    }
    print(table.concat(response))
 

Daniel_Govnocode

Активный
Автор темы
324
60
Короче порешал, сделал вот такую залупу.
Lua:
local copas = require 'copas'
local http = require 'copas.http'
local requests = require 'requests'
requests.http_socket, requests.https_socket = http, http

function httpRequest(method, request, args, handler) -- lua-requests
    -- start polling task
    if not copas.running then
        copas.running = true
        lua_thread.create(function()
            wait(0)
            while not copas.finished() do
                local ok, err = copas.step(0)
                if ok == nil then error(err) end
                wait(0)
            end
            copas.running = false
        end)
    end
    -- do request
    if handler then
        return copas.addthread(function(m, r, a, h)
            copas.setErrorHandler(function(err) h(nil, err) end)
            h(requests.request(m, r, a))
        end, method, request, args, handler)
    else
        local results
        local thread = copas.addthread(function(m, r, a)
            copas.setErrorHandler(function(err) results = {nil, err} end)
            results = table.pack(requests.request(m, r, a))
        end, method, request, args)
        while coroutine.status(thread) ~= 'dead' do wait(0) end
        return table.unpack(results)
    end
end

function getGPT(message, token)
  local jsonTable = {
    message = message,
    api_key = token
  }

  local headers = {['Content-Type'] = 'application/json'} -- application/json - тот свмый тип запроса
  local response, err = httpRequest('POST','https://ask.chadgpt.ru/api/public/gpt-4o-mini',{data = jsonTable})
  -- local response = requests.post("https://ask.chadgpt.ru/api/public/gpt-4o-mini", jsonTable)
  print(response)
  print(err)
  -- local response = response.json()
  if response then
    local data = decodeJson(response.text)
    print('response text:', response.text)
    print('error:', data.error_message)    
  else
      print('Ошибка...')
      print('status_code:', response.status_code)
      print('response text:', response.text)
  end
end

Но он понимает только английские сообщения. Напишу чото на русском снова ошибка failed-parse-input-json. Если поставлю u8(message) вместо message, то он тупо не понимает сообщения. Всегда отвечает "Hello! How can I assist you today?". Что делать?
 

chapo

чопа сребдс // TG/IG: @moujeek
Модератор
9,042
11,895
Короче порешал сделал вот такую залупу.
Lua:
local copas = require 'copas'
local http = require 'copas.http'
local requests = require 'requests'
requests.http_socket, requests.https_socket = http, http

function httpRequest(method, request, args, handler) -- lua-requests
    -- start polling task
    if not copas.running then
        copas.running = true
        lua_thread.create(function()
            wait(0)
            while not copas.finished() do
                local ok, err = copas.step(0)
                if ok == nil then error(err) end
                wait(0)
            end
            copas.running = false
        end)
    end
    -- do request
    if handler then
        return copas.addthread(function(m, r, a, h)
            copas.setErrorHandler(function(err) h(nil, err) end)
            h(requests.request(m, r, a))
        end, method, request, args, handler)
    else
        local results
        local thread = copas.addthread(function(m, r, a)
            copas.setErrorHandler(function(err) results = {nil, err} end)
            results = table.pack(requests.request(m, r, a))
        end, method, request, args)
        while coroutine.status(thread) ~= 'dead' do wait(0) end
        return table.unpack(results)
    end
end

function getGPT(message, token)
  local jsonTable = {
    message = message,
    api_key = token
  }

  local headers = {['Content-Type'] = 'application/json'} -- application/json - тот свмый тип запроса
  local response, err = httpRequest('POST','https://ask.chadgpt.ru/api/public/gpt-4o-mini',{data = jsonTable})
  -- local response = requests.post("https://ask.chadgpt.ru/api/public/gpt-4o-mini", jsonTable)
  print(response)
  print(err)
  -- local response = response.json()
  if response then
    local data = decodeJson(response.text)
    print('response text:', response.text)
    print('error:', data.error_message)    
  else
      print('Ошибка...')
      print('status_code:', response.status_code)
      print('response text:', response.text)
  end
end

Но он понимает только английские сообщения. Напишу чото на русском снова ошибка failed-parse-input-json. Если поставлю u8(message) вместо message то он тупо не понимает сообщения. Всегда отвечает "Hello! How can I assist you today?". Что делать?
добавь print(encodeJson(jsonTable)) перед запросом и потом скинь че там пишет (только копируй именно из мунлога, а не из консоли сампфункса)
 

Muzzle

Новичок
5
0
Короче порешал, сделал вот такую залупу.
Lua:
local copas = require 'copas'
local http = require 'copas.http'
local requests = require 'requests'
requests.http_socket, requests.https_socket = http, http

function httpRequest(method, request, args, handler) -- lua-requests
    -- start polling task
    if not copas.running then
        copas.running = true
        lua_thread.create(function()
            wait(0)
            while not copas.finished() do
                local ok, err = copas.step(0)
                if ok == nil then error(err) end
                wait(0)
            end
            copas.running = false
        end)
    end
    -- do request
    if handler then
        return copas.addthread(function(m, r, a, h)
            copas.setErrorHandler(function(err) h(nil, err) end)
            h(requests.request(m, r, a))
        end, method, request, args, handler)
    else
        local results
        local thread = copas.addthread(function(m, r, a)
            copas.setErrorHandler(function(err) results = {nil, err} end)
            results = table.pack(requests.request(m, r, a))
        end, method, request, args)
        while coroutine.status(thread) ~= 'dead' do wait(0) end
        return table.unpack(results)
    end
end

function getGPT(message, token)
  local jsonTable = {
    message = message,
    api_key = token
  }

  local headers = {['Content-Type'] = 'application/json'} -- application/json - тот свмый тип запроса
  local response, err = httpRequest('POST','https://ask.chadgpt.ru/api/public/gpt-4o-mini',{data = jsonTable})
  -- local response = requests.post("https://ask.chadgpt.ru/api/public/gpt-4o-mini", jsonTable)
  print(response)
  print(err)
  -- local response = response.json()
  if response then
    local data = decodeJson(response.text)
    print('response text:', response.text)
    print('error:', data.error_message)   
  else
      print('Ошибка...')
      print('status_code:', response.status_code)
      print('response text:', response.text)
  end
end

Но он понимает только английские сообщения. Напишу чото на русском снова ошибка failed-parse-input-json. Если поставлю u8(message) вместо message, то он тупо не понимает сообщения. Всегда отвечает "Hello! How can I assist you today?". Что делать?
чет дохуя и по сообщению кароче разрабы этой хуйни пидоры
 

Daniel_Govnocode

Активный
Автор темы
324
60
добавь print(encodeJson(jsonTable)) перед запросом и потом скинь че там пишет (только копируй именно из мунлога, а не из консоли сампфункса)
message пустое поле чота

Решил. Проблема была в u8
 
Последнее редактирование: