Skip to content

Instantly share code, notes, and snippets.

Last active April 12, 2024 08:21
Show Gist options
  • Save obokaman-com/07e66dcfcbcbe09bce50c970fabac079 to your computer and use it in GitHub Desktop.
Save obokaman-com/07e66dcfcbcbe09bce50c970fabac079 to your computer and use it in GitHub Desktop.
A bash script to start Ngrok in background, and send ngrok URL to a Telegram Bot automatically, copying the remote URL to clipboard
#!/usr/bin/env bash
# Start NGROK in background
echo "⚡️ Starting ngrok"
ngrok http 8080 > /dev/null &
# Wait for ngrok to be available
while ! nc -z localhost 4040; do
sleep 1/5 # wait Ngrok to be available
# Get NGROK dynamic URL from its own exposed local API
NGROK_REMOTE_URL="$(curl http://localhost:4040/api/tunnels | jq ".tunnels[0].public_url")"
if test -z "${NGROK_REMOTE_URL}"
echo "❌ ERROR: ngrok doesn't seem to return a valid URL (${NGROK_REMOTE_URL})."
exit 1
# Trim double quotes from variable
NGROK_REMOTE_URL=$(echo ${NGROK_REMOTE_URL} | tr -d '"')
# If http protocol is returned, replace by https
# Get script parent folder to point to .env file and get TELEGRAM_BOT_TOKEN dynamically
PARENT_PATH=$( cd "$(dirname "${BASH_SOURCE[0]}")" || exit ; pwd -P )
# Get TELEGRAM_BOT_TOKEN dynamically from local .env file
TELEGRAM_BOT_TOKEN=$(grep TELEGRAM_BOT_TOKEN ${PARENT_PATH}/../.env.local | cut -d '=' -f2)
if test -z "${TELEGRAM_BOT_TOKEN}"
echo "❌ ERROR: I haven't been able to recover TELEGRAM_BOT_TOKEN from your local .env.local variables file."
exit 1
# Set our NGROK remote url to our development
curl -F "url=${NGROK_REMOTE_URL}/webhook/telegram/${TELEGRAM_BOT_TOKEN}/"${TELEGRAM_BOT_TOKEN}/setWebhook
bold=$(tput bold)
normal=$(tput sgr0)
echo ${NGROK_REMOTE_URL} | tr -d '\n' | pbcopy
printf "\n\n🌍 Your ngrok remote URL is 👉 ${bold}${NGROK_REMOTE_URL} 👈\n📋 ${normal}I've just copied it to your clipboard 😉\n\n"
Copy link

Madjda commented Oct 13, 2022

Thanks! That was very handy!
But I had to add a sleep after starting ngrok else NGROK_REMOTE_URL was null. (am on the free version)

Copy link

FYI to stop backgrounded ngrok use the following command:


  echo "Stopping background ngrok process"
  kill -9 $(ps -ef | grep 'ngrok' | grep -v 'grep' | awk '{print $2}')
  echo "ngrok stopped"

Copy link

Thanks for the suggestion, @OlegChuev

Copy link

yoo love code
can i mod and add tiny ssh comands tho ?
stuff like /status /reboot ?
and drop it on a game bot forum for shakes and fidged all creds go to you ofc

Copy link

Of course, feel free to modify / improve / share at your convenience, @poopy-droid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment