Advertisement
DreamWolf

Echo

Dec 26th, 2024 (edited)
14
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. -- EchoStream.lua
  2. local component = require("component")
  3. local internet = require("internet")
  4. local JSON = require("json")
  5.  
  6. local EchoStream = {}
  7.  
  8. -- Инициализация бота
  9. function EchoStream.init(telegramToken)
  10. EchoStream.telegramToken = telegramToken
  11. EchoStream.lastUpdateId = 0
  12. end
  13.  
  14. -- Функция для получения сообщения
  15. function EchoStream.receive()
  16. local url = string.format(
  17. "https://api.telegram.org/bot%s/getUpdates?offset=%d&timeout=60&allowed_updates=[\"message\"]",
  18. EchoStream.telegramToken, EchoStream.lastUpdateId + 1
  19. )
  20.  
  21. print("Запрос для получения сообщений: " .. url)
  22.  
  23. local result, response = pcall(function()
  24. local handle = internet.request(url)
  25. local responseData = ""
  26. for chunk in handle do
  27. responseData = responseData .. chunk
  28. end
  29. return responseData
  30. end)
  31.  
  32. if not result or not response then
  33. return nil
  34. end
  35.  
  36. local decoded, err = JSON:decode(response)
  37. if err then
  38. print("Ошибка декодирования JSON: " .. err)
  39. return nil
  40. end
  41.  
  42. if decoded and decoded.ok and decoded.result then
  43. for _, update in ipairs(decoded.result) do
  44. if update.update_id > EchoStream.lastUpdateId then
  45. EchoStream.lastUpdateId = update.update_id
  46. if update.message.text then
  47. print("Получено сообщение: " .. update.message.text)
  48. return update.message.text
  49. end
  50. end
  51. end
  52. end
  53. return nil
  54. end
  55.  
  56. return EchoStream
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement