async def queue(self, ctx): if ctx.invoked_subcommand is None: try: if queue[ctx.guild.id]['playing']: # If object exists in here, we show the queue embed = tls.Embed(ctx, description=f"Currently {(len(queue[ctx.guild.id]['q']) + 1)} items in queue") curr = queue[ctx.guild.id]['playing'][0] try: embed.add_field(name=f"**>**[**1**] {curr['title']}", value=f"**Artist:** {curr['author']}", inline=False) except Exception: embed.add_field(name=f"**>**[**1**] {curr['title']}", value=f"**Added by:** {curr['discord_mention']}", inline=False) pos = 2 for song in queue[ctx.guild.id]['q']: if pos <= 10: try: embed.add_field(name=f"[**{pos}**] {song['title']}", value=f"**Artist:** {song['author']}", inline=False) except Exception: embed.add_field(name=f"[**{pos}**] {song['title']}", value=f"**Added by:** {song['discord_mention']}", inline=False) pos += 1 if pos > 10: dif = (len(queue[ctx.guild.id]['q']) + 1) - 10 embed.set_footer(text=f'Plus {dif} other tracks.', icon_url=self.bot.user.avatar_url) await ctx.send(embed=embed) else: await ctx.send('The queue is currently empty.') except Exception as err: random.seed(traceback.format_exc()) number = random.randint(10000, 99999) await ctx.send(f'Oops! Something went wrong! `(#{number})`') log.exception(f'Code #{number}', exc_info=err)
async def on_error(self, event, *args, **kwargs): # GENERAL ERROR HANDLER exc = sys.exc_info() random.seed(traceback.format_exc()) number = random.randint(10000, 99999) log.error( f'> {trace.red}{event.capitalize()}{trace.alert} encountered {trace.red}' f'{exc[0].__name__}{trace.alert} with message {trace.red}{exc[1]}') log.exception(f'Code #{number}', exc_info=exc)
async def hackban(self, ctx, snowflake, *, reason='User was hackbanned'): try: await ctx.guild.ban(tls.Snowflake(snowflake), delete_message_days=0, reason=reason) await ctx.send(f'Hackbanned <@!{snowflake}> with reason `{reason}`.') except discord.Forbidden as err: await funcs.respond(ctx, err) except discord.HTTPException as err: await funcs.respond(ctx, err) except Exception as err: log.exception(err)
def post(self, json): try: with httpx.Client() as client: client.post(url=self.url, json=dict(json)) except httpx._exceptions.WriteError: log.debug(f'{self.url} Write Error') except httpx._exceptions.ConnectTimeout: log.debug(f'{self.url} Connect Timeout') except httpx._exceptions.ReadTimeout: log.debug(f'{self.url} Read Timeout') except Exception as exc: log.exception(exc)
async def async_get(self): try: async with httpx.AsyncClient() as client: r = await client.get(url=self.url) return r except httpx._exceptions.ConnectTimeout: log.debug(f'{self.url} Connect Timeout') except httpx._exceptions.ReadTimeout: log.debug(f'{self.url} Read Timeout') except Exception as exc: log.exception(exc) return None
def name_to_id(name): url = "https://api.twitch.tv/kraken/users?login=" + name try: r = requests.get(url=url, headers=header) r_json = r.json() if r_json['users']: return r_json['users'][0]['_id'] except requests._exceptions.ConnectTimeout: log.debug('Connect Timeout') except requests._exceptions.ReadTimeout: log.debug('Read Timeout') except Exception as exc: log.exception(exc) return None
async def is_online(): host = json.json.orm['api'] try: async with requests.AsyncClient() as client: r = await client.get( url=f"http://{host['host']}:{host['port']}/ctv/online") return r.json() except requests._exceptions.ConnectTimeout: log.debug('Connect Timeout') except requests._exceptions.ReadTimeout: log.debug('Read Timeout') except Exception as exc: log.exception(exc) return None
async def name_to_id(_name): if _name is not None: host = json.json.orm['api'] try: async with requests.AsyncClient() as client: r = await client.get( url=f"http://{host['host']}:{host['port']}/ctv/id/{_name}") return r.json() except requests._exceptions.ConnectTimeout: log.debug('Connect Timeout') except requests._exceptions.ReadTimeout: log.debug('Read Timeout') except Exception as exc: log.exception(exc) return False
async def play(self, ctx, url=None): if await Player.can_connect(ctx, False): await Player.join(ctx.message.author) if Player.is_connected(ctx): try: if url is not None: async with ctx.typing(): info, data = await Player.info(url, loop=self.bot.loop, ctx=ctx) # log.debug(info) if info is not None: if len(info) > 1: playlist = data['title'] else: playlist = None embed = tls.Embed(ctx) for item in info: # Append tracks to queue. Eventually it'll just be pfp and data. try: item.update({'discord_mention': ctx.author.mention}) extractor = Player.Extractor.fetch(data) queue[ctx.guild.id]['q'].append(item) # log.debug(item) except KeyError as err: log.error(err) # break if playlist is None: item = await Player.process_picture(item, extractor[0]) try: # log.debug(queue[ctx.guild.id]['q'][-1]['extractor']) embed.set_author(name=item['uploader'], url=item['uploader_url'], icon_url=queue[ctx.guild.id]['q'][-1]['pfp']) except KeyError as err: embed.set_author(name=item['uploader'], icon_url=queue[ctx.guild.id]['q'][-1]['pfp']) embed.add_field(name=f"{item['title']}", value=f"has been added to the queue.", inline=False) else: embed.add_field(name=f"{len(info)} tracks added from", value=f" playlist **{playlist}**", inline=False) await ctx.send(embed=embed) else: # If no URL specified, try to resume Player.resume(ctx) await Player.loop(self, ctx) except Exception as err: random.seed(traceback.format_exc()) number = random.randint(10000, 99999) await ctx.send(f'Oops! Something went wrong! `(#{number})`') log.exception(f'Code #{number}', exc_info=err)
def is_online(): _id = [] for x in data.base['ctv_users']: _id.append(x['userid']) _id = ','.join([str(elem) for elem in _id]) url = "https://api.twitch.tv/kraken/streams/?limit=100&channel=" + _id try: r = requests.get(url=url, headers=header) r_json = r.json() if r_json['streams']: return r_json except requests._exceptions.ConnectTimeout: log.debug('Connect Timeout') except requests._exceptions.ReadTimeout: log.debug('Read Timeout') except Exception as exc: log.exception(exc) return None
async def reset(self): try: for x in self.bot.guilds: gid = data.base['ctv_guilds'].find_one(guild=x.id) if gid: for m in x.members: roles = [ tls.Snowflake(r) for r in ast.literal_eval(gid['give_roles']) ] if [y for y in m.roles for x in roles if y.id == x.id]: await m.remove_roles(*roles) except Exception as err: import traceback import random random.seed(traceback.format_exc()) number = random.randint(10000, 99999) log.exception(f'Code #{number}', exc_info=err)
async def profile_picture(cls, _id, extractor='youtube'): from core.bot.tools import crypt from data.data import data from core import json # print(_id) # print(extractor) # log.debug(extractor) info = data.base['cache'].find_one(id=_id, platform=extractor) # print(info) try: if info is None: if extractor == 'youtube': # 2 points base = f"https://www.googleapis.com/youtube/v3/channels?part=snippet&id={_id}&key={crypt(json.json.orm['secure']['extractors'][extractor])}" info = requests.get(base, timeout=5).json()['items'][0]['snippet']['thumbnails']['high']['url'] # log.debug(info) data.base['cache'].upsert(dict(platform=extractor, id=_id, data=info), ['id']) elif extractor == 'twitch': # Kraken - Depreciated. version = 'kraken' if version == 'kraken': # Kraken implementation url = "https://api.twitch.tv/kraken/users?login=" + _id header = { 'Client-ID': crypt(json.json.orm['secure']['extractors']['twitch']), 'Accept': 'application/vnd.twitchtv.v5+json' } async with requests.AsyncClient() as client: r = await client.get(url=url, headers=header, timeout=5) _data = r.json() if _data['users']: info = _data['users'][0]['logo'] data.base['cache'].upsert(dict(platform=extractor, id=_id, data=info), ['id']) elif version == 'helix': # No implementation return discord.Embed.Empty else: return discord.Embed.Empty else: info = info['data'] except Exception as err: random.seed(traceback.format_exc()) number = random.randint(10000, 99999) log.exception(f'Code #{number}', exc_info=err) info = assets.Discord.error.value # log.debug(info) return info
async def find_online_users(self): live = [] for guild in self.bot.guilds: for member in guild.members: if not member.bot: for x in member.activities: if x.type == discord.ActivityType.streaming: new = {'user': member.id, 'twitch': x.twitch_name} if new not in live: live.append(new) for x in live: try: _id = data.base['ctv_users'].find_one(discorduid=x['user']) if not _id: _id = await name_to_id(x['twitch']) if _id is not False: data.base['ctv_users'].upsert( dict(userid=_id, discorduid=x['user']), ['discorduid']) except Exception as exc: log.exception(exc)
async def live_loop(self): await reset(self) log.debug('CTV Loop Started') # if test: # log.debug('CTV Loop Started') from cogs.core.system import lockdown global looping while not lockdown and do_loop: if test_debug: log.debug(f'{self.bot.user.name} is looping') from cogs.core.system import lockdown if lockdown: break looping = True try: info = await is_online() if info: # print(info) global past past = now.copy() now.clear() for x in info['streams']: # Add userID to memory now.append(x['channel']['_id']) # if past: # If has past history data, continue if True: # print(info) for x in now: # Compare. If not in memory previously, it's new if x not in past: await on_live(self, x) for x in past: # Compare. If not in memory anymore, went offline if x not in now: await on_offline(self, x) except Exception as err: log.exception(err) await asyncio.sleep(10) looping = False log.error('CTV Loop Stopped')
import os from core.logger import log while True: try: os.system('python berry.tls.py') except Exception as exc: log.exception(exc)
def run(self): try: app.run(host=json.orm['api']['host'], port=json.orm['api']['port']) except Exception as exc: log.exception(exc)