async def async_init(self, _app=None): kwargs = self._kwargs.copy() if kwargs.get('no_notifications', False): self.logger.info('No notifications') else: if not self.notifier: try: self.notifier = Notifier(loop=self.loop, **kwargs) await self.notifier.init_task except Exception: self.logger.exception('Cannot initialize Notifier') embed = self.make_embed() embed.colour = Colour.light_grey() embed.description = 'Started' await self.send_notification(embed=embed) if kwargs.pop('enable_cleaner', False): kwargs['check_path'] = self.src_path kwargs['notifier'] = self.notifier try: self.cleaner = Cleaner(loop=self.loop, **kwargs) await self.cleaner.init_task except Exception: self.logger.exception('Cannot initialize Cleaner')
async def stellar_wallet_overall(ctx, coin_stats: dict, utc_now): try: bridges = coin_stats['bridges'] except KeyError: bridges = 0 building_bridges = Embed( title=f':construction_site: Building Bridges :construction_site:', description= "Your Input on bridging the Stellar Network with Discord " "Users through Crypto Link.", colour=Colour.gold(), timestamp=utc_now) building_bridges.add_field( name=f':bridge_at_night: Created Bridges :bridge_at_night: ', value=f'```{int(bridges)}```') await ctx.author.send(embed=building_bridges) for k, v in coin_stats.items(): if k in ["xlm"]: coin_stats = Embed( title=f'{k.upper()} wallet statistics', description= f':bar_chart: ***__Statistical Data on Stellar Lumen Discord Wallet__*** ' f':bar_chart:', colour=Colour.light_grey(), timestamp=utc_now) coin_stats.add_field( name=f':inbox_tray: Total Deposits :inbox_tray:', value=f'Deposited ***{v["depositsCount"]}*** with total ' f'***{v["totalDeposited"]}*** ') coin_stats.add_field(name=f'\u200b', value='\u200b') coin_stats.add_field( name=f':outbox_tray: Total Withdrawals :outbox_tray: ', value= f'Withdrawn ***{v["withdrawalsCount"]}*** withdrawals with ' f'total ***{v["totalWithdrawn"]}*** ') coin_stats.add_field( name= f':family_man_woman_boy: Public Tx :family_man_woman_boy:', value=f':incoming_envelope: `{v["publicTxSendCount"]}`\n' f':money_with_wings: `{(int(v["publicSent"] * (10 ** 7))) / (10 ** 7):.7f}`\n' f':envelope_with_arrow: `{v["publicTxReceivedCount"]}`\n' f':money_mouth: `{(int(v["publicReceived"] * (10 ** 7))) / (10 ** 7):.7f}`' ) coin_stats.add_field( name=f':detective: Private Tx :detective:', value=f':incoming_envelope: `{v["privateTxSendCount"]}`\n' f':money_with_wings: `{(int(v["privateSent"] * (10 ** 7))) / (10 ** 7):.7f}`\n' f':envelope_with_arrow: `{v["privateTxReceivedCount"]}`\n' f':money_mouth: `{(int(v["privateReceived"] * (10 ** 7))) / (10 ** 7):.7f}` ' ) coin_stats.add_field( name= f':convenience_store: Merchant purchases :convenience_store: ', value=f':man_juggling:` `{v["roleTxCount"]}`\n' f':money_with_wings: `{(int(v["spentOnRoles"] * (10 ** 7))) / (10 ** 7): .7f}`\n', inline=False) await ctx.author.send(embed=coin_stats)
async def async_init(self, user_login, **kwargs): self.logger.debug("aiohttp session initialized.") self.aio_sess = ClientSession() if self.enc_path.startswith('/'): self.unix_sess = ClientSession(connector=UnixConnector( path=self.enc_path)) self.logger.debug("Unix session initialized.") self.user = await self.get_user_id(user_login) if not self.user: self.logger.critical('Cannot find user %s', user_login) await self.close() raise RuntimeError(f'Cannot find user {user_login}') if kwargs.get('no_notifications', False): self.logger.info('No notifications') else: if not self.notifier: kwargs['sess'] = self.aio_sess try: self.notifier = Notifier(loop=self.loop, **kwargs) await self.notifier.init_task except Exception: self.logger.exception('Cannot initialize Notifier') embed = self.make_embed() embed.colour = Colour.light_grey() embed.description = 'Started' await self.send_notification(embed=embed) self.check_en.set()
def as_embed(self) -> Embed: # Visually indicate match likelihood by changing the color based on similarity percentage # 85% is arbitrarily chosen and I might adjust this in future if I think it's too low or too # high color = Colour.green() if float( self.similarity) >= 85 else Colour.light_grey() # TODO: Set proper title from meta object embed = Embed(title='Found potential source.', colour=color) embed.set_thumbnail(url=self.thumbnail) embed.set_footer(text='Powered by SauceNAO.') # At least one entry should always exist # If it somehow turns out that's not the case, # I can always add a `if links else 'None found' later embed.add_field(name='Links', value=' | '.join(self.meta.links), inline=False) if self.meta.artist: embed.add_field(name='Artist', value=self.meta.artist, inline=True) embed.add_field(name='Similarity', value=f'{self.similarity}%', inline=True) return embed
def __init__(self, title="", description=""): super().__init__() self.timestamp = datetime.utcnow() self.colour = Colour.light_grey() self.url = "https://github.com/bundestagsBot/bundestagsBotAnalyzer" self.title = title self.description = description
class WebhookHandler(logging.Handler): _colours = { logging.DEBUG: Colour.light_grey(), logging.INFO: Colour.gold(), logging.WARNING: Colour.orange(), logging.ERROR: Colour.red(), logging.CRITICAL: Colour.dark_red() } def __init__(self, webhook_url, level=logging.NOTSET): super().__init__(level) self._webhook_logger = EmbedWebhookLogger(webhook_url) def emit(self, record: logging.LogRecord): self.format(record) message = f'{record.message}\n{record.exc_text or ""}' message = message[:1987] + '...' if len(message) > 1987 else message self._webhook_logger.log( Embed(colour=self._colours.get(record.levelno), title=record.name, description=f'```py\n{message}\n```', timestamp=datetime.datetime.fromtimestamp( record.created)).add_field( name=ZWSP, value=f'{record.filename}:{record.lineno}'))
async def get_event_embed(self, event, add_postamble=True): embed = discord.Embed(title='**{0.name}**'.format(event), color=Colour.light_grey(), description=event.description) participants = self.bot.db.get_participants_of_event(event.id) if len(participants) > 0: text = '' for participant in participants: user = await self.bot.fetch_user(participant) text += '{}\n'.format(user.mention) embed.add_field(name='Participants', value=text, inline=False) if add_postamble: embed.add_field( name='Join', value='Press {0} to join / leave this event!'.format( self.__join_emoji), inline=False) return embed
async def details(self, ctx, selling: str, buying: str): selling_asset = self.check_asset(asset_query=selling.upper()) if self.is_asset(asset_to_check=selling_asset): buying_asset = self.check_asset(asset_query=buying.upper()) if self.is_asset(asset_to_check=buying_asset): try: data = self.server.orderbook(selling=selling_asset, buying=buying_asset).call() base_asset_details = data["base"] counter_asset_details = data["counter"] base_details = '' if base_asset_details.get('asset_type') != 'native': base_details += f'{base_asset_details["asset_code"]}\n' \ f'```{base_asset_details["asset_issuer"]}```' else: base_details = 'XLM' counter_details = '' if counter_asset_details.get('asset_type') != 'native': counter_details += f'{counter_asset_details["asset_code"]}\n' \ f'```{counter_asset_details["asset_issuer"]}```' else: counter_details = 'XLM' ask_side = data["asks"] ask_str = str() for a in ask_side[:3]: ask_str += f'{a["amount"]} @ {a["price"]}\n' bid_side = data["bids"] bid_str = str() for b in bid_side[:3]: bid_str += f'{b["amount"]} @ {b["price"]}\n' orderbook_spread = round( float(ask_side[0]['price']) - float(bid_side[0]["price"]), 7) orderbook_embed = Embed( title=f' :book: Order book details :book:', colour=Colour.light_grey()) orderbook_embed.add_field( name=':gem: Base Asset Details :gem:', value=base_details, inline=False) orderbook_embed.add_field( name=':gem: Counter Asset Details :gem:', value=counter_details, inline=False) orderbook_embed.add_field( name=f':bar_chart: Order Book Spread :bar_chart: ', value=f'{orderbook_spread}', inline=False) orderbook_embed.add_field( name=':green_circle: Buy Offers :green_circle: ', value=f'{bid_str}') orderbook_embed.add_field( name=':red_circle: Sell Offers :red_circle: ', value=f'{ask_str}') await ctx.author.send(embed=orderbook_embed) except BadRequestError as e: extras = e.extras await horizon_error_msg(destination=ctx.message.author, error=extras["reason"]) else: multi_details = Embed( title= f':exclamation: Multiple Entries Found :exclamation: ', description= 'You have received this message because multiple entries have been found' f' for Buying asset parameter `{buying}`. Check the list bellow and' f' repeat the call however provide issuer address for Selling Asset', colour=Colour.red()) await ctx.author.send(embed=multi_details) for asset in buying_asset: multi_details.add_field( name= f':bank: Asset Issuer for {asset["asset_code"]} :bank:', value=f'```{asset["asset_issuer"]}```', inline=False) await ctx.author.send(embed=multi_details) else: multi_details = Embed( title=f':exclamation: Multiple Entries Found :exclamation: ', description= 'You have received this message because multiple entries have been found' f' for Selling asset parameter `{selling}`. Check the list bellow and' f' repeat the call however provide issuer address for Selling Asset', colour=Colour.red()) for asset in selling_asset: multi_details.add_field( name= f':bank: Asset Issuer for {asset["asset_code"]} :bank:', value=f'```{asset["asset_issuer"]}```', inline=False) await ctx.author.send(embed=multi_details)
class Leaderboard: colors = [Colour.gold(), Colour.light_grey(), Colour.dark_orange()] async def check_server_leaderboard(msg_obj, client): try: data = None with open("leaderboards/" + msg_obj.server.id + ".json") as file: data = json.load(file) for ping in range(len(data)): await client.send_message(msg_obj.channel, embed=Leaderboard.embed_constructor( data[ping], msg_obj.server, ping + 1, Leaderboard.colors[ping])) except Exception as e: print(e) await client.send_message( msg_obj.channel, error + "No leaderboard for this server!") #TODO: Maybe divide interval by ping_count to determine a ping's "value" and compare values for leaderboard spots # maybe only use the worth as a modifier to multiply ping_count by for a "value" def try_add_to_leaderboard(server_id, ping): # try to open an existing leaderboard and if possible add this ping try: leaderboard_path = "leaderboards/" + server_id + ".json" print("checking if ping should be added") data = None insert_index = -1 ping_json = ping.asJSON() with open(leaderboard_path) as file: data = json.load(file) ping_count = ping_json['ping_count'] for i in range(0, len(data)): if data[i]['ping_count'] < ping_count: insert_index = i print("ping marked for insertion") break if insert_index == -1 and len(data) < 3: insert_index = -2 # add the ping if insert_index was actually changed if insert_index > -1: with open(leaderboard_path, "w") as outfile: data.insert(insert_index, ping_json) if len(data) == 4: del data[3] json.dump(data, outfile) print("ping inserted") # if there's room for the ping, just add it elif insert_index == -2: with open(leaderboard_path, "w") as outfile: data.append(ping_json) print("ping appended") json.dump(data, outfile) # if there's no existing leaderboard for this server, make one and add this ping except Exception as e: print("error ", e) print("making leaderboard") with open("leaderboards/" + server_id + ".json", "w") as outfile: data = [] data.append(ping.asJSON()) json.dump(data, outfile) #TODO: Add discriminator to the JSON def embed_constructor(ping_json, server, num, color): embed = Embed() author = ping_json["author"] author_icon = ping_json["avatar"] embed.colour = color embed.set_author(name="#{0}".format(num)) embed.set_thumbnail(url=author_icon) embed.add_field(name="Author", value=author) embed.add_field(name="Message", value=ping_json["user_message"]) mentions = ping_json["mentions"] embed.add_field(name="Mentions", value=pingutils.get_formatted_name_list( server, mentions)) embed.add_field(name="Ping Count", value=ping_json["ping_count"]) interval = ping_json["interval"] embed.add_field(name="Interval", value="{0} seconds".format(interval)) return embed
from random import seed, randint from datetime import datetime seed(datetime.now()) colours = [ Colour.teal(), Colour.dark_teal(), Colour.green(), Colour.dark_green(), Colour.blue(), Colour.dark_blue(), Colour.purple(), Colour.dark_purple(), Colour.magenta(), Colour.dark_magenta(), Colour.gold(), Colour.dark_gold(), Colour.orange(), Colour.dark_orange(), Colour.red(), Colour.dark_red(), Colour.lighter_grey(), Colour.light_grey(), Colour.dark_grey(), Colour.darker_grey(), Colour.blurple(), Colour.greyple(), Colour.from_rgb(randint(0, 255), randint(0, 255), randint(0, 255)) ]
async def on_message(self, message, **kwargs): assert isinstance(message, Message) client = self.client prefix = kwargs.get("prefix") if not is_valid_command(message.content, valid_commands, prefix=prefix): return else: self.stats.add(MESSAGE) def startswith(*args): for a in args: if message.content.startswith(a): return True return False if startswith(prefix + "osu"): username = message.content[len(prefix + "osu "):] t_start = time.time() user = self.osu.get_user(username) if not user: await client.send_message(message.channel, "User does not exist.") return # About inverting: this inverts the number before and after the splitting def prepare(this): if not type(this) in (float, int): return None return invert_str(",".join( split_every(str(invert_num(this)), 3))) global_rank = prepare(user.world_rank) country_rank = prepare(user.country_rank) total_score = prepare(user.total_score) ranked_score = prepare(user.ranked_score) try: acc = str(round(float(user.accuracy), 2)) + " %" except TypeError: await client.send_message(message.channel, ":warning: Something went wrong...") return pp_amount = str(int(float(user.pp))) osu_level = int(float(user.level)) avatar_url = "http://a.ppy.sh/{}".format(user.id) # Color is determined by the level range if osu_level < 10: color = Colour.darker_grey() elif osu_level < 25: color = Colour.light_grey() elif osu_level < 40: color = Colour.dark_teal() elif osu_level < 50: color = Colour.teal() elif osu_level < 75: color = Colour.dark_purple() elif osu_level < 100: color = Colour.purple() # Only the masters get the gold ;) else: color = Colour.gold() desc = "**Level**: {}\n**Rank**: \n\t" \ "**Global**: #{}\n\t" \ "**Country** (**{}**): #{}\n" \ "Total PP: **{}**".format(osu_level, global_rank, user.country, country_rank, pp_amount) embed = Embed(url=user.profile_url, description=desc, colour=color) embed.set_author(name=user.name) embed.set_thumbnail(url=avatar_url) embed.add_field(name="Total score", value=total_score) embed.add_field(name="Ranked score", value=ranked_score) embed.add_field(name="Average accuracy", value=acc) delta = int((time.time() - t_start) * 1000) embed.set_footer(text="Search took {} ms".format(delta)) try: await client.send_message(message.channel, embed=embed) except errors.HTTPException: await client.send_message( message.channel, "Something went wrong " + StandardEmoji.THINKING)