Code Monkey home page Code Monkey logo

Comments (9)

gSpotx2f avatar gSpotx2f commented on May 31, 2024

Вот скрипт на основе скрипта из Padavan's wiki. Не ручаюсь за его работоспособность, я не пользуюсь telegram и поэтому не могу протестировать.
Скачайте скрипт в /opt/usr/bin/smarthtml_mailer_tg, разрешите выполнение: chmod +x /opt/usr/bin/smarthtml_mailer_tg. В конфиге /opt/etc/smarthtml.conf: MAILER_SCRIPT="/opt/usr/bin/smarthtml_mailer_tg" и USE_MAIL=1. Далее выпоните все шаги из инструкции Padavan'а по созданию бота в tg, заполнению API_TOKEN и CHAT_ID в smarthtml_mailer_tg. Потом тестируйте: smarthtml mailtest. Если, вдруг, всё заработает, то отпишитесь здесь и я добавлю скрипт в проект и описание в wiki.

from smarthtml.

anch665 avatar anch665 commented on May 31, 2024

Переделал smarthtml_mailer_tg с wget на curl, так он хотя бы отправляет сказанный файл в телегу,
к сожалению при выполнении smarthtml mailtest ни чего не происходит, я правильно понимаю что в каталоге /opt/var/smarthtml/message должен появится файл сообщения, в общем его там нет

MTA_MSG_FILE="$1"
DEBUG="$2"
CURL_CMD=`which curl`
if [ $? -ne 0 ]; then
    echo " Error! curl doesn't exists..." >&2
    exit 1
fi

if [ -z "$CHAT_ID" ]; then
    if [ -n "$DEBUG" ]; then
        echo "Please, define CHAT_ID first! See \"chat\":{\"id\":xxxxxxx string below:"
        $CURL_CMD  -k -i -X GET "https://api.telegram.org/bot${API_TOKEN}/getUpdates"
    fi
    exit 1
fi
MSG="<b>$(nvram get computer_name)</b>: S.M.A.R.T.

<strong>`cat "$MTA_MSG_FILE"`</strong>"

$CURL_CMD --data-urlencode "text=${MSG}" "https://api.telegram.org/bot${API_TOKEN}/sendMessage?chat_id=${CHAT_ID}&parse_mode=html" 2>&1
return_code=$0

if [ -n "$DEBUG" ]; then
    if [ $return_code -eq 0 ]; then
        echo "Message sent successfully."
    else
        echo "Error while sending message!"
        exit 1
    fi
fi

from smarthtml.

gSpotx2f avatar gSpotx2f commented on May 31, 2024

Файл с сообщением /opt/var/smarthtml/message создаётся во время выполнения smarthtml (если необходимо отправить сообщение) и удаляется сразу после отправки сообщения. Поэтому, вы его не найдёте, он существует несколько секунд пока выполняется программа.

Сам скрипт smarthtml_mailer_tg, ваша версия (с curl вместо wget) работает? Если запускать его как самостоятельный скрипт, без smarthtml?

from smarthtml.

anch665 avatar anch665 commented on May 31, 2024

Да, работает, тестовые сообщения отправляются. curl необходимо установить из entware opkg install curl
этот блок не работает, telegramm сменил API, не разбирался что да как, у меня давно работает бот и я знаю свои чатид и ботид
echo "Please, define CHAT_ID first! See \"chat\":{\"id\":xxxxxxx string below:" $CURL_CMD -k -i -X GET "https://api.telegram.org/bot${API_TOKEN}/getUpdates"

Есть правда один несущественный момент
после выполнения
/opt/usr/bin/smarthtml mailtest
сообщение отравляется, но в логах всегда ошибка
Error while sending message!
Стало интересно, сделал в коде:
echo "Error while sending message! $return_code"
на выходе получил
Error while sending message! /opt/usr/bin/smarthtml_mailer_tg

from smarthtml.

gSpotx2f avatar gSpotx2f commented on May 31, 2024

сообщение отравляется, но в логах всегда ошибка

Опечатка была в скрипте, в строке 39: вместо $0 должно быть S?.

Подытожим: smarthtml_mailer_tg с curl работает, сообщения отправляет. Код для получения CHAT_ID не работает. Надо выяснить как получить CHAT_ID или выпилить из скрипта вообще этот блок? Проверьте пожалуйста скрипт из gist, я добавил ваш код с curl...

from smarthtml.

anch665 avatar anch665 commented on May 31, 2024

Ваш вариант не работаете, т.к. телега поддерживает ограниченное количество HTML тегов, к сожалению <br> в их число не входит.
{"ok":false,"error_code":400,"description":"Bad Request: can't parse entities: Unsupported start tag \"br\" at byte offset 40"}
Кстати ответ отдается в таком виде и соответственно блок кода ниже работает не так как надо
if [ -n "$DEBUG" ]; then if [ $return_code -eq 0 ]; then echo "Message sent successfully." else echo "Error while sending message!" exit 1 fi fi
return_code всегда возвращает 0

from smarthtml.

anch665 avatar anch665 commented on May 31, 2024

оставил такой вариант, и он у меня работает
разобрался с https://api.telegram.org/bot${API_TOKEN}/getUpdates, тут все в порядке, отображает как надо

`
export PATH="/opt/bin:/opt/sbin:/opt/usr/bin:/usr/sbin:/usr/bin:/sbin:/bin"
export LANG="en_US.UTF-8"
export LANGUAGE="en"
export HOSTNAME="$HOSTNAME"

MAILER_MSG_FILE="$1"
DEBUG="$2"
CURL_CMD=which curl
if [ $? -ne 0 ]; then
echo " Error! curl doesn't exists..." >&2
exit 1
fi

if [ -z "$CHAT_ID" ]; then
if [ -n "$DEBUG" ]; then
echo "Please, define CHAT_ID first! See "chat":{"id":xxxxxxx string below:"
$CURL_CMD -k -i -X GET "https://api.telegram.org/bot${API_TOKEN}/getUpdates"
fi
exit 1
fi

MSG="cat "$MAILER_MSG_FILE""

$CURL_CMD --data-urlencode "text=${MSG}" "https://api.telegram.org/bot${API_TOKEN}/sendMessage?chat_id=${CHAT_ID}&parse_mode=html"`

from smarthtml.

gSpotx2f avatar gSpotx2f commented on May 31, 2024

Теги вернул к начальному варианту, как было в оригинальном скрипте. Посмотрел доки tg, он поддерживает лишь несколько тэгов для выделения текста.

return_code всегда возвращает 0

$return_code равен 0 если curl работает без ошибок. Ошибки API телеграма находятся внутри успешного результата работы curl :) В общем, $return_code - это проверка правильной работы curl, а не телеграма.

from smarthtml.

anch665 avatar anch665 commented on May 31, 2024

Отлично! работает, можно добавлять в вики

from smarthtml.

Related Issues (3)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.