Здравствуйте, гость ( Вход | Регистрация )

> Telegram lua api for pilot, управление пилотом через телеграм
Madeus
сообщение 8.8.2022, 20:54
Сообщение #1


*****

Journeyman
Сообщений: 319
Регистрация: 19.11.2019
Группа: Пользователи
Наличность: 11519
Пользователь №: 19.451
Возраст: 32



За основу взят telegram-bot-lua и внесены фиксы для реалий пилота.

Исправлены ошибки появившиеся в связи с даунгрейдом lua, оригинал написан под lua 5.3, в пилоте lua 5.1.
Добавлена поддержка кириллицы в кодировке win1251 для пилота.
Добавлена поддержка lua-cjson, в оригинале используется dkjson, делал для себя желающие могут откатиться, исходник есть в архиве.
Так же прилагаются все необходимые библиотеки для работы включая ssl 32 bit.

Для использования вам понадобятся:
  • телеграм
  • token бота зарегистрированный через @BotFather
  • ваш chat id узнать его можно через множество ботов например тут @getmyid_bot
Распаковать в корень папки пилота.

Примеры использования.

Отправить боту сообщение / фото / файл. Можно использовать как информационные сообщения о состоянии вашего скрипта
Пример 1
Код
--lua
local api = require('telegram.core').configure(TOKEN) -- вместо TOKEN указываем свой полученный в @BotFather
local chat_id = CHAT_ID -- вместо CHAT_ID указываем свой, узнать можно с помощью ботов коих немало в сети

api.send_message(chat_id, 'Hello bot') -- отправить сообщение
api.send_photo(chat_id, [[c:\photo.jpg]]) -- отправить фото
api.send_document(chat_id, [[c:\file.txt]]) -- отправить файл


В следующем примере полноценный бот по задумке открывается в нулевой "0" вкладке (можно запускать пилот с флагом /r0 для автоматического запуска бота. "с:\uopilot\uopilot.exe" /r0).
Умеет:
  • Запускать, останавливать скрипты, так же показывать их текущий статус
  • Присылать лог в виде сообщения или текстового файла (для файла необходимо раскоментировать строку)
  • Делать скриншот экрана и присылать его в виде фото
  • Закрывать окна программ по заголовку(имени) окна. Необходимо отправить боту сообщение вида Terminate #имя окна#, например Terminate Блокнот
Пример бот
Код
--lua
local api = require('telegram.core').configure(TOKEN) -- вместо TOKEN указываем свой полученный в @BotFather
local chat_id = CHAT_ID -- вместо CHAT_ID указываем свой, узнать можно с помощью ботов коих немало в сети

local function start_keyboard()
  local keyboard = {['inline_keyboard'] = {{}}}
  local count_scipts = scripts()
  local row = 1
  local count = 0
  for i = 2, #count_scipts do
    count = count + 1
    if count == 8 then
      row = row + 1
      table.insert(keyboard.inline_keyboard, {})
      count = 0
    end
    table.insert(keyboard.inline_keyboard[row], {['text'] = count_scipts[i][1], ['callback_data'] = 'Start ' .. count_scipts[i][1]})
  end
  return keyboard
end

local function stop_keyboard()
  local keyboard = {['inline_keyboard'] = {{}}}
  local count_scipts = scripts()
  local row = 1
  local count = 0
  for i = 2, #count_scipts do
    count = count + 1
    if count == 8 then
      row = row + 1
      table.insert(keyboard.inline_keyboard, {})
      count = 0
    end
    table.insert(keyboard.inline_keyboard[row], {['text'] = count_scipts[i][1], ['callback_data'] = 'Stop ' .. count_scipts[i][1]})
  end
  return keyboard
end

local function status_keyboard()
  local keyboard = {['inline_keyboard'] = {{}}}
  local count_scipts = scripts()
  local row = 1
  local count = 0
  for i = 2, #count_scipts do
    count = count + 1
    if count == 8 then
      row = row + 1
      table.insert(keyboard.inline_keyboard, {})
      count = 0
    end
    table.insert(keyboard.inline_keyboard[row], {['text'] = count_scipts[i][1], ['callback_data'] = 'Script ' .. count_scipts[i][1] .. ' Status ' .. count_scipts[i][3]})
  end
  return keyboard
end

api.send_message(chat_id, 'Pilot online', nil, true, false, nil, api.keyboard():row(api.row():button('Start script'):button('Stop script')):row(api.row():button('Status script'):button('Log')):row(api.row():button('Screenshot')))

local subs = {runing = 'сейчас запущен', stoped = 'сейчас остановлен'}

function api.on_callback_query(callback_query)
  local script_num, status
  local message = callback_query.message
  if callback_query.data:match('Start') then
    script_num = callback_query.data:match('Start (%d+)')
    if script_num then
      api.edit_message_text(message.chat.id, message.message_id, 'Запустил срипт ' .. script_num)
      start_script(script_num)
    end
  elseif callback_query.data:match('Stop') then
    script_num = callback_query.data:match('Stop (%d+)')
    if script_num then
      api.edit_message_text(message.chat.id, message.message_id, 'Остановил скрипт ' .. script_num)
      stop_script(script_num)
    end
  elseif callback_query.data:match('Status') then
    script_num, status = callback_query.data:match('Script (%d+) Status (%S+)')
    if script_num and status then
      api.edit_message_text(message.chat.id, message.message_id, 'Скрипт ' .. script_num .. ' ' .. string.gsub(status, '(%w+)', subs))
    end
  end
end

function api.on_message(message)
  if message.chat.id == chat_id then
    if message.text and message.text:match('Screenshot') then
      printscreen (0, 0, 0, 0, 0, 'screen.jpg')
      api.send_photo(chat_id, 'screen.jpg')
    elseif message.text and message.text:match('Start script') then
      api.send_message(message.chat.id, 'Выбери какой скрипт запустить:', nil, true, false, nil, start_keyboard())
    elseif message.text and message.text:match('Stop script') then
      api.send_message(message.chat.id, 'Выбери какой скрипт остановить:', nil, true, false, nil, stop_keyboard())
    elseif message.text and message.text:match('Status script') then
      api.send_message(message.chat.id, 'Выбери какой скрипт проверить:', nil, true, false, nil, status_keyboard())
    elseif message.text and message.text:match('Log') then
      local log_path = 'pilot_log.txt'
      log('save', log_path)
      local log_file = io.open(log_path)
      local log_text = log_file:read('*a')
      log_file:close()
      if #log_text > 0 then
--      api.send_document(message.chat.id, log_path) -- если нужно отправить файл лога раскоментируй строку
        api.send_message(message.chat.id, log_text)
      else
        api.send_message(message.chat.id, 'Log пустой')
      end
    elseif message.text and message.text:match('Terminate') then -- что бы закрыть окно любой программы отправь боту сообщение вида 'Terminate #заголовок окна#' например 'Terminate Блокнот'
      local terminate_window = message.text:match('Terminate%s+(.+)')
      if terminate_window then
        local handle = findwindow(terminate_window)
        if handle then
          terminate(terminate_window)
          api.send_message(message.chat.id, 'Окно ' .. terminate_window .. ' закрыто')
        else
          api.send_message(message.chat.id, 'Окно ' .. terminate_window .. ' не найдено')
        end
      end
    end
  end
end

api.run(1, 100)


Прикрепленные файлы
Прикрепленный файл  telegram.zip ( 2,83 мегабайт ) Кол-во скачиваний: 419
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
 
Ответить в эту темуОткрыть новую тему
Ответов
DarkMaster
сообщение 6.1.2023, 12:51
Сообщение #2


***********

Модератор UOPilot
Сообщений: 9.765
Регистрация: 2.12.2008
Группа: Супермодераторы
Наличность: 29992
Пользователь №: 11.279



Desktop area have shared coordinates. As example if you have 2 monitors and they was positioned in horizontal line and have full hd resolution, then frist monitor will start from 0, 0 end at 1919, 1079, second will start from 1920, 0 and will and at 3839, 1079.

But be careful with positioning. It can have almost any offset. For be sure in offset if you have non standard config you can check it paint by placing full screenshot or check it in register:

HKEY_CURRENT_CONFIG\System\CurrentControlSet\Control\Video

or


For anyone that is looking for the key in Windows 7 it is in one of the folders in:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\GraphicsDrivers\Configuration\

Look for Position.cx and Position.cy in each of the subfolders; you have to edit the hex string.

Сообщение отредактировал DarkMaster - 6.1.2023, 12:51


--------------------
Скрипты UOPilot под заказ.
Консультации по UOpilot 15$/час.
Услуги Lua разработчика (не пилот, проекты, постоянка)
Disсоrd:
Kov____

Контакт актуален, подпись актуальна.
Пользователь в онлайне!Delete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения
TheQQmaster
сообщение 6.1.2023, 20:29
Сообщение #3


**

Neophyte
Сообщений: 12
Регистрация: 17.9.2017
Группа: Пользователи
Наличность: 0
Пользователь №: 18.608
Возраст: 25



Цитата(DarkMaster @ 6.1.2023, 11:51) *

Desktop area have shared coordinates. As example if you have 2 monitors and they was positioned in horizontal line and have full hd resolution, then frist monitor will start from 0, 0 end at 1919, 1079, second will start from 1920, 0 and will and at 3839, 1079.

But be careful with positioning. It can have almost any offset. For be sure in offset if you have non standard config you can check it paint by placing full screenshot or check it in register:

HKEY_CURRENT_CONFIG\System\CurrentControlSet\Control\Video

or
For anyone that is looking for the key in Windows 7 it is in one of the folders in:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\GraphicsDrivers\Configuration\

Look for Position.cx and Position.cy in each of the subfolders; you have to edit the hex string.

thx, solved (IMG:style_emoticons/default/smile.gif)
u could respond russian, i understand ,but bad with typing
Пользователь в офлайнеDelete PostОтправить личное сообщение
Вернуться в начало страницы
+Ответить с цитированием данного сообщения



Ответить в эту темуОткрыть новую тему
1 чел. читают эту тему (гостей: 1, скрытых пользователей: 0)
Пользователей: 0

 

- Текстовая версия | Версия для КПК Сейчас: 25.10.2025, 22:10
Designed by Nickostyle