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_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 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 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 on_analyze_command(self, event): if event.channel.name not in ALLOWED_CHANNELS: event.msg.reply( "{}, please run this command in #help.".format(event.author.mention)) return if len(event.msg.attachments) < 1: event.msg.reply("{}, usage: Attach Xenia's logfile with your message (preferably compressed in a .zip).".format( event.author.mention)) return # Fire off a typing event. self.client.api.channels_typing(event.channel.id) for _, attach in event.msg.attachments.items(): s_file_name = sanitize(attach.filename, escape_codeblocks=True) if attach.size > SIZE_LIMIT_MB: event.msg.reply(event.author.mention, embed=MessageEmbed(title=s_file_name, color=COLOR_RED, description="**File above size limit, not analyzed**. Did you compress it?")) continue r = requests.get(attach.url) if r.status_code != 200: event.msg.reply(event.author.mention, embed=MessageEmbed(title=s_file_name, color=COLOR_RED, description="**Failed to fetch file from Discord**, status code {}".format(r.status_code))) continue mime = magic.from_buffer(r.content, mime=True) if mime == 'text/plain': # Plaintext, straight to the parser! event.msg.reply(event.author.mention, embed=self.parse_log_file( attach.filename, io.StringIO(r.text))) elif mime == 'application/zip': z = zipfile.ZipFile(io.BytesIO(r.content)) if len(z.namelist()) != 1: event.msg.reply(event.author.mention, embed=MessageEmbed( title=s_file_name, color=COLOR_RED, description="**Archives must contain only a single file**.")) continue # Parse every file in the zip file. for name in z.namelist(): # Check the guessed type as well. No voodoo embedding zip files inside one another. mime = magic.from_buffer(z.open(name).read(1024), mime=True) if mime != 'text/plain': event.msg.reply(event.author.mention, embed=MessageEmbed( title=s_file_name, color=COLOR_RED, description="**Contents not plaintext, ignored**.")) continue event.msg.reply(event.author.mention, embed=self.parse_log_file( name, z.open(name))) z.close() else: event.msg.reply(event.author.mention, embed=MessageEmbed( title=s_file_name, color=COLOR_RED, description="**Unsupported file type, not analyzed**.")) continue
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 cmd_help(self, event, command=None): """ This is the help command! Use this command to help you get info some certain commands. Usage: `help [Command Name]` To get general info, just type `help` """ if command is None: embed = MessageEmbed() embed.title = 'GamesKeeper Help' embed.description = '**To get help with a certain command please use `{prefix}help Command`**\n** **\nFor help with settings please type `{prefix}help settings`'.format( prefix=event.db_guild.prefix) return event.msg.reply('', embed=embed) elif command == 'settings' and (event.user_level == 100 or event.bot_admin): embed = MessageEmbed() embed.title = 'GamesKeeper Settings Help' description = [ 'To change most settings, the command group is `update`', '\♦ To change **Prefix**, use `{}settings prefix`'.format( event.db_guild.prefix), '\♦ To change **Games Category**, use `{}settings gc`'.format( event.db_guild.prefix), '\♦ To change the **Referee** role, use `{}settings ref`'. format(event.db_guild.prefix), '\♦ To update **Spectator** roles, use `{}settings addspec/rvmspec`' .format(event.db_guild.prefix), '\♦ To **Enable/Disable Games**, use `{}games enable/disable`'. format(event.db_guild.prefix), ] embed.description = '\n'.join(description) return event.msg.reply('', embed=embed) elif command == 'settings' and (event.user_level != 100 or not event.bot_admin): return event.msg.reply('`Error:` Command Not Found') else: commands = list(self.bot.commands) for cmd in commands: if cmd.name != command: continue elif cmd.level == -1 and not event.bot_admin: continue else: embed = MessageEmbed() embed.title = 'Command: {}{}'.format( '{} '.format(cmd.group) if hasattr(cmd, 'group') and cmd.group is not None else '', cmd.name) helpstr = cmd.get_docstring() embed.description = helpstr return event.msg.reply('', embed=embed) return event.msg.reply('`Error:` Command Not Found')
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 get_queue_embed_item(entry, count): description = entry.description if not description: description = "_None_" category_breadcrumbs = "#" + entry.category_channel_name if entry.genre_category_name: category_breadcrumbs = "#" + entry.genre_category_name + " / " + category_breadcrumbs embed = MessageEmbed() embed.title = "Items in queue: {numberOfItems}".format(numberOfItems=count) if entry.state == 4: embed.description = '🔄 Category Change!' embed.add_field(name='Name', value=entry.name, inline=True) embed.add_field(name='Description', value=description, inline=True) embed.add_field(name='Category', value=category_breadcrumbs, inline=True) embed.add_field(name='Invite', value="discord.gg/{entry.invite_code}".format(entry=entry), inline=True) embed.add_field(name='Server ID', value="`#{entry.server_id}`".format(entry=entry), inline=True) embed.add_field( name='Invitee', value="<@{entry.invitee_id}>\n`#{entry.invitee_id}`".format( entry=entry), inline=True) embed.add_field(name='Submitted At', value="{entry.submitted_at}".format(entry=entry), inline=True) embed.set_footer(text="ID: {entry.id}".format(entry=entry)) # embed.color = 0xffd700 return 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 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 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 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 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 list_settings(self, event): settings_msg = """ __**Prefix**__: {prefix} __**Referee Role**__: {rr} __**Games Category**__: {gc} __**Spectator Roles**__: {sr} """ settings = Guild.using_id(event.guild.id) games_category = None if settings.games_category: games_category = event.guild.channels.get(settings.games_category) spectator_roles = [] if len(settings.spectator_roles) > 0: for x in settings.spectator_roles: spectator_roles.append('<@&{}>'.format(x)) embed = MessageEmbed() # embed.color = 0xFF0000 embed.add_field(name='General Settings', value=settings_msg.format( prefix=settings.prefix, rr='{}'.format('`None`' if settings.referee_role == None else '<@&' + str(settings.referee_role) + '>'), gc='{} (`{}`)'.format(games_category.name, games_category.id) if settings.games_category else '`None`', sr='{}'.format('`None`' if len(spectator_roles) == 0 else ', '.join(spectator_roles)) )) embed.add_field(name='Enabled Games', value='{}'.format(''.join(settings.enabled_games_emotes())), inline=True) embed.add_field(name='Disabled Games', value='{}'.format(''.join(settings.disabled_games_emotes())), inline=True) embed.set_footer(text='Go get help with settings, do {}help settings'.format(settings.prefix), icon=self.state.me.get_avatar_url()) return event.msg.reply('', embed=embed)
def render_status_command(self): param = { "orderBy": "time desc", "recordsPerPage": 1, "page": 0 } res = requests.get(BACKEND_HOST + '/document/vendors-update', params=param, headers={SESSION_HEADER: self.session}).json() info = res['data'][0] today = arrow.utcnow() reset_text = "" if today.weekday() == 5: reset_text = "in 6 days" else: temp = today.shift(weekday=5) reset_text = temp.humanize() last_updated = arrow.Arrow.fromtimestamp(info['time']) embed = MessageEmbed() embed.title = "Last Updated %s" % last_updated.humanize() embed.description = "by %s" % info['updater'] embed.add_field(name='Next Vendor Reset (in game)', value=reset_text, inline=True) return embed
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 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 create_base_message_embed(): """Create a rich Discord message.""" embed = MessageEmbed() embed.color = constants.EMBED_COLOR return 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 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 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 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_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 command_about(self, event): embed = MessageEmbed() embed.set_author(name='Rowboat', icon_url=self.client.state.me.avatar_url, url='https://docs.rowboat.party/') embed.description = BOT_INFO embed.add_field(name='Servers', value=str(Guild.select().count()), inline=True) embed.add_field(name='Uptime', value=humanize.naturaltime(datetime.utcnow() - self.startup), inline=True) event.msg.reply('', embed=embed)
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 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 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))