Search code examples
arraysbashgitlab-citelegram-api

Generate Telegram API sendMediaGroup request with bash


I want to send all video files from current dir to Telegram from Gitlab CI. Image has no python or jq, I need to generate command from files list:

curl -F "chat_id=13245679" \
     -F 'media=[{"type": "video", "media": "attach://file1"}, {"type": "video", "media": "attach://file2" }]' \
     -F "file1=@/tmp/test1.txt" \
     -F "file2=@/tmp/test2.txt" \
     "https://api.telegram.org/bot<BOT-TOKEN>/sendMediaGroup"

I can create JSON like this:

export T=$(printf '{"type": "video", "media": "attach://%s"}, ' *)
-F "media=[${T::-1}]"

But I can't create list of attachments (like this printf '-F "%s=@%s" ' *).


Solution

  • The bash implementation of printf doesn't support reuse of arguments. The format string %s=@%s will suck up two arguments at a time and repeat until all arguments are exhausted.

    If we're sticking to bash, you can loop over the files and individually create an argument for each one. Try something like this:

    #!/bin/bash
    form_args=()
    for f in * ; do
      form_args+=( -F )
      form_args+=( "$( printf '%s=@%s' "$f" "$f" )" )
    done
    curl -F 'chat_id=13245679' -F 'media=...' "${form_args[@]}"