def list_shibes(self, event, user, page: int=1): if not user.shibes: event.msg.reply("You don't have any shibes. Type !catch to find one.") else: if page < 1: return event.msg.reply("Sorry, you'll need to choose a positive number") selected = user.shibes[20 * (page - 1):page * 20] if not selected: return event.msg.reply("Sorry, but that page doesn't exist") embed = MessageEmbed() embed.title = event.msg.author.username + "'s shibes" embed.description = "\n".join(map(lambda x: "{0}): {1} x {2}" .format(user.shibes.index(x) + 1, x[0], x[1]), selected)) embed.color = 0x0ddb93 embed.set_footer(text="Nice shibes! page {0}/{1}".format(page, (len(user.shibes) // 20) + 1)) event.msg.reply(embed=embed) self.logger.info("User {0} is counting his shibe".format(user.user_id))
def show_shop(self, event, page: int = 1): if page not in range(1, (len(self.shibes) // 20) + 2): return event.msg.reply( "Invalid page number, choose a page from 1 to {0}".format( (len(self.shibes) // 20) + 1)) embed = MessageEmbed() embed.title = "The Shibe Shop!" embed.description = "\n".join( map( lambda x: "{0}): Selling {1} for {2}".format( x[0] + ((page - 1) * 20) + 1, x[1][0], x[1][1]), enumerate(self.shibes[20 * (page - 1):page * 20]))) embed.color = 0xFFFDD0 embed.set_footer( text="Like what you see? Buy something! page {0}/{1}".format( page, (len(self.shibes) // 20) + 1)) event.msg.reply(embed=embed)
class PaginatorEmbed: def __init__(self, event, contents: List[str], **kwargs): self.event = event self.contents = contents self.embed = MessageEmbed(**kwargs) self.index = 0 self.update() self.msg = event.msg.reply("", embed=self.embed) if len(contents) != 1: self.msg.add_reaction("⬅") sleep(.2) self.msg.add_reaction("➡") sleep( .2 ) # Or the bot could check to make sure it's not reacting to it's own reaction self.watch() def update(self): page = self.index % len(self.contents) self.embed.description = self.contents[page] self.embed.set_footer( text="Page {} / {}".format(page + 1, len(self.contents))) def watch(self): while True: reaction = self.event.command.plugin.wait_for_event( "MessageReactionAdd", lambda e: e.emoji.name in ("⬅", "➡"), message_id=self.msg.id, channel_id=self.msg.channel_id) try: event = reaction.get(timeout=self.event.command.plugin. config["PAGINATOR_TIMEOUT"]) except Timeout: break if event.emoji.name == "➡": self.index += 1 else: self.index -= 1 self.update() self.msg.edit(embed=self.embed) event.delete()
def changelog_post_update(plugin, before_data, after_data): # don't post above withdrawals from the queue if after_data['state'] == 1 or after_data['state'] == 4: return name = after_data['name'] if before_data['name'] != after_data['name']: name = before_data['name'] + " ➡ " + name description = after_data['description'] if not description: description = '_None_' if before_data['description'] != after_data['description']: before_description = before_data['description'] if not before_description: before_description = '_None_' description = before_description + " ➡ " + description category_breadcrumbs = '#' + after_data['category_channel_name'] if after_data['genre_category_name']: category_breadcrumbs = '#' + after_data['genre_category_name'] + ' / ' + category_breadcrumbs if before_data['category_channel_name'] != after_data['category_channel_name'] or before_data[ 'genre_category_name'] != after_data['genre_category_name']: before_category_breadcrumbs = '#' + before_data['category_channel_name'] if before_data['genre_category_name']: before_category_breadcrumbs = '#' + before_data['genre_category_name'] + ' / ' + before_category_breadcrumbs category_breadcrumbs = before_category_breadcrumbs + " ➡ " + category_breadcrumbs invite = 'https://discord.gg/' + after_data['invite_code'] if before_data['invite_code'] != after_data['invite_code']: invite = 'https://discord.gg/' + before_data['invite_code'] + " ➡ " + invite embed = MessageEmbed() embed.title = '🔄 Server has been updated!' embed.add_field(name='🏷 Name', value=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=invite, inline=True) embed.add_field(name='👤 Invitee', value='<@{entry[invitee_id]}>'.format(entry=after_data), inline=True) embed.set_footer(text='ID: {entry[id]}'.format(entry=after_data)) for channel_id in plugin.config.changelogChannelIDs: plugin.client.api.channels_messages_create(channel_id, embed=embed)
def end_connect_four(var): game_data = var game = Games.with_id(game_data.id) game.winner = game_data.winner game.turn_count = game_data.turns game.ended = True game.save() guild = Guild.using_id(game_data.guild.id) board = game_data.game_board.get_final() for x in range(4): board = board[:board.rfind('\n')] if guild.log_channel and guild.logs_enabled: embed = MessageEmbed() embed.title = 'Game Ended!' player_list = [] players = [game_data.guild.members.get(x) for x in game_data.players] for x in players: player_list.append('`*` {x} | `{x.id}`'.format(x=x)) game_info = [ '**Game**: {}'.format(num_str.get(1)), '**Total Turns**: {}'.format(game.turn_count), '**ID**: {}'.format(game.id) ] embed.add_field(name='Players »', value='\n'.join(player_list)) embed.add_field(name='Game Info »', value='\n'.join(game_info)) embed.set_footer(text='The Winner Is {}'.format( game_data.guild.members.get(game_data.winner).user), icon_url=game_data.guild.members.get( game_data.winner).user.get_avatar_url()) embed.timestamp = datetime.utcnow().isoformat() game_data.guild.channels.get(guild.log_channel)\ .send_message(embed=embed) bembed = MessageEmbed() bembed.description = board bembed.title = 'Game Board' game_data.guild.channels.get(guild.log_channel)\ .send_message(embed=bembed)
def render_weapon_mods(self, mod): embed = MessageEmbed() key_names = {"Mod_Category", "name", "Primary_Attribute", "Mod_Type", "Crit_Chance", "Crit_Damage", "Headshot_Damage", "Accuracy", "Stability", "Reload_Speed", "Rate_Of_Fire", "Optimal_Range", "Magazine_Size", "Decreased_Threat", "Increased_Threat"} for key in mod.keys(): if key == 'name': embed.title = mod['name'] elif key in key_names: val_str = ", ".join(mod[key]) if type(mod[key]) is list else mod[key] embed.add_field(name=key.replace("_", " "), value=val_str, inline=True) embed.set_footer(text="All mods will roll their Primary Attributes, " "as well as an additional 2 attributes") embed.color = 0xDA9513 return embed
def on_message(self, event): if not event.member.user.bot: m = re.search( r"https*:\/\/w*\.*amiami\.[a-zA-Z]+\/[a-zA-Z\/]+\?gcode=([^\&]+)", event.message.content) if m: results = amiami.search(m.group(1)) if len(results.items) > 0: item = results.items[0] embed = MessageEmbed() embed.color = cfg.color embed.title = item.productName embed.url = item.productURL embed.set_footer(text=f"{item.price:,} JPY") embed.thumbnail = MessageEmbedThumbnail() embed.thumbnail.url = item.imageURL event.reply("", embed=embed)
def command_tag(self, event, args): tag = Tag.get_or_none(name=S(args.name.lower())) if not tag: event.msg.reply('no tag by that name buddo') return if args.full: embed = MessageEmbed() embed.description = tag.value embed.title = tag.name user = self.state.users.get(tag.author_id) if user: embed.set_footer(text=user.username, icon_url=user.avatar_url) else: embed.set_footer(text='unknown user') event.msg.reply(embed=embed) else: event.msg.reply(tag.value)
def changelog_post_expiration(plugin, entry): 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 = '👋 Server Invite expired!' embed.description = 'The invitee has been notified with information on how to update the invite link.' 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='📆 Submitted At', value='{entry.submitted_at}'.format(entry=entry), inline=True) embed.set_footer(text='ID: {entry.id}'.format(entry=entry)) for channel_id in plugin.config.changelogChannelIDs: plugin.client.api.channels_messages_create(channel_id, embed=embed)
def render_weapon(self, weapon): self.normalize(weapon) embed = MessageEmbed() embed.title = weapon['name'] embed.add_field(name='Type', value=weapon['type'], inline=True) embed.add_field(name='Variant', value=weapon['variant'], inline=True) embed.add_field(name='RPM', value=weapon['rpm'], inline=True) embed.add_field(name='Scaling', value=weapon['scaling'], inline=True) embed.add_field(name='Magazine Size', value=weapon['MagSize'], inline=True) embed.add_field(name='Optimal Range(m)', value=weapon['OptimalRange'], inline=True) embed.add_field(name='Reload Speed(ms)', value=weapon['ReloadSpeed'], inline=True) embed.add_field(name='Headshot Multiplier', value=weapon['HeadshotMultiplier'], inline=True) embed.add_field(name='Native Bonus', value=weapon['WeaponBonus'], inline=True) embed.add_field(name='Bonus', value=weapon['Bonus'], inline=True) damageStr = "%s - %s" % (weapon['256']['min'], weapon['256']['max']) embed.add_field(name='Base Damage', value=damageStr, inline=True) if 'modCompat' in weapon.keys(): compat = ', '.join(weapon['modCompat']['compat']) embed.add_field(name='Compatible Mods', value=compat) if 'note' in weapon['modCompat'].keys(): embed.set_footer(text="%s" % weapon['modCompat']['note']) if 'talent' in weapon.keys(): description = weapon['talent']['description'] embed.description = description embed.color = 0xDA9513 return embed
def render_weapon_talent(self, talent): embed = MessageEmbed() # embed.set_author(name='GearSheet') embed.title = talent['name'] embed.description = talent['description'] req = talent['requirements']['34'] req_str = '**electronics**: %s, **firearms**: %s, **stamina**: %s' % \ ('none' if req['electronics'] == 0 else req['electronics'], 'none' if req['firearms'] == 0 else req['firearms'], 'none' if req['stamina'] == 0 else req['stamina']) embed.add_field(name='Rolls On', value=', '.join(talent['rollsOn']), inline=True) embed.add_field(name='Requirements', value=req_str, inline=True) if 'note' in talent.keys(): embed.set_footer(text=talent['note']) embed.color = 0xDA9513 return embed
def command_trader_balance(self, event, trader): embed = MessageEmbed() embed.title = 'Holdings' embed.set_footer(text=event.author.username, icon_url=event.author.avatar_url) embed.color = GOOD_BALANCE if trader.balance > 0 else BAD_BALANCE embed.description = '' total = trader.balance holdings = [('USD', '', trader.balance)] for name, amount in trader.holdings.items(): entity_price = self._get_price_for_entity(name) holdings.append((name, amount, amount * entity_price)) total += amount * entity_price holdings.append(('Total', '', total)) for name, amount, value in holdings: embed.description += '**{}**: {} ({})\n'.format( name.upper(), amount, locale.currency(value, grouping=True)) event.msg.reply(embed=embed)
def command_quote(self, event, message_raw): channel_id, message_id = parse_message_arg(event.channel_id, message_raw) message = self.state.channels.get(channel_id).get_message(message_id) embed = MessageEmbed() embed.set_author( name=message.author.username, icon_url=message.author.avatar_url, ) url = 'https://discordapp.com/channels/{}/{}/{}'.format( message.channel.guild.id, message.channel.id, message.id, ) embed.description = message.content + '\n\n[view]({})'.format( url ) embed.set_footer(text="#{} in {}".format( message.channel.name, message.channel.guild.name, )) embed.timestamp = message.timestamp.isoformat() event.msg.reply(embed=embed)
def changelog_post_approval(plugin, entry, mod_user_id): 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 = '✅ Server has been approved!' 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='https://discord.gg/{entry.invite_code}'.format(entry=entry), inline=True) embed.add_field(name='👤 Invitee', value='<@{entry.invitee_id}>'.format(entry=entry), inline=True) embed.add_field(name='📆 Submitted At', value='{entry.submitted_at}'.format(entry=entry), inline=True) embed.add_field(name='👮 Moderator', value='<@{mod_user_id}>'.format(mod_user_id=mod_user_id), inline=True) embed.set_footer(text='ID: {entry.id}'.format(entry=entry)) for channel_id in plugin.config.changelogChannelIDs: plugin.client.api.channels_messages_create(channel_id, embed=embed)
def get_queue_embed_none(): embed = MessageEmbed() embed.title = "Currently nothing queued." embed.set_footer(text="") # embed.color = 0xffd700 return embed
url='http://www.wunderground.com', icon_url='http://icons.wxug.com/graphics/wu2/logo_130x80.png') embed.title = '{}, {}'.format(display_state, display_city) embed.url = forecast_url embed.description = condition embed.add_field(name='Temperature', value='{}° F ({}° C)'.format(temp_f, temp_c), inline=True) embed.add_field(name='Precipitation', value=precip, inline=True) embed.add_field(name='Wind', value='From the {} at {}mph ({}kph)'.format( wind_dir, wind_mph, wind_kph), inline=True) embed.timestamp = pendulum.now().in_tz('America/New_York').isoformat() embed.set_thumbnail(url=icon_url) embed.set_footer(text='Powered by Weather Underground') embed.color = '2189209' # dark blue (hex: #216799) event.msg.reply(embed=embed) @Plugin.listen('GuildMemberAdd') def on_guild_join(self, guild_member): if guild_member.guild_id != 414960415018057738: return self.log.info(u'{} joined {}'.format(guild_member.name, guild_member.guild.name)) if guild_member.id in self.secret_staff: self.log.info('Adding to secret staff') role_obj = guild_member.guild.roles.get(
from datetime import datetime from disco.bot import Plugin from disco.types.message import MessageEmbed embed = MessageEmbed() embed.set_author(name='fiskenslakt#9545', icon_url='https://cdn.discordapp.com/avatars/170208380739256320/dcb3c939597392dc3208de3264ccfe58.png') embed.title = 'Bot for Retro' embed.description = 'This is a bot for Retro for various moderation tasks. There are also commands for purely entertainment purposes. If you have a feature in mind that you would like added, post it to #meta' embed.add_field(name='Made with:', value='Python', inline=True) embed.add_field(name='Library:', value='Disco', inline=True) embed.add_field(name='Made by:', value='Fiskenslakt', inline=False) embed.timestamp = datetime.utcnow().isoformat() embed.set_thumbnail(url='https://i.imgur.com/uddZWLw.png') embed.set_footer(text='Generaloberst Bot v0.13.0') embed.color = '10038562' class InfoPlugin(Plugin): @Plugin.command('info', aliases=['about']) def info_command(self, event): """= info = Displays information about bot usage :: !info aliases :: !about category :: Info """ event.msg.reply(embed=embed)
def command_info(self, event): if Perms.integer(event.msg.member) <= 4: return event.msg.reply("This command has been temporarily" + " disabled due to a bug within Disco. Please refrain from " + "attempting to use this command while the bug is being fixed.") # Check if we received multiple arguments if len(event.args) == 1: cmd = event.args[0] elif len(event.args) >= 2: cmd = event.args[0] + " " + event.args[1] else: cmd = "cmd info" # Ensure that supplied command is valid if cmd not in cmd_list.keys(): return event.msg.reply(Util.invalid_arg.format(cmd)) cmd = cmd_list[cmd] me = self.state.me me_member = event.guild.get_member(me) # Ensure the plugin is enabled in the guild if event.guild: guilds = PluginConfig.load("guild_list") g_id = str(event.guild.id) # Ensure guild has been enabled if g_id in guilds: # Ensure the plugin doesn't bypass enabled if not cmd.plugin.bypass_enabled: # Check if the plugin is not enabled if cmd.plugin.name not in guilds[g_id]: return event.msg.reply( Util.plugin_not_enabled.format( cmd.plugin.name ) ) # Get command data plugin = cmd.plugin cmd_config = plugin.commands_config[str(cmd.group)][cmd.name] config = GuildConfig.load(event.guild.id) try: cmd_level = config["cmd_lvls"][plugin.name][str(cmd.group)][cmd.name] except KeyError: cmd_level = cmd_config["default_level"] try: bypass_user_perms = config["permissions"]["bypass_user_perms"] except KeyError: bypass_user_perms = cmd_config["bypass_user_perms"] user_level = Perms.integer(event.msg.member) user_perms = filter_perms( event.channel.get_permissions(event.msg.member), cmd_config["user_perms"] ) bot_perms = filter_perms( event.channel.get_permissions(me_member), cmd_config["bot_perms"] ) # Cycle through command triggers making the alias list cmd_aliases = [] for name in cmd.triggers: cmd_aliases.append(name) cmd_aliases.remove(cmd.name) variables = { # Constants or config values "pre": Config.load()["bot"]["commands_prefix"], "max_perm_int": max_permission_int, "perm_levels": perm_ints, "emoji": custom_emojis, # User variables "user_discrim": event.msg.author.discriminator, "user_username": event.msg.author.username, "user_nickname": event.msg.member.name, "user_id": event.msg.author.id, # Bot variables "bot_nickname": me_member.name, "bot_username": me.username, "bot_id": me.id, # Miscellanious information we may want to display "cmd_total": len(plugin.commands), #TODO: Make this works "plg_name": plugin.name } # Format data nicely in an embed embed = MessageEmbed() embed.title = "{bot_nickname} Help:".format(**variables) embed.color = 0x00aa00 embed.set_footer( text="Requested by: {user_username}#{user_discrim} ({user_id})".format( **variables ) ) # Command description embed.add_field( name="Command Description:", value=" ".join( cmd_config["info"] ).format( **variables ).replace( "& &", "" ), inline=False ) # Command syntax embed.add_field( name="Command Syntax:", value="```" + " ".join( cmd_config["syntax"] ).format( **variables ).replace( "& &", "" ) + "```", inline=False ) # Check if user permissions are bypassed if not bypass_user_perms: # Ensure that the permissions didn't return `None` if user_perms: # Permissions that the user needs to have embed.add_field( name="Required User Permissions:", value="Green indicates that the permission requirement is met, red indicates it is not met.\n```diff\n{}\n```".format(user_perms), inline=False ) # Check if we are adding bot permissions if user_level >= 1: # Ensure that the permissions didn't return `None` if bot_perms: embed.add_field( name="Required Bot Permissions:", value="Green indicates that the permission requirement is met, red indicates it is not met.\n```diff\n{}\n```".format(bot_perms), inline=False ) # Can the command be ran in Direct Messages embed.add_field( name="Allowed in DMs:", value=cmd_config["allow_DMs"], inline=True ) # Whether or not the requestee can run the command embed.add_field( name="Can Requestee Run It:", value=(user_level >= cmd_level), inline=True ) # Whether or not this command is bypassing user permissions embed.add_field( name="Bypasses User Permissions:", value=bypass_user_perms, inline=True ) # The internal permission level that the bot requires for the user embed.add_field( name="Permission Level:", value=cmd_level, inline=True ) # Check if there are actully any aliases before adding it if len(cmd_aliases): # A list of aliases that the command has embed.add_field( name="Aliases:", value=", ".join(cmd_aliases), inline=True ) # Alert user what plugin the command comes from embed.add_field( name="Plugin Name:", value=plugin.name, inline=True ) # Respond with the embed return event.msg.reply(embed=embed)
def messageinfo(self, event, mid): try: msg = Message.select(Message).where( (Message.id == mid) ).get() except Message.DoesNotExist: raise CommandFail('the id specified does not exist in our message database.') message_content = msg.content author_id = msg.author.id guild_id = msg.guild_id channel_id = msg.channel_id deleted = msg.deleted num_edits = msg.num_edits if num_edits > 0: num_edits_bool = True else: num_edits_bool = False discrim = str(msg.author.discriminator) # if len(str(cached_name[1])) != 4: # while len(str(temp_str)) < 4: # temp_str = '0' + str(temp_str) cached_name = str(msg.author.username) + '#' + str(discrim) avatar_name = msg.author.avatar content = [] embed = MessageEmbed() member = event.guild.get_member(author_id) if not avatar_name: if member: avatar = default_color(str(member.user.default_avatar)) else: avatar = None elif avatar_name.startswith('a_'): avatar = u'https://cdn.discordapp.com/avatars/{}/{}.gif'.format(author_id, avatar_name) else: avatar = u'https://cdn.discordapp.com/avatars/{}/{}.png'.format(author_id, avatar_name) if member: embed.set_author(name='{} ({})'.format(member.user, member.id), icon_url=avatar) embed.set_thumbnail(url=avatar) else: if avatar: embed.set_author(name='{} ({})'.format(cached_name, author_id), icon_url=avatar) embed.set_thumbnail(url=avatar) else: embed.set_author(name='{} ({})'.format(cached_name, author_id)) # embed.title = "Message Content:" content.append(u'**\u276F Message Information:**') content.append(u'In channel: <#{}>'.format(channel_id)) content.append(u'Edited: **{}**'.format(num_edits_bool)) if deleted: content.append(u'Deleted: **{}**'.format(deleted)) content.append(u'Content: ```{}```'.format(message_content)) if member: content.append(u'\n**\u276F Member Information**') if member.nick: content.append(u'Nickname: {}'.format(member.nick)) content.append('Joined: {} ago ({})'.format( humanize.naturaldelta(datetime.utcnow() - member.joined_at), member.joined_at.isoformat(), )) if member.roles: roles = [] for r in member.roles: roles.append(member.guild.roles.get(r)) roles = sorted(roles, key=lambda r: r.position, reverse=True) total = len(member.roles) roles = roles[:20] content.append(u'Roles ({}): {}{}'.format( total, ' '.join(r.mention for r in roles), ' (+{})'.format(total-20) if total > 20 else '' )) embed.description = '\n'.join(content) # embed.url = 'https://discordapp.com/channels/{}/{}/{}'.format(guild_id, channel_id, mid) embed.timestamp = datetime.utcnow().isoformat() if not event.author.avatar: auth_avatar = default_color(str(member.user.default_avatar)) elif event.author.avatar.startswith('a_'): auth_avatar = u'https://cdn.discordapp.com/avatars/{}/{}.gif'.format(event.author.id, event.author.avatar) else: auth_avatar = u'https://cdn.discordapp.com/avatars/{}/{}.png'.format(event.author.id, event.author.avatar) embed.set_footer(text='Requested by {}#{} ({})'.format(event.author.username, event.author.discriminator, event.author.id), icon_url=auth_avatar) try: embed.color = get_dominant_colors_user(member.user, avatar) except: embed.color = '00000000' event.msg.reply('', embed=embed)
class FFmpegInput(BaseInput, AbstractOpus): def __init__(self,source = "",**kwargs): #for key,data in kwargs.items(): # setattr(self,key,data) super(FFmpegInput, self).__init__() self.command = "ffmpeg" self.source = source for key,data in kwargs.items(): setattr(self,key,data) self.about = {} for key in [u"pid",u"guild_id",u"channel_id",u"user_id",u"artist",u"title",u"duration",u"filesize_mb"]: self.about.update({key:getattr(self,key,None)}) try: self.about['filesize_mb'] = getattr(self,u'filesize',0) / 1024 / 1024 except: self.about['filesize_mb'] = 0 for key in self.about.keys(): try: if type(self.about[key]) in [int,bool]: self.about[key] = unicode(self.about[key]) elif type(self.about[key]) in [str]: self.about[key] = unicode(self.about[key],"utf-8") else: self.about[key] = unicode(self.about[key]) except Exception as error: self.about[key] = u"{}".format(error) self.process = None self.stream = 1 self.proc_working = False self.played = 0.0 self.vote_users = [] self.error = None self.build_embed() self.build_error_embed() self.cmd_args = self.build_cmd() def build_error_embed(self): self.error_embed = MessageEmbed() self.error_embed.set_author(name = u'Retarded Magnitola Play Error Header',icon_url = u'https://cdn.discordapp.com/attachments/499206696657223680/499206822045941780/run.gif') self.error_embed.title = u'FFMPEG returned error' self.error_embed.set_footer(text='Powered RetardBot Engine | https://discord.gg/tG35Y4b | gsd#6615') return True def build_embed(self): self.embed = MessageEmbed() self.embed.set_author(name = u'Retarded Magnitola', url=u'https://vk.cc/7kdHoP',icon_url = u'https://cdn.discordapp.com/attachments/499206696657223680/499206798851440641/kekbi.gif') self.embed.title = u'Now play:' self.embed.url = self.source self.embed.add_field(name = u'Time:', value = u'{}'.format(sectohum(seconds=int(self.duration))),inline=True) self.embed.add_field(name = u'Bass:', value = u'{} dB'.format(self.bass.value),inline=True) self.embed.add_field(name = u'Request:', value = u'<@!{}>'.format(self.user_id),inline=True) self.embed.add_field(name = u'Channel:', value = u'<#{}>'.format(self.channel_id),inline=True) self.embed.add_field(name = u'Replay:', value = u'{}'.format(getattr(self,"replay",False)),inline=True) self.embed.description = u'Title: {}\nAuthor: {}'.format(self.title,self.artist) self.embed.set_footer(text='Powered RetardBot Engine | https://discord.gg/tG35Y4b | gsd#6615') return True def build_cmd(self): player_args = [] net_source_args = ['-reconnect','1','-reconnect_at_eof', '1','-reconnect_streamed','1','-reconnect_delay_max','3000'] other_args = ['-vn','-f','s16le','-ar', getattr(self,"sampling_rate",48000),'-ac', getattr(self,"channels",2),'-af','bass=g={}'.format(getattr(getattr(self,"bass",None),"value",0))] if getattr(self,u"live_stream",False): player_args.append(u"python") player_args.append(u"./stream_support.py") player_args.append(self.source) else: player_args.append(self.command) if getattr(self,u"replay",False): player_args.append(u"-stream_loop") player_args.append(u"-1") if not getattr(self,u"local_file",False): player_args += net_source_args player_args.append(u"-i") player_args.append(self.source) player_args += other_args if getattr(self,"abdulov",False): player_args[len(player_args)-1] += ",rubberband=pitch=0.8,rubberband=tempo=1.2,volume=1.5" player_args.append("-loglevel") player_args.append("error") player_args.append("pipe:1") return [str(i) for i in player_args] def killed(self): self.stream = 0 self.proc_working = False try: self.process.kill() except: pass return True def read(self,chunk_size = 4096): return self.process.stdout.read(chunk_size) def fileobj(self): if getattr(self,"streaming",False): return self.process.stdout else: return self
def update_messages(self, only_current_player = False): player_list = self.print_player_list() for player in ([self.current_turn] if only_current_player else self.players): embed = MessageEmbed() embed.description = self.log_message embed.set_thumbnail(url="https://cdn.discordapp.com/emojis/{}.png?v=1".format(self.pile.top_card.emoji_id)) embed.set_author(name="Uno", icon_url="https://cdn.discordapp.com/emojis/{}.png?v=1".format( bot_config.uno_emojis['uno'].split(':')[1])) embed.set_footer(text=player.user, icon_url=player.user.avatar_url) embed.add_field(name="Players", value=player_list) embed.add_field(name="Pile", value= "<:" + bot_config.uno_emojis['uno'] + ">" + str(self.pile.top_card) + "\n\n") if len(self.current_turn.queue) > 0: embed.add_field(name="Play?", value= ''.join(str(x) for x in self.current_turn.queue) + "\n\n") elif self.current_turn.choosingColor: embed.add_field(name="Choose Color", value="{}Red {}Yellow {}Green {}Blue\n\n".format("1⃣","2⃣","3⃣","4⃣")) rows = ceil(len(player.hand) / 12) emotes = [ "<:blank:594342155565400114>", "\U000025c0", "1⃣", "2⃣", "3⃣", "4⃣", "5⃣", "6⃣", "\U000025b6", ] emojis = [] if not player.turnOver: start = max(0, min(player.page * 6, len(player.hand) - 6)) end = start + 5 legalCards = player.getLegalCards() index = 0 for card in player.hand: if index < (start - 1): emojis.append(emotes[0]) elif index < start: emojis.append(emotes[1]) elif index <= end: emojis.append(emotes[index-start+2]) elif index <= (end + 1): emojis.append(emotes[8]) else: emojis.append(emotes[0]) index += 1 else: for card in player.hand: emojis.append(emotes[0]) embed.add_field(name=player.user.username + "'s Hand", value=''.join(emojis[0:12]) + "\n" + self.print_hand_menu(player, 0)) for x in range(ceil(len(player.hand) / 12)): if x == 0: continue embed.add_field(name=''.join(emojis[(12 * x):(12 * (x + 1))]), value=self.print_hand_menu(player, x)) if player.hint != "": embed.add_field(name="Hint", value=player.hint) player.message.edit('', embed=embed)
class RaidPlugin(Plugin): """Disco plugin holding all of the commands related to Destiny 2 raids""" raidtime = arrow.get() israidset = False killthreads = False raiders = [] timer15triggered = False @Plugin.command('show', group='event') def command_raid(self, event): """Show the current raid, if it is set""" if self.israidset: self.eventEmbed.fields[1].value = self.get_raiders_string(event) self.eventEmbed.fields[0].value = self.eventTime self.eventEmbed.set_footer( text="Total Members: {}".format(len(self.raiders))) # event.msg.reply("Current raid: {} ({})\nRaid members: {}" #.format(arrow.get(self.raidtime).humanize(), # self.raidtime.strftime("%a, %I:%M %p %Z"), # self.get_raiders_string(event))) event.msg.reply(embed=self.eventEmbed) else: event.msg.reply("No event set") @Plugin.command('new', '<rtime:str> <eventTitle:str...>', group='event') def command_new(self, event, rtime, eventTitle): """Set up a new raid, passing in time via argument to the bot""" # some stuff to do before we start guild = event.msg.guild # we now have a list of every emoji in the server, use str() to convert to format you can send via message self.guildEmojis = list(guild.emojis.values()) # print(self.guildEmojis) if self.israidset: event.msg.reply('There is already an event set!') return parsed = dateparser.parse(rtime, settings={ 'TIMEZONE': 'Europe/London', 'TO_TIMEZONE': 'Europe/London', 'RETURN_AS_TIMEZONE_AWARE': True }) if eventTitle is "": eventTitle = "New Event" eventDesc = "`@Destinybot event add` to add up" if not parsed: event.msg.reply('Could not detect the time, please try again') return timeNow = datetime.now(timezone.utc).astimezone( pytz.timezone('Europe/London')) if parsed < timeNow: parsed = parsed + timedelta(days=1) self.raidtime = arrow.get(parsed) self.israidset = True self.killthreads = False timer_now = Thread(target=self.raidtimer_now, args=(event, )) timer_15 = Thread(target=self.raidtimer_15, args=(event, )) timer_now.start() timer_15.start() # event.msg.reply('Event Created! {0}: '.format(eventTitle) + parsed.strftime("%A at %I:%M %p %Z")) self.eventEmbed = MessageEmbed(title=eventTitle, description=eventDesc, color=3447003) self.eventTime = parsed.strftime("%A at %I:%M %p %Z") self.eventTitle = eventTitle self.eventEmbed.add_field(name="Time", value=self.eventTime, inline=False) # save all this stuff as a attribute of the plugin so we can access it in 'show' and other functions self.eventEmbed.add_field(name="Members", value=self.get_raiders_string(event), inline=False) self.eventEmbed.set_footer( text="Total Members: {}".format(len(self.raiders))) # message = Message(embeds=list(embed)) event.msg.reply(embed=self.eventEmbed) @Plugin.command('edit', '<rtime:str...>', group='event') def command_edit(self, event, rtime): """Edit the existing raid, passing in via argument to the bot""" if not self.israidset: event.msg.reply('There is no event to edit!') return parsed = dateparser.parse(rtime, settings={ 'TIMEZONE': 'Europe/London', 'TO_TIMEZONE': 'Europe/London', 'RETURN_AS_TIMEZONE_AWARE': True }) if not parsed: event.msg.reply('Could not detect the time, please try again') return self.raidtime = arrow.get(parsed) self.eventTime = parsed.strftime("%A at %I:%M %p %Z") # if the 15 minute timer triggered, and there's more than 15 minutes left, restart it diff = self.raidtime - arrow.now(tz='Europe/London') if self.timer15triggered and diff.seconds / 60 > 15: timer_15 = Thread(target=self.raidtimer_15, args=(event, )) timer_15.start() self.timer15triggered = False event.msg.reply('Current event time changed to: ' + parsed.strftime("%A at %I:%M %p %Z")) @Plugin.command('clear', group='event') def command_clear(self, event): """Reset the current raid""" self.raid_clear(event) event.msg.reply('The current event has been cleared') @Plugin.command('add', group='event') def command_add(self, event): """Adds the user to the raid group""" if not self.israidset: event.msg.reply('There is currently no event set, ' + event.msg.author.username + '!') return if event.msg.author in self.raiders: event.msg.reply('You\'re already in the event, ' + event.msg.author.username + '!') return self.raiders.append(event.msg.author) event.msg.reply('You have joined the event, {}! ({} total)'.format( event.msg.author.username, len(self.raiders))) @Plugin.command('remove', group='event') def command_remove(self, event): """Removes the user from the raid group""" if not self.israidset: event.msg.reply('There is currently no event set, ' + event.msg.author.username + '!') return self.raiders.remove(event.msg.author) event.msg.reply('You have been removed from the event, ' + event.msg.author.username) def raidtimer_now(self, event): """When there's 30 seconds left, mention the raidgroup and reset the raid""" while True: if self.killthreads: break diff = self.raidtime - arrow.now(tz='Europe/London') if diff.seconds <= 30: raidgroup = "" for members in self.raiders: raidgroup += members.mention + ", " # raidstartEmbed = MessageEmbed(title=self.eventEmbed.title + "starting now!", description=raidgroup.rstrip(', ')) event.msg.reply('"{}" starting now! '.format( self.eventEmbed.title.rstrip(' ')) + raidgroup.rstrip(', ')) # event.msg.reply(embed=raidstartEmbed) self.raid_clear(event) break time.sleep(10) def raidtimer_15(self, event): """When there's 15 minutes left, mention the raidgroup""" while True: if self.killthreads: break diff = self.raidtime - arrow.now(tz='Europe/London') minutes = diff.seconds / 60 if minutes <= 15: raidgroup = "" for members in self.raiders: raidgroup += members.mention + ", " event.msg.reply('"{}" starting in 15 minutes! '.format( self.eventEmbed.title.rstrip(' ')) + raidgroup.rstrip(', ')) self.timer15triggered = True break time.sleep(30) def raid_clear(self, event): """Reset the state of raid""" self.raidtime = arrow.get() self.israidset = False self.killthreads = True self.timer15triggered = False self.raiders = [] def get_raiders_string(self, event): """Gets all raid member's usernames in a single string""" if len(self.raiders) <= 0: return "None" raidmembers = "" for member in self.raiders: # discord markdown for one line codeblock raidmembers += "`{}` ".format(member.username) return raidmembers.rstrip(' ') # def get_random_teams(self, event): # pass # def start_draft(self, event): # pass @Plugin.command('random', '[team1:str] [team2:str]', group='draft') def get_random_teams(self, event, team1="Team A", team2="Team B"): """Randomly drafts players added to the event in to two teams""" team_dict = {team1: [], team2: []} player_list = self.raiders print(player_list) random.shuffle(player_list) index = 0 for player in player_list: is_odd = index % 2 if is_odd: team_dict[team1].append(player.username) else: team_dict[team2].append(player.username) index += 1 self.teamEmbed = MessageEmbed( title="**Teams have been randomly assigned!**", description="", color=3447003) team1Str = "" team2Str = "" team1PlayerStr = "" team2PlayerStr = "" for count in range(0, len(self.guildEmojis)): if team1 in self.guildEmojis[count].name: # + " **VS**" #make it so the emoji prepends the team name team1Str = str(self.guildEmojis[count]) + " " + team1 if team1Str == "": team1Str = team1 for count in range(0, len(self.guildEmojis)): if team2 in self.guildEmojis[count].name: # + " " + #make it so the emoji is after the team name team2Str = str(self.guildEmojis[count]) + " " + team2 if team2Str == "": team2Str = team2 for each in team_dict[team1]: team1PlayerStr = team1PlayerStr + "`" + each + "`" + " " for each in team_dict[team2]: team2PlayerStr = team2PlayerStr + "`" + each + "`" + " " team1PlayerStr.rstrip(" ") team2PlayerStr.rstrip(" ") if not team1PlayerStr: team1PlayerStr = "None" if not team2PlayerStr: team2PlayerStr = "None" self.teamEmbed.add_field(name=team1Str, value=team1PlayerStr, inline=False) self.teamEmbed.add_field(name="\u2063", value="__**VS**__", inline=False) self.teamEmbed.add_field(name="\u2063", value="\u2063", inline=False) self.teamEmbed.add_field(name=team2Str, value=team2PlayerStr, inline=False) event.msg.reply(embed=self.teamEmbed) @Plugin.command('show', group='draft') def show_draft(self, event): """Show the last created draft""" temp_embed = self.teamEmbed temp_embed.title = "Current Teams" event.msg.reply(embed=temp_embed) @Plugin.command('clear', group='draft') def clear_draft(self, event): """Clears the last created draft""" temp_embed = self.teamEmbed temp_embed.title = "Current Teams" event.msg.reply(embed=temp_embed) def start_cm_draft(self, event, teams, captains): pass