async def on_commons_division(self, division: CommonsDivision, bill: Bill): channel = self._guild.get_channel( int(self.config.get_channel_id("commons_divisions")) ) if channel is None: return division_file = await self.generate_division_image(self.parliament, division) embed = Embed( color=discord.Colour.from_rgb(84, 174, 51), timestamp=datetime.now() ) did_pass = division.get_aye_count() > division.get_no_count() embed.title = f"**{division.get_division_title()}**" next_line = "\n" description = ( f"**Division Result:** {'Passed' if did_pass else 'Not passed'} by a division of" f" {division.get_aye_count() if did_pass else division.get_no_count()} {'Ayes' if did_pass else 'Noes'}" f" to {division.get_no_count() if did_pass else division.get_aye_count()} " f"{'Noes' if did_pass else 'Ayes'}{next_line}**Division Date:** " f"{division.get_division_date().strftime('%Y-%m-%d %H:%M:%S')}" ) if bill is not None: description += ( f"{next_line}**Bill Summary [(Link)](https://bills.parliament.uk/" f"bills/{bill.get_bill_id()})**: {bill.get_long_title()}" ) embed.description = description embed.set_image(url="attachment://divisionimage.png") self.tracker_status["commonsdivisions"]["confirmed"] = True await channel.send( file=division_file, embed=embed, )
async def send_message(self, message): try: if int(message.conversation.id) > 0: chat = self.client.get_user(message.conversation.id) else: chat = self.client.get_channel(positive(message.conversation.id)) await chat.trigger_typing() if message.type == 'text': content = self.add_discord_mentions(chat, message.content) if message.extra: if 'format' in message.extra and message.extra['format'] == 'HTML': content = html_to_discord_markdown(content) if 'preview' in message.extra and not message.extra['preview']: content = re.sub(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', r'<\g<0>>', content, flags=re.MULTILINE) if len(content) > 2000: texts = split_large_message(content, 2000) for text in texts: await chat.send(text) else: await chat.send(content) elif message.type == 'photo' or message.type == 'document' or message.type == 'video' or message.type == 'voice': send_content = True embed = Embed() if message.extra and 'caption' in message.extra and message.extra['caption']: lines = message.extra['caption'].split('\n') embed.title = lines[0] embed.description = '\n'.join(lines[1:]) send_content = False if send_content: if message.content.startswith('/'): await chat.send(file=discord.File(message.content, filename=message.type + get_extension(message.content))) else: await chat.send(message.content) else: if message.content.startswith('/'): await chat.send(file=discord.File(message.content, filename=message.type + get_extension(message.content)), embed=embed) elif message.content.startswith('http'): if message.type == 'photo': embed.set_image(url=message.content) elif message.type == 'video': embed.set_video(url=message.content) else: embed.url = message.content await chat.send(embed=embed) except KeyboardInterrupt: pass except Exception as e: logging.error(e) if self.bot.started: catch_exception(e, self.bot)
async def get_help_embed(command, msg_content, author): raw_args = await utils.get_args(command, msg_content) args = raw_args['args'] num_args = len(args) embed = Embed() embed.colour = author.colour if num_args not in (1, 2) and not raw_args['help']: usage = HelpManager.get_help(command._aliases[0])['usage'].replace('{prefix}', conf['prefix']) embed.add_field(name="Usage:", value=usage, inline=False) return embed elif raw_args['help']: name = msg_content.split()[0][1:] lang = 'en' else: name = args[0] lang = args[1] if num_args == 2 else 'en' entry = HelpManager.get_help(name, lang=lang) if not entry: if name in CommandRegistrar.instance().command_table.keys(): embed.title = f":octagonal_sign: There is no '{lang}' translation for '{name}'. :octagonal_sign:" else: embed.title = ":octagonal_sign: That doesnt seem to be a valid command. :octagonal_sign:" print("C**t...") return embed usage = entry['usage'].replace('{prefix}', conf['prefix']) description = entry['description'] command_table = CommandRegistrar.instance().commands command = command_table[name] embed.title = f"**{name}**" embed.description = f"aliases: {', '.join(command.aliases)}" embed.set_thumbnail(url='https://i.imgur.com/MXkFjJj.png') embed.add_field(name="Usage:", value=usage, inline=False) embed.add_field(name="Description:", value=description, inline=False) embed.set_thumbnail(url='https://i.imgur.com/MXkFjJj.png') embed.set_footer(text=f"Requested by {author.name}#{author.discriminator}", icon_url=author.avatar_url) return embed
async def rule34(ctx, *, tags: str = '*'): url34 = environ.get('URL34') def get_random_posts(url): respond_for_img = requests.get(url=url, headers=HEADERS) bs = BeautifulSoup(respond_for_img.text, 'html.parser') return bs.posts def get_any_random_post_url(url): resp = requests.get(url=url, headers=HEADERS) bs = BeautifulSoup(resp.text, 'html.parser') post_id = bs.title.string.split()[-1] post_url = url34+'page=dapi&s=post&q=index&id='+post_id return post_url if tags == '*': post_url = get_any_random_post_url(url34+'page=post&s=random') post = get_random_posts(post_url).post image_url = post['file_url'] # Image URL post_id = post['id'] # Post ID else: posts_count = get_random_posts(url34+'page=dapi&s=post&q=index&limit=1&tags='+tags)['count'] # Posts count try: post_pid = random.randint(0, int(posts_count) - 1) # Post PID except: await ctx.send(':sob: Не могу найти такой пост...') return post = get_random_posts(url34+'page=dapi&s=post&q=index&limit=1&pid='+str(post_pid)+'&tags='+tags).post # Post object image_url = post['file_url'] # Image URL post_id = post['id'] # Post ID print(f'Sending post ID{post_id}') emb = Embed() if tags != '*': emb.title='Rule34: '+tags emb.description = f'Количество постов с этим тэгом: **{posts_count}**\n' else: emb.title='Rule34: случайный пост' emb.set_author(name=f'ID: {post_id}', url=f'{url34}page=post&s=view&id={post_id}') emb.set_image(url=image_url) emb.set_footer(text='Тэги: '+post['tags']) await ctx.message.delete() await ctx.send(embed=emb)
def _query(self, query: str) -> Embed: query = query.encode('utf-8') response = requests.get( 'http://api.wolframalpha.com/v2/query?input=%s&appid=%s' % (quote(query), self._api)) try: tree = etree.fromstring(response.content) results = [] embed = Embed(color=0xFFFFFF) ident = tree.xpath( '//pod[contains(@scanner, "Identity")]/subpod/plaintext') if len(ident) > 0: embed.title = ident[0].text ok = False def append(name, path): nonlocal ok if ok: return nonlocal embed res = tree.xpath(path) if len(res) > 0: ok = True print('Adding ', res[0].text) embed.add_field(name=name, value=res[0].text) append('Solution', '//pod[contains(@title, "Solution")]/subpod/plaintext') append('Result', '//pod[contains(@title, "Result")]/subpod/plaintext') append('Value', '//pod[contains(@scanner, "Numeric")]/subpod/plaintext') append('Data', '//pod[contains(@scanner, "Data")]/subpod/plaintext') append( 'Numerical solution', '//pod[contains(@title, "Numerical solution")]/subpod/plaintext' ) append( 'Numerical solutions', '//pod[contains(@title, "Numerical solutions")]/subpod/plaintext' ) if ok: print('returning data') return embed print("No result", response.text) return None except Exception as e: print("Exception", e, response.text) return None
async def send_matches(message: discord.message.Message): resp = await do_get_todays_matches() for m in resp['matches']: e = Embed() e.title = m['competition']['name'] e.description = m['competition']['area']['name'] e.set_image(url=m['competition']['area']['ensignUrl']) e.add_field(name='Time', value=m['utcDate'], inline=False) e.add_field(name='Status', value=m['status'], inline=False) e.add_field(name=m['homeTeam']['name'], value=m['score']['fullTime']['homeTeam'], inline=True) e.add_field(name=m['awayTeam']['name'], value=m['score']['fullTime']['awayTeam'], inline=True) await message.reply(embed=e)
async def on_royal_assent_update(self, feed: Feed, update: FeedUpdate): channel = self._guild.get_channel( int(self.config.get_channel_id("royal_assent")) ) if channel is None: return next_line = "\n" embed = Embed( colour=discord.Colour.from_rgb(134, 72, 186), timestamp=datetime.now() ) embed.title = f"**Royal Assent Given:** {update.get_title()}" embed.description = ( f"**Signed At:** {update.get_update_date().strftime('%H:%M:%S on %Y:%m:%d')}{next_line}" f"**Summary:** {update.get_description()}" ) self.tracker_status["royalassent"]["confirmed"] = True await channel.send(embed=embed)
def ping_embed(package, message, paginate): 'Formats and generates the embed for the ping' embed = Embed() currentmsg = paginate.pages_yielded totalmsgs = currentmsg + paginate.pages_left if currentmsg == 1: embed.title = package['sender'] embed.set_author(name=package['description']) embed.description = message embed.set_thumbnail(url=package['logo_url']) if totalmsgs > 1: embed.set_footer( text='Message {}/{}'.format(currentmsg, totalmsgs)) embed.timestamp = datetime.utcnow() embed.colour = package['embed_colour'] return embed
async def on_feed_update(self, feed: Feed, update: FeedUpdate): channel = self._guild.get_channel(int(self.config.get_channel_id("feed"))) if channel is None: return embed = Embed(colour=config.EMBED_COLOUR, timestamp=datetime.now()) next_line = "\n" last_update = await self._bills_storage.get_last_update(update.get_bill_id()) embed.description = ( f"**Last Stage:**: {last_update['stage']}{next_line}" if last_update is not None else "" f"**Next Stage:** {update.get_stage()}{next_line} **Summary:** {update.get_description()}" f"{next_line}**Categories:**{', '.join(update.get_categories())}" ) embed.title = update.get_title() if self._guild is not None: embed.set_author(name="TLDRBot", icon_url=self._guild.icon_url) self.tracker_status["feed"]["confirmed"] = True await channel.send(embed=embed) # type: ignore
async def on_lords_division(self, division: LordsDivision, bill: Bill): channel = self._guild.get_channel( int(self.config.get_channel_id("lords_divisions")) ) if channel is None: return print(f"Lords Event: {division.get_division_title()}") print(f"Lords Event Date: {division.get_division_date()}") print("Getting lords division image.") division_file = await self.generate_division_image(self.parliament, division) print("Got lords division image.") embed = Embed( color=discord.Colour.from_rgb(166, 42, 22), timestamp=datetime.now() ) did_pass = division.get_aye_count() > division.get_no_count() embed.title = f"**{division.get_division_title()}**" embed.set_image(url="attachment://divisionimage.png") next_line = "\n" description = ( f"**ID:** {division.get_id()}{next_line}**Summary [(Link)](https://votes.parliament.uk/" f"Votes/Lords/Division/{division.get_id()}):** {division.get_amendment_motion_notes()[0:250]}...{next_line}" f"**Division Result:** {'Passed' if did_pass else 'Not passed'} by a division of " f"{division.get_aye_count() if did_pass else division.get_no_count()} " f"{'Ayes' if did_pass else 'Noes'} to {division.get_no_count() if did_pass else division.get_aye_count()}" f" {'Noes' if did_pass else 'Ayes'}{next_line}**Division Date:** " f"{division.get_division_date().strftime('%Y-%m-%d %H:%M:%S')}" ) if bill is not None: description += ( f"{next_line}**Bill Summary [(Link)](https://bills.parliament.uk/bills/" f"{bill.get_bill_id()})**: {bill.get_long_title()}**" ) embed.description = description self.tracker_status["lordsdivisions"]["confirmed"] = True embed.set_image(url="attachment://divisionimage.png") print("Sending lords division embed.") await channel.send( file=division_file, embed=embed, )
def _make_embed_skeleton(self, header: bool, desc: bool, footer: bool, image: bool): embed = self.template e_new = Embed(colour=embed.colour, type=embed.type) if header: e_new.title = embed.title e_new.url = embed.url author = embed.author if author.name is not EmptyEmbed: e_new.set_author(name=author.name, url=author.url, icon_url=author.icon_url) if desc: e_new.description = embed.description if image: if embed.image.url is not EmptyEmbed: e_new.set_image(url=embed.image.url) if embed.thumbnail.url is not EmptyEmbed: e_new.set_thumbnail(url=embed.thumbnail.url) if footer: e_new.timestamp = embed.timestamp footer = embed.footer e_new.set_footer(text=footer.text, icon_url=footer.icon_url) return e_new
async def send_embed_message( ctx: Optional[Context], *, title: str, description: Optional[str], colour=Config.EMBED_COLOUR, icon_url=IconUrls.POMBOMB, fields: list = None, footer: str = None, image: str = None, thumbnail: str = None, private_message: bool = False, _func: Callable = None, ) -> Message: """Send an embedded message using the context. @param ctx Either the context with which to send the response, or None when a coroutine is specified via _func. @param colour Colour to line the left side of the embed. @param private_messaage Whether or not to send this emabed as a DM to the user; does not apply when ctx is None. @param _func Coroutine describing how to send the embed. All other parameters: ┌───────────────────────────────────────┐ │┌─────┐ │ ││icon │ Title ┌──────┐ │ │└─────┘ │thumb-│ │ ├───────────────────────── │nail │ │ │ │ │ │ │ Description └──────┘ │ │ │ │ │ │┌──────────────┐┌──────────────┐ │ ││ ││ │ │ ││ Field ││ Field │ │ ││ (inline) ││ (inline) │ │ ││ ││ │ │ ││ ││ │ │ │└──────────────┘└──────────────┘ │ │ │ │ ┌──────────────────────────────────┐ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ Image │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ └──────────────────────────────────┘ │ │Footer │ └───────────────────────────────────────┘ @return The message object that was sent. """ # In discord.py==1.7.x there is a defect which handles None as a string. # This a workaround and can likely be removed later. description = description or EmptyEmbed message = Embed( description=description, colour=colour, ) if icon_url: message.set_author( name=title, icon_url=icon_url, ) else: message.title=title message.description=description message.colour=colour if fields: for field in fields: name, value, inline = field message.add_field(name=name, value=value, inline=inline) for content, setter, kwarg in ( (image, message.set_image, "url"), (footer, message.set_footer, "text"), (thumbnail, message.set_thumbnail, "url"), ): if content: setter(**{kwarg: content}) if ctx is None: coro = _func else: coro = ctx.author.send if private_message else ctx.send # Allow the TypeError to bubble up when both ctx and _func are None. return await coro(embed=message)