Пример #1
0
def highlight(lrrbot, conn, event, respond_to, description):
    """
	Command: !highlight DESCRIPTION
	Section: misc

	For use when something particularly awesome happens onstream, adds an entry on the Highlight Reel spreadsheet: https://docs.google.com/spreadsheets/d/1yrf6d7dPyTiWksFkhISqEc-JR71dxZMkUoYrX4BR40Y
	"""

    stream_info = twitch.get_info()
    if not stream_info["live"]:
        conn.privmsg(respond_to, "Not currently streaming.")
        return
    now = datetime.datetime.now(datetime.timezone.utc)

    for video in (yield from twitch.get_videos(broadcasts=True)):
        uptime = now - dateutil.parser.parse(video["recorded_at"])
        if video["status"] == "recording":
            break
    else:
        store_highlight(stream_info["status"], description, now, irc.client.NickMask(event.source).nick)
        conn.privmsg(respond_to, "Highlight added.")
        return

    yield from gdata.add_rows_to_spreadsheet(
        SPREADSHEET,
        [format_row(stream_info["status"], description, video["url"], uptime, irc.client.NickMask(event.source).nick)],
    )

    conn.privmsg(respond_to, "Highlight added.")
Пример #2
0
def viewers(lrrbot, conn, event, respond_to):
	"""
	Command: !viewers
	Section: info

	Post the number of viewers currently watching the stream
	"""
	stream_info = twitch.get_info()
	if stream_info:
		viewers = stream_info.get("viewers")
	else:
		viewers = None
	
	# Since we're using TWITCHCLIENT 3, we don't get join/part messages, so we can't just use
	# len(lrrbot.channels["#loadingreadyrun"].userdict)
	# as that dict won't be populated. Need to call this api instead.
	chatters = utils.http_request("http://tmi.twitch.tv/group/user/%s/chatters" % config["channel"])
	chatters = json.loads(chatters).get("chatter_count")

	if viewers is not None:
		viewers = "%d %s viewing the stream." % (viewers, "user" if viewers == 1 else "users")
	else:
		viewers = "Stream is not live."
	if chatters is not None:
		chatters = "%d %s in the chat." % (chatters, "user" if chatters == 1 else "users")
	else:
		chatters = "No-one in the chat."
	conn.privmsg(respond_to, "%s %s" % (viewers, chatters))
Пример #3
0
def viewers(lrrbot, conn, event, respond_to):
	"""
	Command: !viewers
	Section: info

	Post the number of viewers currently watching the stream
	"""
	stream_info = twitch.get_info()
	if stream_info:
		viewers = stream_info.get("viewers")
	else:
		viewers = None
	
	# Since we're using TWITCHCLIENT 3, we don't get join/part messages, so we can't just use
	# len(lrrbot.channels["#loadingreadyrun"].userdict)
	# as that dict won't be populated. Need to call this api instead.
	chatters = utils.http_request("http://tmi.twitch.tv/group/user/%s/chatters" % config["channel"])
	chatters = json.loads(chatters).get("chatter_count")

	if viewers is not None:
		viewers = "%d %s viewing the stream." % (viewers, "user" if viewers == 1 else "users")
	else:
		viewers = "Stream is not live."
	if chatters is not None:
		chatters = "%d %s in the chat." % (chatters, "user" if chatters == 1 else "users")
	else:
		chatters = "No-one in the chat."
	conn.privmsg(respond_to, "%s %s" % (viewers, chatters))
Пример #4
0
def uptime_msg(stream_info=None):
	if stream_info is None:
		stream_info = twitch.get_info()
	if stream_info and stream_info.get("stream_created_at"):
		start = dateutil.parser.parse(stream_info["stream_created_at"])
		now = datetime.datetime.now(datetime.timezone.utc)
		return "The stream has been live for %s." % utils.nice_duration(now-start, 0)
	elif stream_info and stream_info.get('live'):
		return "Twitch won't tell me when the stream went live."
	else:
		return "The stream is not live."
Пример #5
0
def main():
	if twitch.get_info()["live"]:
		print("Stream is live.")
		return
	
	highlights = send_bot_command("get_data", {"key": "staged_highlights"})
	if argv.test:
		print("Staged highlights: %r" % highlights)
	if highlights is None:
		highlights = []
	highlights = list(filter(lambda e: e is not None, map(twitch_lookup, highlights)))

	if highlights == []:
		return

	token = get_oauth_token(["https://spreadsheets.google.com/feeds"])
	headers = {"Authorization": "%(token_type)s %(access_token)s" % token}
	url = "https://spreadsheets.google.com/feeds/worksheets/%s/private/full" % SPREADSHEET
	tree = xml.dom.minidom.parseString(utils.http_request(url, headers=headers))
	worksheet = next(iter(tree.getElementsByTagName("entry")))
	list_feed = find_schema(worksheet, "http://schemas.google.com/spreadsheets/2006#listfeed")
	if list_feed is None:
		print("List feed missing.")
		return
	list_feed = xml.dom.minidom.parseString(utils.http_request(list_feed, headers=headers))
	post_url = find_schema(list_feed, "http://schemas.google.com/g/2005#post")
	if post_url is None:
		print("POST URL missing.")
		return

	for highlight in highlights:
		doc = xml.dom.minidom.getDOMImplementation().createDocument(None, "entry", None)
		root = doc.documentElement
		root.setAttribute("xmlns", "http://www.w3.org/2005/Atom")
		root.setAttribute("xmlns:gsx", "http://schemas.google.com/spreadsheets/2006/extended")

		root.appendChild(new_field(doc, "SHOW", highlight["title"]))
		root.appendChild(new_field(doc, "QUOTE or MOMENT", highlight["description"]))
		root.appendChild(new_field(doc, "YOUTUBE VIDEO LINK", highlight["url"]))
		root.appendChild(new_field(doc, "ROUGH TIME THEREIN", "before "+ utils.nice_duration(highlight["time"], 0)))
		root.appendChild(new_field(doc, "NOTES", "From chat user '%s'." % highlight["user"]))

		if argv.test:
			print("Command: %s" % doc.toxml())
		else:
			headers["Content-Type"] = "application/atom+xml"
			utils.http_request(post_url, headers=headers, data=doc.toxml(), method="POST")

	if not argv.test:
		send_bot_command("set_data", {"key": "staged_highlights", "value": []})
Пример #6
0
    def on_subscriber(self,
                      conn,
                      channel,
                      user,
                      eventtime,
                      logo=None,
                      monthcount=None):
        notifyparams = {
            'apipass': config['apipass'],
            'message': "%s just subscribed!" % user,
            'eventtime': eventtime,
            'subuser': user,
            'channel': channel,
        }

        if logo is None:
            try:
                channel_info = twitch.get_info(user)
            except:
                pass
            else:
                if channel_info.get('logo'):
                    notifyparams['avatar'] = channel_info['logo']
        else:
            notifyparams['avatar'] = logo

        if monthcount is not None:
            notifyparams['monthcount'] = monthcount

        # have to get this in a roundabout way as datetime.date.today doesn't take a timezone argument
        today = datetime.datetime.now(config['timezone']).date().toordinal()
        if today != storage.data.get("storm", {}).get("date"):
            storage.data["storm"] = {
                "date": today,
                "count": 0,
            }
        storage.data["storm"]["count"] += 1
        self.lastsubs.append(user.lower())
        self.lastsubs = self.lastsubs[-10:]
        storage.save()
        conn.privmsg(
            channel,
            "lrrSPOT Thanks for subscribing, %s! (Today's storm count: %d)" %
            (notifyparams['subuser'], storage.data["storm"]["count"]))
        utils.api_request('notifications/newmessage', notifyparams, 'POST')

        self.subs.add(user.lower())
        storage.data['subs'] = list(self.subs)
        storage.save()
Пример #7
0
def main():
	if twitch.get_info()["live"]:
		print("Stream is live.")
		return

	highlights = get_staged_highlights()
	videos = []
	for highlight in highlights:
		highlight["video"] = yield from lookup_video(highlight, videos)

	yield from gdata.add_rows_to_spreadsheet(SPREADSHEET, [
		format_row(highlight["title"], highlight["description"], highlight["video"]["url"],
			 highlight["time"] - highlight["video"]["recorded_at"], highlight["nick"])
		for highlight in highlights
	])
	delete_staged_highlights(highlights)
Пример #8
0
def uptime(lrrbot, conn, event, respond_to):
	"""
	Command: !uptime
	Section: info

	Post the duration the stream has been live.
	"""

	stream_info = twitch.get_info()
	if stream_info and stream_info.get("stream_created_at"):
		start = dateutil.parser.parse(stream_info["stream_created_at"])
		now = datetime.datetime.now(datetime.timezone.utc)
		conn.privmsg(respond_to, "The stream has been live for %s" % utils.nice_duration(now-start, 0))
	elif stream_info:
		conn.privmsg(respond_to, "Twitch won't tell me when the stream went live.")
	else:
		conn.privmsg(respond_to, "The stream is not live.")
Пример #9
0
def highlight(lrrbot, conn, event, respond_to, description):
	"""
	Command: !highlight DESCRIPTION
	Section: misc

	For use when something particularly awesome happens onstream, adds an entry on the Highlight Reel spreadsheet: https://docs.google.com/spreadsheets/d/1yrf6d7dPyTiWksFkhISqEc-JR71dxZMkUoYrX4BR40Y

	Note that the highlights won't appear on the spreadsheet immediately, as the link won't be available until the stream finishes and the video is in the archive. It should appear within a day.
	"""
	if not twitch.get_info()["live"]:
		conn.privmsg(respond_to, "Not currently streaming.")
		return
	storage.data.setdefault("staged_highlights", [])
	storage.data["staged_highlights"] += [{
		"time": time.time(),
		"user": irc.client.NickMask(event.source).nick,
		"description": description,
	}]
	storage.save()
	conn.privmsg(respond_to, "Highlight added.")
Пример #10
0
def get_status_msg(lrrbot):
	messages = []
	stream_info = twitch.get_info()
	if stream_info and stream_info.get('live'):
		game = lrrbot.get_current_game()
		game = game and game.get("display", game["name"])
		show = lrrbot.show_override or lrrbot.show
		show = show and storage.data.get("shows", {}).get(show, {}).get("name", show)
		if game and show:
			messages.append("Currently playing %s on %s." % (game, show))
		elif game:
			messages.append("Currently playing %s." % game)
		elif show:
			messages.append("Currently showing %s." % show)
		messages.append(uptime_msg(stream_info))
	else:
		messages.append(googlecalendar.get_next_event_text(googlecalendar.CALENDAR_LRL))
	if 'advice' in storage.data['responses']:
		messages.append(random.choice(storage.data['responses']['advice']['response']))
	return ' '.join(messages)
Пример #11
0
    def on_subscriber(self, conn, channel, user, eventtime, logo=None, monthcount=None):
        notifyparams = {
            "apipass": config["apipass"],
            "message": "%s just subscribed!" % user,
            "eventtime": eventtime,
            "subuser": user,
            "channel": channel,
        }

        if logo is None:
            try:
                channel_info = twitch.get_info(user)
            except:
                pass
            else:
                if channel_info.get("logo"):
                    notifyparams["avatar"] = channel_info["logo"]
        else:
            notifyparams["avatar"] = logo

        if monthcount is not None:
            notifyparams["monthcount"] = monthcount

            # have to get this in a roundabout way as datetime.date.today doesn't take a timezone argument
        today = datetime.datetime.now(config["timezone"]).date().toordinal()
        if today != storage.data.get("storm", {}).get("date"):
            storage.data["storm"] = {"date": today, "count": 0}
        storage.data["storm"]["count"] += 1
        self.lastsubs.append(user.lower())
        self.lastsubs = self.lastsubs[-10:]
        storage.save()
        conn.privmsg(
            channel,
            "lrrSPOT Thanks for subscribing, %s! (Today's storm count: %d)"
            % (notifyparams["subuser"], storage.data["storm"]["count"]),
        )
        utils.api_request("notifications/newmessage", notifyparams, "POST")

        self.subs.add(user.lower())
        storage.data["subs"] = list(self.subs)
        storage.save()
Пример #12
0
	def on_subscriber(self, conn, channel, user, eventtime, logo=None, monthcount=None):
		notifyparams = {
			'apipass': config['apipass'],
			'message': "%s just subscribed!" % user,
			'eventtime': eventtime,
			'subuser': user,
			'channel': channel,
		}

		if logo is None:
			try:
				channel_info = twitch.get_info(user)
			except:
				pass
			else:
				if channel_info.get('logo'):
					notifyparams['avatar'] = channel_info['logo']
		else:
			notifyparams['avatar'] = logo

		if monthcount is not None:
			notifyparams['monthcount'] = monthcount

		# have to get this in a roundabout way as datetime.date.today doesn't take a timezone argument
		today = datetime.datetime.now(config['timezone']).date().toordinal()
		if today != storage.data.get("storm",{}).get("date"):
			storage.data["storm"] = {
				"date": today,
				"count": 0,
			}
		storage.data["storm"]["count"] += 1
		self.lastsubs.append(user.lower())
		self.lastsubs = self.lastsubs[-10:]
		storage.save()
		conn.privmsg(channel, "lrrSPOT Thanks for subscribing, %s! (Today's storm count: %d)" % (notifyparams['subuser'], storage.data["storm"]["count"]))
		utils.api_request('notifications/newmessage', notifyparams, 'POST')

		self.subs.add(user.lower())
		storage.data['subs'] = list(self.subs)
		storage.save()
Пример #13
0
def highlight(lrrbot, conn, event, respond_to, description):
    """
	Command: !highlight DESCRIPTION
	Section: misc

	For use when something particularly awesome happens onstream, adds an entry on the Highlight Reel spreadsheet: https://docs.google.com/spreadsheets/d/1yrf6d7dPyTiWksFkhISqEc-JR71dxZMkUoYrX4BR40Y

	Note that the highlights won't appear on the spreadsheet immediately, as the link won't be available until the stream finishes and the video is in the archive. It should appear within a day.
	"""
    if not twitch.get_info()["live"]:
        conn.privmsg(respond_to, "Not currently streaming.")
        return
    storage.data.setdefault("staged_highlights", [])
    storage.data["staged_highlights"] += [{
        "time":
        time.time(),
        "user":
        irc.client.NickMask(event.source).nick,
        "description":
        description,
    }]
    storage.save()
    conn.privmsg(respond_to, "Highlight added.")
Пример #14
0
def main():
    if twitch.get_info()["live"]:
        print("Stream is live.")
        return

    highlights = send_bot_command("get_data", {"key": "staged_highlights"})
    if argv.test:
        print("Staged highlights: %r" % highlights)
    if highlights is None:
        highlights = []
    highlights = list(
        filter(lambda e: e is not None, map(twitch_lookup, highlights)))

    if highlights == []:
        return

    token = get_oauth_token(["https://spreadsheets.google.com/feeds"])
    headers = {"Authorization": "%(token_type)s %(access_token)s" % token}
    url = "https://spreadsheets.google.com/feeds/worksheets/%s/private/full" % SPREADSHEET
    tree = xml.dom.minidom.parseString(utils.http_request(url,
                                                          headers=headers))
    worksheet = next(iter(tree.getElementsByTagName("entry")))
    list_feed = find_schema(
        worksheet, "http://schemas.google.com/spreadsheets/2006#listfeed")
    if list_feed is None:
        print("List feed missing.")
        return
    list_feed = xml.dom.minidom.parseString(
        utils.http_request(list_feed, headers=headers))
    post_url = find_schema(list_feed, "http://schemas.google.com/g/2005#post")
    if post_url is None:
        print("POST URL missing.")
        return

    for highlight in highlights:
        doc = xml.dom.minidom.getDOMImplementation().createDocument(
            None, "entry", None)
        root = doc.documentElement
        root.setAttribute("xmlns", "http://www.w3.org/2005/Atom")
        root.setAttribute(
            "xmlns:gsx",
            "http://schemas.google.com/spreadsheets/2006/extended")

        root.appendChild(new_field(doc, "SHOW", highlight["title"]))
        root.appendChild(
            new_field(doc, "QUOTE or MOMENT", highlight["description"]))
        root.appendChild(new_field(doc, "YOUTUBE VIDEO LINK",
                                   highlight["url"]))
        root.appendChild(
            new_field(doc, "ROUGH TIME THEREIN",
                      "before " + utils.nice_duration(highlight["time"], 0)))
        root.appendChild(
            new_field(doc, "NOTES",
                      "From chat user '%s'." % highlight["user"]))

        if argv.test:
            print("Command: %s" % doc.toxml())
        else:
            headers["Content-Type"] = "application/atom+xml"
            utils.http_request(post_url,
                               headers=headers,
                               data=doc.toxml(),
                               method="POST")

    if not argv.test:
        send_bot_command("set_data", {"key": "staged_highlights", "value": []})