chube_search.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import asyncio
  2. import os
  3. import aiohttp
  4. from chube_enums import Message
  5. from chube_ws import Resolver, make_message
  6. API_KEY = os.environ.get('GOOGLE_SEARCH_API_KEY')
  7. SEARCH_URL = "https://www.googleapis.com/youtube/v3/search"
  8. SEARCH_ID_URL = "https://www.googleapis.com/youtube/v3/videos"
  9. BASE_QUERY_SEARCH = [('part', 'snippet'), ('type', 'video'), ('videoEmbeddable', 'true'), ('safeSearch', 'none'),
  10. ('key', API_KEY)]
  11. BASE_QUERY_ID_SEARCH = [('part', 'snippet'), ('key', API_KEY)]
  12. async def search_processor(ws, data, path):
  13. async with aiohttp.ClientSession() as session:
  14. async with session.get(SEARCH_URL, params=BASE_QUERY_SEARCH + [('q', data['q'])]) as response:
  15. json_data = await response.json()
  16. await ws.send(make_message(Message.SEARCH, json_data))
  17. async def search_id_processor(ws, data, path):
  18. ids = data["id"]
  19. if not isinstance(ids, list):
  20. ids = {ids}
  21. else:
  22. ids = set(ids)
  23. async with aiohttp.ClientSession() as session:
  24. async with session.get(SEARCH_ID_URL, params=BASE_QUERY_ID_SEARCH + [('id', ",".join(ids))]) as response:
  25. json_data = await response.json()
  26. await ws.send(make_message(Message.SEARCH_ID, json_data))
  27. def make_resolver():
  28. resolver = Resolver()
  29. resolver.register(Message.SEARCH, search_processor)
  30. resolver.register(Message.SEARCH_ID, search_id_processor)
  31. return resolver
  32. if __name__ == "__main__":
  33. async def foo():
  34. async with aiohttp.ClientSession() as session:
  35. async with session.get(SEARCH_URL, params=BASE_QUERY_SEARCH + [('q', "She")]) as response:
  36. json_data = await response.json()
  37. print(json_data)
  38. loop = asyncio.get_event_loop()
  39. loop.run_until_complete(foo())