Advertisement
Guest User

Untitled

a guest
Mar 17th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.70 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. # encoding=utf8
  3. import logging
  4. import requests
  5. import socket
  6. import string
  7. import sys
  8. from time import sleep
  9. import lxml.html as html
  10.  
  11. reload(sys)
  12. sys.setdefaultencoding('utf-8')
  13.  
  14. HOST = "irc.chat.twitch.tv"
  15. NICK = "dj_denis97"
  16. PORT = 6667
  17. PASS = "" # Брать тут http://twitchapps.com/tmi/
  18. readbuffer = ""
  19. MODT = False
  20. game = "https://api.rtainc.co/twitch/channels/just4fun__/status?format=[1]"
  21. time = "https://api.rtainc.co/twitch/channels/just4fun__/uptime?format=%5B1%5D&units=2"
  22.  
  23. # Подключаемся к IRC твича предавая ему данные, и подключаемся к указанному каналу
  24. s = socket.socket()
  25. s.connect((HOST, PORT))
  26. s.send("PASS " + PASS + "\r\n")
  27. s.send("NICK " + NICK + "\r\n")
  28. s.send("JOIN #just4fun__ \r\n")
  29.  
  30.  
  31. def get_mmr():
  32. headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36'}
  33. r = requests.get('https://www.dotabuff.com/players/109462682', headers=headers)
  34. page = html.document_fromstring(r.text)
  35. return page.find_class('header-content-secondary')[0].text_content().split('h')[1].split('S')[0]
  36.  
  37.  
  38. def smart_time(h, m):
  39. result = 'Стрим идет '
  40. if h is not None:
  41. if h == 1:
  42. result += '1 час, '
  43. elif str(h)[0] == '2' or str(h)[0] == '3' or str(h) == '4':
  44. result = result + str(h) + ' часа, '
  45. else:
  46. result = result + str(h) + ' часов, '
  47. if str(m)[-1] == 1:
  48. result = result + str(m) + ' минуту.'
  49. elif str(m)[-1] in ['2', '3', '4']:
  50. result = result + str(m) + ' минуты.'
  51. elif m in [str(i) for i in range(5, 19)] or str(m)[-1] == '0' or str(m)[-1] in ['5', '6', '7', '8', '9']:
  52. result = result + str(m) + ' минут.'
  53. return result
  54.  
  55.  
  56. def get_game():
  57. url = 'https://api.twitch.tv/kraken/streams/just4fun__'
  58. header = {'Client-ID': 'b4dw5l0j92y6zvahdmwsury87akc5gp'}
  59. try:
  60. a = requests.get(url, headers=header).json()['stream']['game']
  61. except:
  62. a = requests.get(game).text
  63. return a
  64.  
  65.  
  66. # Method for sending a message
  67. def send_message(message):
  68. s.send("PRIVMSG #just4fun__ :" + message + "\r\n")
  69. print(message)
  70.  
  71.  
  72. while True:
  73. readbuffer = readbuffer + s.recv(1024)
  74. temp = string.split(readbuffer, "\n")
  75. readbuffer = temp.pop()
  76.  
  77. for line in temp:
  78. # Проверка на сообщение PING от твича, проверка на афк
  79. if "PING" in line:
  80. logging.info(line)
  81. logging.info(line.split(" :")[1])
  82. logging.info(type(line))
  83. s.send("PONG %s\r\n" % line.split(" :")[1])
  84. else:
  85. # Разбиваем строку, для того что бы было проще с ней работать
  86. parts = string.split(line, ":")
  87.  
  88. if "QUIT" not in parts[1] and "JOIN" not in parts[1] and "PART" not in parts[1]:
  89. try:
  90. message = parts[2][:len(parts[2]) - 1]
  91. except:
  92. message = ""
  93. usernamesplit = string.split(parts[1], "!")
  94. username = usernamesplit[0]
  95. # Магия, не трогать
  96. if MODT:
  97. print username + ": " + message
  98. # Тут добавляем команды
  99. if message == "!игра" or message == "!game":
  100. sleep(0.3)
  101. send_message("Текущая игра : " + get_game())
  102. if message in ['!время', '!up', '!time', '!uptime']:
  103. r = requests.get(time) # Делаем запрос к API и получем продолжительность стрима
  104. if r.text == "just4fun__ isn't currently streaming":
  105. sleep(0.3)
  106. send_message("В данный момент стрим оффлайн OpieOP")
  107. else:
  108. if r.text.split(' ')[1] == 'minutes,' or r.text.split(' ')[1] == 'minute,':
  109. send_message(smart_time(None, r.text.split(' ')[0]))
  110. else:
  111. send_message(smart_time(r.text.split(' ')[0], r.text.split(' ')[2]))
  112. if message == '!mmr' or message == '!ммр':
  113. send_message('Текущий ММР ' + get_mmr() + ' поинтов')
  114. for l in parts:
  115. if "End of /NAMES list" in l:
  116. MODT = True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement