Guest User

Untitled

a guest
Jun 11th, 2020
740
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.95 KB | None | 0 0
  1. import io
  2. import os
  3.  
  4. from aiohttp import web
  5. from telethon import utils
  6. from telethon.sync import TelegramClient
  7. from telethon.tl.types import DocumentAttributeAudio
  8.  
  9. bot = TelegramClient('bot', int(os.environ['TG_API_ID']), os.environ['TG_API_HASH']) \
  10.     .start(bot_token=os.environ['TG_TOKEN'])
  11.  
  12.  
  13. async def send_audio(request):
  14.     data = await request.post()
  15.  
  16.     if "chat_id" not in data:
  17.         return web.Response(status=400,
  18.                             text='Bad Request: there is no chat_id in the request')
  19.     if "audio" not in data:
  20.         return web.Response(status=400, text='Bad Request: there is no audio in the request')
  21.  
  22.     attrs = DocumentAttributeAudio(0)
  23.     if "duration" in data:
  24.         attrs.duration = int(data['duration'])
  25.     if "title" in data:
  26.         attrs.title = data['title']
  27.     if "performer" in data:
  28.         attrs.performer = data['performer']
  29.  
  30.     f = data['audio']
  31.     audio = io.BytesIO(f.file.read())
  32.     audio.name = f.filename
  33.  
  34.     thumb = None
  35.     if "thumb" in data:
  36.         thumb = io.BytesIO(data['thumb'].file.read())
  37.         thumb.name = 'thumb.jpg'
  38.  
  39.     try:
  40.         res = await bot.send_file(int(data['chat_id']),
  41.                                   file=audio,
  42.                                   caption=data.get('caption'),
  43.                                   parse_mode=data.get('parse_mode'),
  44.                                   thumb=thumb,
  45.                                   attributes=[attrs])
  46.     except Exception as e:
  47.         return web.Response(status=500, text=str(e))
  48.  
  49.     if res.media is None:
  50.         return web.Response(status=500, text='Upload error')
  51.  
  52.     file_id = utils.pack_bot_file_id(res.media.document)
  53.  
  54.     if file_id is None:
  55.         return web.Response(status=500, text='ID encoding error')
  56.  
  57.     return web.Response(text=file_id)
  58.  
  59.  
  60. app = web.Application(client_max_size=200*1024*1024)
  61. app.add_routes([web.post('/sendAudio', send_audio)])
  62.  
  63. web.run_app(app)
Advertisement
Add Comment
Please, Sign In to add comment