1
0
Fork 0
mirror of synced 2024-05-19 20:12:30 +12:00

Setup of Twitch specific alerts

This commit is contained in:
Phxntxm 2017-06-17 18:04:36 -05:00
parent b9efeefa89
commit b769c64e01

View file

@ -23,7 +23,30 @@ class Twitch:
self.key = utils.twitch_key
self.params = {'client_id': self.key}
async def channel_online(self, twitch_url: str):
def _form_embed(self, data):
# I want to make the least API calls possible, however there's a few things to note here:
# 1) When requesting /streams and a channel is offline, the channel data is not provided
# 2) When requesting /streams and a channel is online, the channel data is provided
# 3) When requesting /channels, no data is provided about the channel being on or offline
# 4) The data provide in /streams matches /channels when they are online
# Due to this...the data "source" will be different based on if they are on or offline
# Instead of making an API call to see if they're online, then an API call to get the data
# The idea here is to separate creating the embed, and the getting of data
# With this method, I can get the data if they are online,then return the embed if applicable
embed = discord.Embed(title=data['display_name'], url=data['url'])
if data['logo']:
embed.set_thumbnail(url=data['logo'])
embed.add_field(name='Title', value=data['status'])
embed.add_field(name='Followers', value=data['followers'])
embed.add_field(name='Views', value=data['views'])
if data['game']:
embed.add_field(name='Game', value=data['game'])
embed.add_field(name='Language', value=data['broadcaster_language'])
return embed
async def online_embed(self, twitch_url: str):
# Check a specific channel's data, and get the response in text format
channel = re.search("(?<=twitch.tv/)(.*)", twitch_url).group(1)
url = "https://api.twitch.tv/kraken/streams/{}".format(channel)
@ -35,56 +58,73 @@ class Twitch:
# Sometimes it returns something that cannot be decoded with JSON (which means we'll get None back)
# In either error case, just assume they're offline, the next check will most likely work
try:
return response['stream'] is not None
data = response['stream']['channel']
embed = self._form_embed(data)
return embed
except (KeyError, TypeError):
return False
return None
async def offline_embed(self, twitch_url: str):
# Check a specific channel's data, and get the response in text format
channel = re.search("(?<=twitch.tv/)(.*)", twitch_url).group(1)
url = "https://api.twitch.tv/kraken/channels/{}".format(channel)
data = await utils.request(url, payload=self.params)
return self._form_embed(data)
async def check_channels(self):
await self.bot.wait_until_ready()
# Loop through as long as the bot is connected
# This is a loop that runs every 30 seconds, checking if anyone has gone online
try:
while not self.bot.is_closed():
twitch = self.bot.db.load('twitch', table_filter={'notifications_on': 1})
twitch = await self.bot.db.actual_load('twitch', table_filter={'notifications_on': 1})
for data in twitch:
m_id = int(data['member_id'])
url = data['twitch_url']
# Check if they are online
online = await self.channel_online(url)
# If they're currently online, but saved as not then we'll send our notification
if online and data['live'] == 0:
for s_id in data['servers']:
server = self.bot.get_guild(int(s_id))
if server is None:
continue
member = server.get_member(m_id)
if member is None:
continue
channel_id = self.bot.db.load('server_settings', key=s_id,
pluck='notifications_channel') or int(s_id)
channel = server.get_channel(channel_id)
if channel is None:
continue
try:
await channel.send("{} has just gone live! View their stream at <{}>".format(member.display_name, data['twitch_url']))
except discord.Forbidden:
pass
self.bot.db.save('twitch', {'live': 1, 'member_id': str(m_id)})
elif not online and data['live'] == 1:
for s_id in data['servers']:
server = self.bot.get_guild(int(s_id))
if server is None:
continue
member = server.get_member(m_id)
if member is None:
continue
channel_id = self.bot.db.load('server_settings', key=s_id,
pluck='notifications_channel') or int(s_id)
channel = server.get_channel(channel_id)
try:
await channel.send("{} has just gone offline! View their stream next time at <{}>".format(member.display_name, data['twitch_url']))
except discord.Forbidden:
pass
self.bot.db.save('twitch', {'live': 0, 'member_id': str(m_id)})
# Check if they are online by trying to get an displayed embed for this user
embed = await self.online_embed(url)
# If they're currently online, but saved as not then we'll let servers know they are now online
if embed and data['live'] == 0:
msg = "{member.display_name} has just gone live!"
self.bot.db.save('twitch', {'live': 1, 'member_id': str(m_id)})
# Otherwise our notification will say they've gone offline
elif not embed and data['live'] == 1:
msg = "{member.display_name} has just gone offline!"
embed = await self.offline_embed(url)
self.bot.db.save('twitch', {'live': 0, 'member_id': str(m_id)})
else:
continue
# Loop through each server that they are set to notify
for s_id in data['servers']:
server = self.bot.get_guild(int(s_id))
# If we can't find it, ignore this one
if server is None:
continue
member = server.get_member(m_id)
# If we can't find them in this server, also ignore
if member is None:
continue
# Get the notifications settings, get the twitch setting
notifications = self.bot.db.load('server_settings', key=s_id, pluck='notifications') or {}
# Set our default to either the one set, or the default channel of the server
default_channel_id = notifications.get('default') or s_id
# If it is has been overriden by twitch notifications setting, use this
channel_id = notifications.get('twitch') or default_channel_id
# Now get the channel
channel = server.get_channel(int(channel_id))
# Unfortunately we need one more check, to ensure a channel hasn't been chosen, then deleted
if channel is None:
channel = server.default_channel
# Then just send our message
try:
await channel.send(msg.format(member=member), embed=embed)
except (discord.Forbidden, discord.HTTPException):
pass
await asyncio.sleep(30)
except Exception as e:
tb = traceback.format_exc()
@ -109,25 +149,7 @@ class Twitch:
await ctx.send("{} has not saved their twitch URL yet!".format(member.name))
return
user = re.search("(?<=twitch.tv/)(.*)", url).group(1)
twitch_url = "https://api.twitch.tv/kraken/channels/{}".format(user)
payload = {'client_id': self.key}
data = await utils.request(twitch_url, payload=payload)
if data is None:
await ctx.send("Sorry but I couldn't connect to twitch right now!")
return
embed = discord.Embed(title=data['display_name'], url=url)
if data['logo']:
embed.set_thumbnail(url=data['logo'])
embed.add_field(name='Title', value=data['status'])
embed.add_field(name='Followers', value=data['followers'])
embed.add_field(name='Views', value=data['views'])
if data['game']:
embed.add_field(name='Game', value=data['game'])
embed.add_field(name='Language', value=data['broadcaster_language'])
embed = await self.offline_embed(url)
await ctx.send(embed=embed)
@twitch.command(name='add')
@ -198,6 +220,24 @@ class Twitch:
self.bot.db.save('twitch', entry)
await ctx.send("I am no longer saving your twitch URL {}".format(ctx.message.author.mention))
@twitch.command(name='alerts', aliases=['notifications'])
@commands.guild_only()
@utils.custom_perms(manage_guild=True)
async def twitch_alerts_channel(self, ctx, channel: discord.TextChannel):
"""Sets the notifications channel for twitch notifications
EXAMPLE: !twitch alerts #twitch
RESULT: Twitch notifications will go to this channel
"""
entry = {
'server_id': str(ctx.message.guild.id),
'notifications': {
'twitch': str(channel.id)
}
}
self.bot.db.save('server_settings', entry)
await ctx.send("All Twitch notifications will now go to {}".format(channel.mention))
@twitch.group(invoke_without_command=True)
@commands.guild_only()
@utils.custom_perms(send_messages=True)