Experimental IRC client, daemon and bot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

97 lines
2.4 KiB

  1. #!/usr/bin/env python3
  2. #
  3. # ZyklonB YouTube plugin, displaying info about YouTube links
  4. #
  5. # Copyright 2014 Přemysl Janouch. All rights reserved.
  6. # See the file LICENSE for licensing information.
  7. #
  8. import sys
  9. import io
  10. import re
  11. import json
  12. import urllib.request
  13. sys.stdin = io.TextIOWrapper (sys.__stdin__.buffer,
  14. encoding = 'iso8859-1', newline = '\r\n', line_buffering = True)
  15. sys.stdout = io.TextIOWrapper (sys.__stdout__.buffer,
  16. encoding = 'iso8859-1', newline = '\r\n', line_buffering = True)
  17. re_msg = re.compile ('(?::([^! ]*)(?:!([^@]*)@([^ ]*))? +)?'
  18. '([^ ]+)(?: +(.*))?\r\n$')
  19. re_args = re.compile (':?((?<=:).*|[^ ]+) *')
  20. def parse (line):
  21. global re_msg
  22. global re_args
  23. m = re_msg.match (line)
  24. if m == None:
  25. return None
  26. (nick, user, host, command, args) = m.groups ()
  27. if args == None:
  28. args = []
  29. else:
  30. args = re_args.findall (args)
  31. return (nick, user, host, command, args)
  32. def get_config (key):
  33. print ("ZYKLONB get_config :%s" % key)
  34. (_, _, _, _, args) = parse (sys.stdin.readline ())
  35. return args[0]
  36. def bot_print (what):
  37. print ('ZYKLONB print :%s' % what)
  38. youtube_api_key = get_config ('youtube_api_key')
  39. if youtube_api_key == "":
  40. bot_print ("youtube: missing `youtube_api_key'")
  41. print ("ZYKLONB register")
  42. regexes = list (map (lambda x: re.compile (x), [
  43. 'youtube\\.[a-z]+/[^ ]*[&?]v=([-_A-Za-z0-9]+)',
  44. 'youtube\\.[a-z]+/v/([-_A-Za-z0-9]+)',
  45. 'youtu\\.be/([-_A-Za-z0-9]+)'
  46. ]))
  47. def print_video_info (channel, video_id):
  48. global youtube_api_key
  49. url = 'https://www.googleapis.com/youtube/v3/' \
  50. + 'videos?id=%s&key=%s&part=snippet,contentDetails,statistics' \
  51. % (video_id, youtube_api_key)
  52. try:
  53. data = json.loads (urllib.request.urlopen
  54. (url, None, 30).read ().decode ('utf-8'))
  55. for x in data['items']:
  56. desc = "YouTube: "
  57. desc += x['snippet']['title'] + ' | '
  58. desc += x['contentDetails']['duration'][2:].lower () + ' | '
  59. desc += x['statistics']['viewCount'] + 'x'
  60. print ("PRIVMSG %s :%s" % (channel,
  61. desc.encode ('utf-8').decode ('iso8859-1')))
  62. except Exception as err:
  63. bot_print ('youtube: %s' % (err))
  64. for line in sys.stdin:
  65. msg = parse (line)
  66. if msg == None:
  67. continue
  68. (nick, user, host, command, args) = msg
  69. if command != 'PRIVMSG' or len (args) < 2:
  70. continue
  71. ctx = args[0]
  72. if not ctx.startswith (('#', '+', '&', '!')):
  73. ctx = nick
  74. for regex in regexes:
  75. for i in regex.findall (args[1]):
  76. print_video_info (ctx, i)