Send a message over telegram when IPSec is down or up

Hello,

I have a little Problem. I want to sent me a Telegram when the IPSec connection goes down or up.
I found some scripts for IPSec, but nothing I could use for this.

To send a telegram is not the problem, I found an example and tested it successful.
My biggest problem at the moment is, how to get the IPSec state.

I’m nor really good at scripting, but I hope anybody can help me with this.

Best Regards
Ben

Hello,
I use this script on my RB, which checks the IPSec phase2 status.
After first execution the script goes in loop mode and checks every 10 seconds.
Change XXXXX with your botId and YYYYY with chatId.
Armando.

:global stopScript2 false

:do {
	:local err "0"
	:local site [/system identity get value-name=name]
	:local day ([:pick [/system clock get date] 4 6])
	:local mon ([:pick [/system clock get date] 0 3])
	:local year ([:pick [/system clock get date] 7 11])
	:local date "$day-$mon-$year"
	:local time (:put [/system clock get time])

	:foreach i in=[/ip ipsec policy find] do={
		:if ($i != "*FFFFFF") do={
			:local state [/ip ipsec policy get $i value-name=ph2-state]
			:if ($state != "established") do={
				:set err "1"
				:log error "IPSec phase2 error"
			}
		}
	}

	:if ($err != "0") do={
		/tool fetch url="https://api.telegram.org/botXXXXX/sendMessage?chat_id=YYYYY&text=MikroTik $site info:%0A[$date $time]%0AIPSec phase2 error" keep-result=no
	}

	:delay 10
} while=(!$stopScript2)

Thank you very much.