4

How can I send an MP3 audio file to a Telegram Bot using the open-source Python library Requests?

I wrote the following code:

URL = 'api.telegram.org/bot'+TOKEN+'/sendAudio'
af = open("temp.mp3", 'rb')
params = {'chat_id' : 421087308, 'audio' : af}
req = requests.post(URL, params)
af.close()
jdoe
  • 634
  • 5
  • 19
ChemBean
  • 63
  • 1
  • 2
  • 5
  • What is the error with the current code? – jdoe Oct 24 '17 at 19:20
  • 2
    Using the [python telegram bot wrapper](https://github.com/python-telegram-bot/python-telegram-bot) you can easily do it using: `bot.send_audio(chat_id=chat_id, audio=open('tests/test.mp3', 'rb'))` – jdoe Oct 24 '17 at 19:22
  • Did the above code work? – jdoe Oct 26 '17 at 16:39
  • Yes, this code work – ChemBean Oct 26 '17 at 16:41
  • Then, please consider accepting it by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – jdoe Oct 26 '17 at 16:43

3 Answers3

12

Using the python telegram bot wrapper you can easily do it using:

bot.send_audio(chat_id=chat_id, audio=open('tests/test.mp3', 'rb'))
jdoe
  • 634
  • 5
  • 19
3

python-telegram-bot can be redundant if you need a bot for a single action like sending mp3 file. So if you want to send the file by using the requests library, you can use following snippet:

with open('tests/test.mp3', 'rb') as audio:
    payload = {
        'chat_id': TELEGRAM_CHAT_ID,
        'title': 'file.mp3',
        'parse_mode': 'HTML'
    }
    files = {
        'audio': audio.read(),
    }
    resp = requests.post(
        "https://api.telegram.org/bot{token}/sendAudio".format(token=TELEGRAM_TOKEN),
        data=payload,
        files=files).json()
mxschumacher
  • 37
  • 1
  • 7
discort
  • 678
  • 1
  • 8
  • 26
0

Try this cammand:

update.message.reply_audio(audio='https://audio_link.mp3')