def help_command(self, event, name: str = None): # TODO: Fix issue with commands with same name different group """ ***The Help Command*** This command will provide information on a certain command, or list all commands if no command is specified. ***Optional Values*** > __name__ **The name of the target command** """ if name is None: collections = [plugin.command_list for plugin in self.bot.plugins.values()] complete = [] for collection in collections: complete.extend(collection) embed = MessageEmbed() embed.title = 'List of Commands' embed.color = 0x6832E3 embed.description = ', '.join(complete) else: for plugin in self.bot.plugins.values(): desc = plugin.get_help(name.lower()) if desc: break else: return event.msg.reply("Could not find command '{}'".format(S(name))) embed = MessageEmbed() embed.title = '**{}**'.format(name) embed.color = 0x6832E3 embed.description = desc event.msg.reply(" ", embed=embed)
def stars_stats(self, event, user=None): if user: try: given_stars = list(StarboardEntry.select( fn.COUNT('*'), ).join(Message).where( (~ (StarboardEntry.star_message_id >> None)) & (StarboardEntry.stars.contains(user.id)) & (Message.guild_id == event.guild.id) ).tuples())[0][0] recieved_stars_posts, recieved_stars_total = list(StarboardEntry.select( fn.COUNT('*'), fn.SUM(fn.array_length(StarboardEntry.stars, 1)), ).join(Message).where( (~ (StarboardEntry.star_message_id >> None)) & (Message.author_id == user.id) & (Message.guild_id == event.guild.id) ).tuples())[0] except: return event.msg.reply(':warning: failed to crunch the numbers on that user') embed = MessageEmbed() embed.color = 0xffd700 embed.title = user.username embed.set_thumbnail(url=user.avatar_url) embed.add_field(name='Total Stars Given', value=str(given_stars), inline=True) embed.add_field(name='Total Posts w/ Stars', value=str(recieved_stars_posts), inline=True) embed.add_field(name='Total Stars Recieved', value=str(recieved_stars_total), inline=True) # embed.add_field(name='Star Rank', value='#{}'.format(recieved_stars_rank), inline=True) return event.msg.reply('', embed=embed) total_starred_posts, total_stars = list(StarboardEntry.select( fn.COUNT('*'), fn.SUM(fn.array_length(StarboardEntry.stars, 1)), ).join(Message).where( (~ (StarboardEntry.star_message_id >> None)) & (Message.guild_id == event.guild.id) ).tuples())[0] top_users = list(StarboardEntry.select(fn.SUM(fn.array_length(StarboardEntry.stars, 1)), User.user_id).join( Message, ).join( User, on=(Message.author_id == User.user_id), ).where( (~ (StarboardEntry.star_message_id >> None)) & (fn.array_length(StarboardEntry.stars, 1) > 0) & (Message.guild_id == event.guild.id) ).group_by(User).order_by(fn.SUM(fn.array_length(StarboardEntry.stars, 1)).desc()).limit(5).tuples()) embed = MessageEmbed() embed.color = 0xffd700 embed.title = 'Star Stats' embed.add_field(name='Total Stars Given', value=total_stars, inline=True) embed.add_field(name='Total Starred Posts', value=total_starred_posts, inline=True) embed.add_field(name='Top Star Recievers', value='\n'.join( '{}. <@{}> ({})'.format(idx + 1, row[1], row[0]) for idx, row in enumerate(top_users) )) event.msg.reply('', embed=embed)
def on_ready(self, event): embed = MessageEmbed() embed.set_footer(text='Aetherya {}'.format('Production' if ENV == 'prod' else 'Testing')) embed.timestamp = datetime.utcnow().isoformat() embed.color = 0x779ecb reconnects = self.client.gw.reconnects self.log.info('Started session %s', event.session_id) if reconnects: embed.title = 'Reconnected' embed.color = 0xffb347 else: embed.title = 'Connected' embed.color = 0x77dd77 embed.add_field(name='Gateway Server', value=event.trace[0], inline=False) embed.add_field(name='Session Server', value=event.trace[1], inline=False) self.client.api.channels_messages_create(AETHERYA_CONTROL_CHANNEL, embed=embed)
def check_quota(self, event, quota_name): base = self.bot.plugins["BasePlugin"] moderators = base.get_staff_in_quota(quota_name, MessagesParticipant) if moderators is None: event.msg.reply(":no_entry_sign: unknown quota.") return quota_fail_list = [] quota_fail_embed = MessageEmbed() for moderator in moderators: if not moderator.eligible: quota_fail_list.append("{count} - <@{id}>".format( id=moderator.user_id, count=moderator.message_count)) if len("\n\n".join(quota_fail_list)) > 2047: for moderator in moderators: if not moderator.eligible: quota_fail_embed.add_field( value="<@{id}>".format(id=moderator.user_id), name="Message count: {count}".format( count=moderator.message_count)) if len(quota_fail_embed.fields) == 0 and len(quota_fail_list) == 0: quota_fail_embed.title = "{green_emoji} All staff passed the quota!".format( green_emoji=self.config.green_tick_emote) quota_fail_embed.color = 0x38ff48 else: if len(quota_fail_embed.fields) == 0: quota_fail_list.sort(key=quotaSort) quota_fail_embed.description = "\n\n".join(quota_fail_list) fail = len(quota_fail_list) else: fail = len(quota_fail_embed.fields) quota_fail_embed.title = "{red_emoji} {fail} staff failed the quota!".format( red_emoji=self.config.red_tick_emote, fail=fail) quota_fail_embed.color = 0xff451c event.msg.reply("Quota check:", embed=quota_fail_embed)
def render_vendor_gear(self, gear): embed = MessageEmbed() embed.title = gear['name'] embed.description = gear['vendor'] embed.add_field(name='Price', value=gear['price'], inline=True) embed.add_field(name='Armor', value=gear['armor'], inline=True) embed.add_field(name="Gearscore", value=gear['score'], inline=True) if (gear['fire'].strip().strip('-')): embed.add_field(name='Firearms', value=gear['fire'], inline=True) if (gear['stam'].strip().strip('-')): embed.add_field(name='Stamina', value=gear['stam'], inline=True) if (gear['elec'].strip().strip('-')): embed.add_field(name='Electronics', value=gear['elec'], inline=True) major_attr = " **|** ".join(gear["major"].strip().strip("-").split("<br/>")) minor_attr = " **|** ".join(gear["minor"].strip().strip("-").split("<br/>")) if major_attr: embed.add_field(name='Major Attribute(s)', value=major_attr, inline=True) if minor_attr: embed.add_field(name='Minor Attribute(s)', value=minor_attr, inline=True) if gear['rarity'] == 'header-he': embed.color = 0xDA9513 else: embed.color = 0x07C973 return embed
def on_schedule(self): self.state.ready.wait() players = self.get_players() if not players: return channel = self.state.channels.get(self.config.channel_id) if not channel: print('failed to find channel') return names = set(players.names) if self._online is not None and names != self._online: connected = names - self._online for conn in connected: embed = MessageEmbed() embed.color = JOIN_COLOR embed.title = '{} joined the server'.format(conn) channel.send_message(embed=embed) disconnected = self._online - names for conn in disconnected: embed = MessageEmbed() embed.color = LEAVE_COLOR embed.title = '{} left the server'.format(conn) channel.send_message(embed=embed) if self._online is None: print('Initial Online: {}'.format(names)) self._online = names
def on_generate(self, event, query): res = self.wolfram.query(query) if res.success.lower() == "true": results = list(res.results) pods = list(res.pods) if results: answer = results[0] if answer.title == "Distribution of total" and "@scanner" in answer and answer.scanner == "Dice": for pod in pods: if pod.title == "Example": answer = pod break elif len(pods) > 1: answer = pods[1] else: event.msg.reply("no results") return if "@scanner" in answer and answer.scanner == "Dice": embed = MessageEmbed() embed.color = cfg.color embed.description = answer.text embed.set_image(url=answer["subpod"]["img"]["@src"]) event.msg.reply("", embed=embed) elif answer.text: event.msg.reply(answer.text) else: embed = MessageEmbed() embed.color = cfg.color embed.set_image(url=answer["subpod"]["img"]["@src"]) event.msg.reply("", embed=embed) else: event.msg.reply("no results")
def show_help(self, event, name: str = None): """Explain commands or list them The help commands provides an easy way for you to learn about a certain command, or list available ones. If you want to access a specific command, type `]help <name>`, For example, `]help ban`. If you want to display a list all command categories, simply type `]help` with nothing else. If you want to list all commands in a category, simply type `]help <Name>`, For example, `]help Mod` Tip: commands will always be all lower case, command categories are Titled. """ if not name: embed = MessageEmbed() embed.color = 0x00FFFF embed.title = "List Command Categories" embed.description = "If you want to see how to use the help command, type `]help help`, otherwise, " \ "below are the available command categories." for plugin in self.bot.plugins.values(): name, desc = plugin.__doc__.split(' | ') embed.add_field(name=name, value=desc, inline=False) event.msg.reply(embed=embed) elif name.title() == name: for plugin in self.bot.plugins.values(): if name in plugin.__doc__: break else: return event.msg.reply( "Sorry, but I could not find the category '{0}'".format( name)) embed = MessageEmbed() embed.color = 0x00FFFF embed.title = plugin.__doc__ for func in plugin.meta_funcs: if hasattr(func, 'docs'): embed.add_field(name=func.docs[0], value=func.docs[1], inline=False) event.msg.reply(embed=embed) else: for plugin in self.bot.plugins.values(): for func in plugin.meta_funcs: if hasattr(func, 'docs') and func.docs[0] == name: embed = MessageEmbed() embed.title = func.docs[1] embed.color = 0x00FFFF embed.description = func.docs[2] return event.msg.reply(embed=embed) event.msg.reply( "Sorry, but I could not find the command '{0}'".format(name))
def send_post(self, config, channel, data): if config.mode is FormatMode.PLAIN: channel.send_message('**{}**\n{}'.format( data['title'], 'https://reddit.com{}'.format(data['permalink']) )) else: embed = MessageEmbed() if 'nsfw' in data and data['nsfw']: if not config.nsfw: return embed.color = 0xff6961 else: embed.color = 0xaecfc8 # Limit title to 256 characters nicely if len(data['title']) > 256: embed.title = data['title'][:253] + '...' else: embed.title = data['title'] embed.url = u'https://reddit.com{}'.format(data['permalink']) embed.set_author( name=data['author'], url=u'https://reddit.com/u/{}'.format(data['author']) ) image = None if data.get('media'): if 'oembed' in data['media']: image = data['media']['oembed']['thumbnail_url'] elif data.get('preview'): if 'images' in data['preview']: image = data['preview']['images'][0]['source']['url'] if 'selftext' in data and data['selftext']: # TODO better place for validation sz = min(64, max(config.text_length, 1900)) embed.description = data['selftext'][:sz] if len(data['selftext']) > sz: embed.description += u'...' if image: embed.set_thumbnail(url=image) elif image: embed.set_image(url=image) if config.include_stats: embed.set_footer(text=emoji.emojize('{} upvotes | {} downvotes | {} comments'.format( data['ups'], data['downs'], data['num_comments'] ))) channel.send_message('', embed=embed)
def help(self, event): embed = MessageEmbed() embed.title = "Bepis Boi's commands" embed.description = """Here are my commands:\n ***Shibe Commands*** **catch** | Find a random shibe, and add it to your inventory. **inv** [#] | Look at your collection of shibes, always stored in stacks. **show** <ID> | Show off your shibes, how cute they are. **trade** <@> <ID> | Move your shibe into anther person's inventory. **release** <ID> | Send your shibe off, into the wild. **redeem** <ABC> | Redeem a code, and earn a shibe created from our great shibe admins. ***Shop Commands*** **bepis** [@] | Admire your bepis, or make fun of someone else's. **sell** <ID> | Sell one of your shibes. Don't worry, they're in good hands. **shop** [#] | Look at our large inventory of shibes, you know you want too. **buy *shibe*** <ID> | Buy a shibe from our shop. It's worth every bepis. **donate** <@> <#> | Feeling charitable? Donate bepis to someone else. **flip** <#> | Flip a coin. You win, double your bet. Lose, lose your bet. **ticket** <#> | Buy a certain amount of tickets, the more the merrier.""" embed.set_footer(text="<>: required, []: optional, @: mention, " "#: number, ID: shop ID / inventory ID, ABC: text") embed.color = 0x000080 event.msg.reply(embed=embed) embed = MessageEmbed() embed.title = "Bepis Boi's commands" embed.description = """Here are my commands:\n ***Fun Commands*** *The following commands don't take any arguments, and show images / videos.* **disrespect, tarnation, anthem, drincc, pat, politics, soviet, stop, approved, extreme, no, blank, shibe, gethapp.** ***Extra Commands*** **invite** | Create an invite link, and share it with your friends to earn bepis. **battle** <@> <ID> | Challenge someone to a duel, pick shibes, winner get's the loser's shibe. **ping** | Pong. **help** | You're looking at it. **role** <ABC> | Add a sweet role to your account, so people know they're not alone. **unrole** <ABC> | Remove a previously added role from your account, yw. **source** | I had to prove the battle cmd wasn't rigged some how. ***Shibe Manager*** *The following commands require the Shibe Manager role* **set *shibe*** <@> <#> <ABC> | Set a certain amount of a shibe to someone. **set *bepis*** <@> <#> | Ste a certain amount of bepis to someone. **reload** <catch/shrine> | When a new image is added, reload the bot's img cache. **gencode** <ABC> | Create a code that can be redeemed, for whatever shibe is supplied. """ embed.set_footer(text="<>: required, []: optional, @: mention, " "#: number, ID: shop ID / inventory ID, ABC: text") embed.color = 0x000080 event.msg.reply(embed=embed)
def update_hint(self, hint): HintsConsumer.send_to_all( json.dumps({ 'id': hint.id, 'content': render_to_string('hint_list_entry.html', { 'hint': hint, 'now': timezone.localtime() }) })) embed = MessageEmbed() embed.author.url = hint.full_url() if hint.claimed_datetime: embed.color = 0xdddddd embed.timestamp = hint.claimed_datetime.isoformat() embed.author.name = 'Claimed by {}'.format(hint.claimer) if hint.claimer in self.get_avatars(): embed.author.icon_url = self.get_avatars()[hint.claimer] debug = 'claimed by {}'.format(hint.claimer) else: embed.color = 0xff00ff embed.author.name = 'U N C L A I M E D' claim_url = hint.full_url(claim=True) embed.title = 'Claim: ' + claim_url embed.url = claim_url debug = 'unclaimed' if self.client is None: message = hint.long_discord_message() logger.info('Hint, {}: {}\n{}'.format(debug, hint, message)) logger.info('Embed: {}'.format(embed.to_dict())) elif hint.discord_id: try: self.client.channels_messages_modify(self.HINT_CHANNEL, hint.discord_id, embed=embed) except Exception: dispatch_general_alert( 'Discord API failure: modify\n{}'.format( traceback.format_exc())) else: message = hint.long_discord_message() try: discord_id = self.client.channels_messages_create( self.HINT_CHANNEL, message, embed=embed).id except Exception: dispatch_general_alert( 'Discord API failure: create\n{}'.format( traceback.format_exc())) return hint.discord_id = discord_id hint.save(update_fields=('discord_id', ))
def server(self, event, guild_id=None): guild = self.state.guilds.get(guild_id) if guild_id else event.guild if not guild: raise CommandFail('Invalid server') content = [] content.append('**\u276F Server Information**') content.append('Owner: {} ({})'.format(guild.owner, guild.owner.id)) created_at = to_datetime(guild.id) content.append('Created: {} ({})'.format( humanize.naturaltime(datetime.utcnow() - created_at), created_at.isoformat(), )) content.append('Members: {:,}'.format(len(guild.members))) if guild.features: content.append('Features: {}'.format(', '.join(guild.features))) content.append('\n**\u276F Counts**') text_count = sum(1 for c in list(guild.channels.values()) if not c.is_voice) voice_count = len(guild.channels) - text_count content.append('Roles: {}'.format(len(guild.roles))) content.append('Text: {}'.format(text_count)) content.append('Voice: {}'.format(voice_count)) content.append('\n**\u276F Members**') status_counts = defaultdict(int) for member in list(guild.members.values()): if not member.user.presence: status = Status.OFFLINE else: status = member.user.presence.status status_counts[status] += 1 for status, count in sorted(list(status_counts.items()), key=lambda i: str(i[0]), reverse=True): content.append('<{}> - {}'.format(STATUS_EMOJI[status], count)) embed = MessageEmbed() if guild.icon: embed.set_thumbnail(url=guild.icon_url) # TODO: Fix whatever caused me to need to do this try: embed.color = get_dominant_colors_guild(guild) except: embed.color = 0x7289DA embed.description = '\n'.join(content) event.msg.reply('', embed=embed)
def on_songinfo(self, event, content): pad = self.pad_reader.find_pad(content) if not pad: event.msg.reply('Dude weed lmao cannot find shit') return embed = MessageEmbed() embed.title = pad.title embed.color = cfg.color embed.set_footer(text=pad.id) embed.url = pad.url if len(pad.needs) > 0: embed.add_field(name='needs', value=', '.join(str(x) for x in pad.needs), inline=True) embed.set_image( url= "https://cdn.discordapp.com/attachments/142137354084155393/437387811663118336/loadingu.gif" ) message = event.msg.reply('', embed=embed) try: text = ps.get_pad_text(self.session, pad.id) text = text[:text.find("~~~~~~~~")] img = self.t2i.create_img(wrap_lines(text), False) embed.set_image(url=img) message.edit(embed=embed) except ImageUploadError as e: logging.getLogger(self).error(e)
def command_test(self, event): embed = MessageEmbed() #sets the title of the embed embed.title = 'Game Center Central' embed.set_author( name='Game Center Central', url='https://discord.ares.party', icon_url='https://blog.ares.party/content/images/2018/01/pfp.gif') embed.description = 'A server built on on the topics of games and other things.' #Inline field 1 embed.add_field(name='Why is our server different', value='Well, Its different in many ways.') #Inline field 2 embed.add_field(name='What does ares break?', value='Everything.') #Inline field 3 embed.add_field(name='Can I break things with Ares', value='Pls no, We dont need more shit broken kthx.') #timestap embed.timestamp = datetime.utcnow().isoformat() #footer embed.set_footer(text='This is the f*****g footer you dumb ass.') #color embed.color = randint(0, 16777215) event.msg.reply(embed=embed)
def create_base_message_embed(): """Create a rich Discord message.""" embed = MessageEmbed() embed.color = constants.EMBED_COLOR return embed
def on_pdf(self, event, content): r = requests.get(content, allow_redirects=True) pages = convert_from_bytes(r.content) images = [] for image in pages: s = io.BytesIO() image.convert(mode="P").save(s, format='png') images.append({"path": None, "data": s.getvalue()}) embed = MessageEmbed() embed.color = cfg.color fname = '' if "Content-Disposition" in r.headers.keys(): fname = re.findall("filename=(.+)", r.headers["Content-Disposition"])[0] else: fname = content.split("/")[-1] embed.title = urllib.parse.unquote(fname) paginator.create_images(self, embed, images, event.msg.reply)
def on_commands_info(self, event, mid): cmd = Command.select(Command, Message, Channel).join( Message, on=(Command.message_id == Message.id).alias('message')).join( Channel, on=(Channel.channel_id == Message.channel_id).alias('channel') ).join( User, on=(User.user_id == Message.author_id).alias('author')).where( Command.message_id == mid).order_by( Message.timestamp.desc(), ).get() embed = MessageEmbed() embed.title = '{}.{} ({})'.format(cmd.plugin, cmd.command, cmd.message.id) embed.set_author(name=str(cmd.message.author), icon_url=cmd.message.author.get_avatar_url()) embed.color = 0x77dd77 if cmd.success else 0xff6961 if not cmd.success: embed.description = '```{}```'.format(cmd.traceback) embed.add_field(name='Message', value=cmd.message.content) embed.add_field(name='Channel', value='{} `{}`'.format(cmd.message.channel.name, cmd.message.channel.channel_id)) embed.add_field(name='Guild', value=str(cmd.message.guild_id)) event.msg.reply(embed=embed)
def store(self, event): if event.guild is not None: event.msg.delete() embed = MessageEmbed() embed.title = "Discord Testers Shop" embed.description = "Use XP to get super cool Dabbit-approved rewards from the shop!" embed.thumbnail.url = "https://cdn.discordapp.com/attachments/330341170720800768/471497246328881153/2Mjvv7E.png" embed.color = int(0xe74c3c) # bug hunter red = #e74c3c index = 0 for item in self.config.store: index = index + 1 name = item["title"] content = "Cost: {cost}\nDescription: {description}\n{link}Buy this with `+buy {id}`".format( cost=item["cost"], description=item["description"], link="" if item.get("link", None) is None else "[Example]({link})\n".format(link=item["link"]), id=index ) embed.add_field(name=name, value=content, inline=False) try: channel = event.msg.author.open_dm() channel.send_message("Shop:", embed=embed) except: event.channel.send_message("please open your direct messages.").after(10).delete()
def render_vendor_gear_mod(self, gearmod): embed = MessageEmbed() embed.title = gearmod['name'] embed.description = gearmod['vendor'] embed.add_field(name='Price', value=gearmod['price'], inline=True) embed.add_field(name='Stat', value=gearmod['stat'], inline=True) embed.add_field(name='Attribute', value=gearmod['attribute']) if gearmod['type'] == 'purple-mod': embed.color = 0x993D78 else: embed.color = 0xDA9513 return embed
def on_commands(self, event, args): embed = MessageEmbed() embed.color = cfg.color if len(args.category) > 0: for cat in self.cmds: if args.category.lower() in cat.lower(): embed.title = cat for k in self.cmds[cat]: embed.add_field(name="`{}`".format( self.cmds[cat][k][0]), value=self.cmds[cat][k][1], inline=False) event.msg.reply('', embed=embed) return event.msg.reply("Category not found") return embed.title = "Commands" embed.description = "`!help` show this message\n`!help <category>` show more info for category" for cat in self.cmds: embed.add_field(name=cat, value="`{}`".format(' '.join( x for x in self.cmds[cat])), inline=False) event.msg.reply('', embed=embed)
def on_urban(self, event, phrase=None): self.client.api.channels_typing(event.msg.channel_id) urban_entry = None if phrase is None: urban_entry = random.choice( ud.random()) # grab some random words | list of urbandef else: defs = ud.define(phrase) if len(defs) > 0: urban_entry = defs[0] if urban_entry is None: event.msg.reply('Failed to find a definition for that!') else: definition = urban_entry.definition # Let's do a little... checking! if len(definition) >= 2000: definition = definition[:1950] + '...' # Let's construct an embed :) embed = MessageEmbed() embed.title = f"**Defintion of {urban_entry.word}**" embed.description = definition embed.add_field(name='Example', value=urban_entry.example) embed.add_field( name='Rating', value=f"{urban_entry.upvotes} 👍 | {urban_entry.downvotes} 👎") embed.color = '5824574' event.msg.reply(embed=embed)
def plugin_manager(self, event, plugin=None, mode='list'): if mode == 'list': embed = MessageEmbed() embed.color = 0x7289da embed.set_author(name='Loaded Plugins ({})'.format(len(self.bot.plugins)), icon_url=self.state.me.avatar_url) embed.description = '```md\n{}```'.format('\n'.join('- {}'.format(key) for key in self.bot.plugins)) embed.set_footer(text='Use file name for load, registered name for unload/reload.') return event.msg.reply('', embed=embed) pl = self.bot.plugins.get(plugin) if mode == 'load': if pl: return event.msg.reply('<:{}> {} plugin is already loaded.'.format(RED_TICK_EMOJI, pl.name)) try: self.bot.add_plugin_module('rowboat.plugins.{}'.format(plugin)) except: return event.msg.reply('<:{}> Failed to load {} plugin.'.format(RED_TICK_EMOJI, plugin)) return event.msg.reply(':ok_hand: Loaded {} plugin.'.format(plugin)) if not pl: return event.msg.reply('<:{}> Could not find this plugin.'.format(plugin)) if mode == 'unload': self.bot.rmv_plugin(pl.__class__) self.log.info('Unloaded {} plugin'.format(pl.name)) return event.msg.reply(':ok_hand: Unloaded {} plugin.'.format(pl.name)) if mode == 'reload': self.bot.reload_plugin(pl.__class__) self.log.info('Reloaded {} plugin'.format(pl.name)) return event.msg.reply(':ok_hand: Reloaded {} plugin.'.format(pl.name))
def get_xp_cooldown(self, event): cd_limit = time.time() - 86400 em = MessageEmbed() em.title = 'Queue XP actions' em.description = 'Your queue actions gaining XP (past 24 hours):' em.color = '7506394' for action, limit in self.config.reward_limits.items(): action_name = self.config.cooldown_map.get(action, None) if action_name is None: continue user_actions = self.actions.find({ 'user_id': str(event.author.id), 'type': action, 'time': { '$gte': cd_limit } }).limit(limit) recent = [x['time'] for x in user_actions] used = len(recent) fv = f'{used}/{limit}' if used >= limit: rem_secs = (min(recent) + 86400) - time.time() hours, rem = divmod(rem_secs, 3600) mins, secs = divmod(rem, 60) fv += f' - Cools down in {int(hours)}h {int(mins)}m {int(secs)}s' em.add_field(name=action_name, value=fv) event.msg.reply(embed=em)
def generate_store_embed(self, current, max): embed = MessageEmbed() embed.title = "Discord Testers Store ({current}/{max})".format(current=str(current + 1), max=str(max + 1)) embed.description = "Use XP to get super cool Dabbit-approved:tm: rewards from the store!" embed.thumbnail.url = "https://cdn.discordapp.com/attachments/330341170720800768/471497246328881153/2Mjvv7E.png" embed.color = int(0xe74c3c) return embed
def on_gelbooru(self, event, tags): r = requests.get("https://gelbooru.com/index.php", params={ "page": "dapi", "s": "post", "q": "index", "tags": tags, "limit": 200, "json": 1 }) if len(r.content) > 0 and len(r.json()) > 0: n = random.randint(0, len(r.json()) - 1) embed = MessageEmbed() embed.color = cfg.color embed.title = tags embed.url = "https://gelbooru.com/index.php?page=post&s=view&id={}".format( r.json()[n]["id"]) embed.set_image(url=r.json()[n]["file_url"]) event.msg.reply("", embed=embed) else: event.msg.reply("nothing found")
def gen_participants_embed(page, num, max): embed = MessageEmbed() embed.title = "Event participants {}/{}".format(num, max) embed.description = page embed.timestamp = datetime.utcnow().isoformat() embed.color = int('F1C40F', 16) return embed
def on_dab(self, event): r = requests.get("https://danbooru.donmai.us/posts.json", params={ "tags": "dab_(dance) rating:safe", "limit": 200, "random": "false" }) if len(r.content) > 0 and len(r.json()) > 0: if "success" in r.json() and not r.json()["success"]: event.message.reply(r.json()["message"]) return n = random.randint(0, len(r.json()) - 1) embed = MessageEmbed() embed.color = cfg.color if "large_file_url" in r.json()[n]: embed.set_image(url=r.json()[n]["large_file_url"]) else: embed.set_image(url=r.json()[n]["file_url"]) event.msg.reply('', embed=embed)
def commands_command(self, event): """Get a list of commands you can use with the bot""" embed = MessageEmbed() embed.set_author( name='Referee Commands', url='https://github.com/UHCBot/Referee', icon_url=self.client.state.me.avatar_url ) embed.color = 0xf3733a for p in self.bot.plugins.values(): for c in p.commands: args = [] if c.args: for arg in c.args.args: args.append(arg.name) user_level = get_user_level(event.guild.members[event.msg.author.id]) global_admin = check_global_admin(event.msg.author.id) if c.level: if not global_admin and c.level == -1: continue if not global_admin and c.level > user_level: continue embed.add_field( name='{}{}'.format( c.group + ' ' if c.group else '', c.name), value='Level: {} {}\nArgs: {}\nDescription: {}'.format( c.level if c.level else 'Everyone', 'or higher' if c.level and c.level != -1 else '', ', '.join(args) if args != [] else 'None', c.get_docstring() if c.get_docstring() else 'No description provided' ).replace('-1', 'Global admin').replace('mod', 'Mod').replace('dev', 'Dev'), inline=True ) event.msg.reply('', embed=embed)
def message_updated(self, msg): # ignore bot messages if not bool(msg.author.id): return if msg.guild is not None: try: logchannel = self.logger[msg.guild.id] msg_old = self.logger.getHistory( msg.guild.id, msg.channel.id).getContent(msg.id) self.logger.updateMessage(msg) embed = MessageEmbed() embed.title = 'Message updated in: **#{}**'.format( msg.channel.name) embed.description = '**{}**\n***old:***\n{}\n***new:***\n{}'.format( msg.author.username.encode("ascii", "ignore"), msg_old, msg.content) embed.color = int("1388D6", 16) #embed.set_author(name = '{}:'.format(msg.author.username)) #embed.add_field(name = 'old:', value = msg_old) #embed.add_field(name = 'new:', value = msg.content) msg.guild.channels[logchannel].send_message('', embed=embed) except KeyError: pass
def message_delete(self, event): channel = self.state.channels[event.channel_id] server = channel.guild # ignore bot messages #if not bool(msg.author.id): # return if server is not None: logchannel = self.logger[server.id] try: message = self.logger.getHistory(server.id, channel.id)[event.id] # ingore embed only messages if not bool(message.content): return embed = MessageEmbed() embed.title = "Message deleted in: **#{}**".format( channel.name) embed.description = '**{}**\n{}'.format( message.author.username.encode("ascii", "ignore"), message.content) embed.color = int("D3262E", 16) #embed.type = 'fields' #embed.add_field(name = message.author.username, value = message.content) server.channels[logchannel].send_message('', embed=embed) except KeyError: pass
def embed(self): e = MessageEmbed() e.color = self.color e.title = self.stream_title e.url = self.stream_url author = MessageEmbedAuthor() author.name = self.display_name author.url = self.stream_url author.icon_url = self.avatar e.author = author thumbnail = MessageEmbedThumbnail() thumbnail.url = self.avatar thumbnail.proxy_url = self.avatar thumbnail.width, thumbnail.height = 100, 100 e.thumbnail = thumbnail image = MessageEmbedImage() image.url = self.stream_preview + '?rand={}'.format(randint(0, 999999)) e.image = image footer = MessageEmbedFooter() footer.text = self.platform_name e.footer = footer if self.stream_game: game_field = MessageEmbedField() game_field.name = 'Played Game' game_field.value = self.stream_game game_field.inline = True e.fields.append(game_field) if self.stream_viewers_count or self.stream_viewers_count == 0: viewers_field = MessageEmbedField() viewers_field.name = 'Viewers' viewers_field.value = str(self.stream_viewers_count) viewers_field.inline = True e.fields.append(viewers_field) return e