downloadBot.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. const Telegram = require('telegraf/telegram')
  2. const Telegraf = require('telegraf')
  3. const fs = require('fs')
  4. const https = require('https');
  5. const telegram = new Telegram(process.env.BOT_TOKEN)
  6. const bot = new Telegraf(process.env.BOT_TOKEN)
  7. bot.start( (ctx) => {
  8. console.log('started:', ctx.from.id)
  9. return ctx.reply('Welcome!')
  10. })
  11. bot.command('help', (ctx) => ctx.reply('Try send a sticker!'))
  12. bot.hears('hi', (ctx) => ctx.reply('Hey there!'))
  13. bot.hears(/buy/i, (ctx) => ctx.reply('Buy-buy!'))
  14. bot.on('sticker', (ctx) => ctx.reply('👍'))
  15. bot.on('audio', (ctx) => {
  16. console.log('message received: ', ctx.from.id)
  17. telegram.getFile( ctx.message.audio.file_id, (ctx) => {
  18. console.log('audio_id sent to TG: ', ctx.message.audio.file_id)
  19. })
  20. const specialChars = "!@#$^&%*()+=[]\/{}|:<>?,."
  21. const audio = ctx.message.audio
  22. var filename = audio.performer + " - " + audio.title
  23. for (var i = 0; i < specialChars.length; i++) {
  24. filename = filename.replace(new RegExp("\\" + specialChars[i], 'gi'), '')
  25. }
  26. filename = filename + ".mp3"
  27. const downloadDir = "/var/music/bot/"
  28. var file = fs.createWriteStream(downloadDir+filename);
  29. const promise = telegram.getFile(audio.file_id)
  30. promise.then(function(result){
  31. const requestFile = https.get("https://api.telegram.org/file/bot"+process.env.BOT_TOKEN+"/"+result.file_path, function(response) {
  32. if(response.statusCode != 200){
  33. return ctx.reply('Error downloading file: '+response.statuscode)
  34. }else{
  35. response.pipe(file);
  36. console.log('Download finished stored at: ' + downloadDir + filename)
  37. return ctx.reply('Downloaded "'+ filename + '"')
  38. }
  39. });
  40. })
  41. })
  42. bot.startPolling()