Last active
March 27, 2018 08:19
-
-
Save peterc/6e7926cb3cb8d778b44ca4d1ac2bc1cf to your computer and use it in GitHub Desktop.
Download audio messages from a Telegram channel or chat and turn them into a single MP3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'dotenv' | |
Dotenv.load | |
require 'telegram/bot' | |
require 'json' | |
require 'open-uri' | |
token = ENV['TELEGRAM_TOKEN'] | |
files = [] | |
Telegram::Bot::Client.run(token) do |bot| | |
# Grab updates from the Telegram bot | |
updates = bot.api.get_updates(allowed_updates: ["channel_post"])["result"] | |
# Select only voice posts from the past 24 hours | |
updates.select! { |msg| msg['channel_post'] && msg['channel_post']['voice'] && msg['channel_post']['date'] && ((Time.now.to_i - msg['channel_post']['date']) < 86400) } | |
# Iterate over each update | |
updates.each.with_index do |msg, i| | |
voice = msg['channel_post']['voice'] | |
# Get the Telegram file ID, then the file object itself | |
file_id = voice['file_id'] | |
res = bot.api.get_file(file_id: file_id) | |
file_path = res['result']['file_path'] | |
# Construct the URL the audio is available at and download it | |
url = "https://api.telegram.org/file/bot#{token}/#{file_path}" | |
puts "Fetching audio #{i}: #{file_path}" | |
data = open(url).read | |
temp_file = "/tmp/output-#{i}.mp3" | |
File.open("/tmp/temp.oga", "w") { |f| f.puts data } | |
# Normalize the format of the audio into a 44.1KHz 96kbps mono MP3 | |
`ffmpeg -loglevel panic -y -i /tmp/temp.oga -ab 96000 -ar 44100 -filter:a loudnorm -ac 1 #{temp_file}` | |
files << temp_file | |
end | |
end | |
# Join MP3s together with beeps in between each segment | |
`cat #{files.zip(['beep.mp3'] * (files.length - 1)).join(' ')} > output.mp3` | |
# Clean up the final MP3 (brew install mp3val) | |
`mp3val output.mp3 -f -nb` | |
puts "output.mp3 is built" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment