async def role_templateadmin_set(self, ctx, role=None): m = re.match('<@&(\d+)>', role) r = dget(ctx.guild.roles, id=int(m.group(1))) if m else dget(ctx.guild.roles, name=role) if r: sql.guild_update(ctx.guild.id, template_admin=r.id) await ctx.send(ctx.s("configuration.role_template_admin_set").format(r.name)) else: await ctx.send(ctx.s("configuration.role_not_found"))
async def autoscan(ctx): if ctx.guild and not sql.guild_is_autoscan(ctx.guild.id): return canvas = sql.guild_get_canvas_by_id( ctx.guild.id) if ctx.guild else "pixelcanvas" cmd = None view = "" m_pc = re.search('pixelcanvas\.io/@(-?\d+),(-?\d+)(?:(?: |#| #)(-?\d+))?', ctx.message.content) m_pz = re.search( 'pixelzone\.io/\?p=(-?\d+),(-?\d+)(?:,(\d+))?(?:(?: |#| #)(-?\d+))?', ctx.message.content) m_ps = re.search( 'pxls\.space/#x=(\d+)&y=(\d+)(?:&scale=(\d+))?(?:(?: |#| #)(-?\d+))?', ctx.message.content) m_pre_def = re.search('@(-?\d+)(?: |,|, )(-?\d+)(?:(?: |#| #)(-?\d+))?', ctx.message.content) m_dif_def = re.search( '(?:(-l) )?(-?\d+)(?: |,|, )(-?\d+)(?:(?: |#| #)(-?\d+))?', ctx.message.content) if m_pc: cmd = dget(dget(ctx.bot.commands, name='preview').commands, name='pixelcanvas') view = ' '.join(m_pc.groups(default='1')) elif m_pz: cmd = dget(dget(ctx.bot.commands, name='preview').commands, name='pixelzone') view = '{} {} {}'.format(m_pz.group(1), m_pz.group(2), m_pz.group(4) or m_pz.group(3) or '1') elif m_ps: cmd = dget(dget(ctx.bot.commands, name='preview').commands, name='pxlsspace') view = '{} {} {}'.format(m_ps.group(1), m_ps.group(2), m_ps.group(4) or m_ps.group(3) or '1') elif m_pre_def: cmd = dget(dget(ctx.bot.commands, name='preview').commands, name=canvas) view = ' '.join(m_pre_def.groups(default='1')) elif m_dif_def and len( ctx.message.attachments ) > 0 and ctx.message.attachments[0].filename[-4:].lower() == ".png": cmd = dget(dget(ctx.bot.commands, name='diff').commands, name=canvas) view = '{} {} {} {}'.format( m_dif_def.group(1) or "", m_dif_def.group(2), m_dif_def.group(3), m_dif_def.group(4) or 1) if cmd: ctx.command = cmd ctx.view = StringView(view) ctx.is_autoscan = True await ctx.bot.invoke(ctx) return True
async def on_raw_reaction_add(self, payload): member = payload.member if payload.emoji.name == '✅' and not member.bot: channel = self.bot.get_channel(payload.channel_id) message = await channel.fetch_message(payload.message_id) reaction = dget(message.reactions, emoji=payload.emoji.name) role = dget(member.guild.roles, name='Member') if not role in member.roles: await member.add_roles(role) else: pass await reaction.remove(member)
async def autoscan(ctx): if not ctx.guild: return guild = ctx.session.query(Guild).get(ctx.guild.id) if not guild.autoscan: return canvas = guild.canvas if guild.canvas else "pixelcanvas" cmd = None g = None m_pc = re.search(r'pixelcanvas\.io/@(-?\d+),(-?\d+)(?:(?: |#| #)(-?\d+))?', ctx.message.content) m_pz = re.search( r'pixelzone\.io/\?p=(-?\d+),(-?\d+)(?:,(\d+))?(?:(?: |#| #)(-?\d+))?', ctx.message.content) m_ps = re.search( r'pxls\.space/#x=(\d+)&y=(\d+)(?:&scale=(\d+))?(?:(?: |#| #)(-?\d+))?', ctx.message.content) m_pre_def = re.search(r'@(-?\d+)(?: |,|, )(-?\d+)(?:(?: |#| #)(-?\d+))?', ctx.message.content) m_dif_def = re.search(r'(-?\d+)(?: |,|, )(-?\d+)(?:(?: |#| #)(-?\d+))?', ctx.message.content) if m_pc: cmd = dget(dget(ctx.bot.commands, name='preview').commands, name='pixelcanvas') g = m_pc.groups() elif m_pz: cmd = dget(dget(ctx.bot.commands, name='preview').commands, name='pixelzone') g = m_pz.groups() elif m_ps: cmd = dget(dget(ctx.bot.commands, name='preview').commands, name='pxlsspace') g = m_ps.groups() elif m_pre_def: cmd = dget(dget(ctx.bot.commands, name='preview').commands, name=canvas) g = m_pre_def.groups() elif m_dif_def and len( ctx.message.attachments ) > 0 and ctx.message.attachments[0].filename[-4:].lower() == ".png": cmd = dget(dget(ctx.bot.commands, name='diff').commands, name=canvas) g = m_dif_def.groups() if cmd: view = f"{g[0]} {g[1]} -z {g[2] if g[2] != None else 1}" ctx.command = cmd ctx.view = commands.view.StringView(view) ctx.is_autoscan = True await ctx.bot.invoke(ctx) return True
async def team(self, ctx): """Display your team""" # TODO jk = dget(ctx.guild.members, name="ThePianoDentist") await ctx.send( f'Hey {jk.mention}, {ctx.author.name} wants to see their team right about now!' )
async def alertchannel(self, ctx): guild = ctx.session.query(Guild).get(ctx.guild.id) channel = dget(ctx.guild.channels, id=guild.alert_channel) if channel: await ctx.send(ctx.s("configuration.alert_channel_current").format(channel.mention)) else: await ctx.send(ctx.s("configuration.alert_channel_none"))
def get_templateadmin_role(ctx): guild = ctx.session.query(Guild).get(ctx.guild.id) r = dget(ctx.guild.roles, id=guild.template_admin) if guild.template_admin and not r: guild.template_admin = None return None return r
async def mypronouns(self, ctx, selector: str = None): o = None op = 1 if "-" in selector: op = 0 selector = selector.replace("-", "") if selector is not None: member = ctx.message.author proles = {} g = ctx.guild guild_pronouns = self.pronoun_roles[str(g.id)] for r in guild_pronouns: p = guild_pronouns[r]["nom"] proles[p] = r gr = proles.get(selector, None) if gr is not None: try: role = dget(g.roles, id=int(gr)) if op: await member.add_roles(role) o = "%s have been added to your pronouns, %s" % (role.name, member.mention) else: await member.remove_roles(role) o = "%s have been removed from your pronouns, %s" % (role.name, member.mention) except Exception as e: print(e) o = "Hmm. I'm confused. Try again." else: o = "Hmm. I can't find that pronoun. Try again using the nominative pronoun on its own (i.e. she, they, he)." else: o = "Which pronouns did you want to set? Try using the nominative pronoun on its own (i.e she, they, he)." await ctx.send(o)
def get_botadmin_role(ctx): role_id = sql.guild_get_by_id(ctx.guild.id).bot_admin r = dget(ctx.guild.roles, id=role_id) if role_id and not r: sql.guild_update(ctx.guild.id, bot_admin=None) return None return r
def get_templateadder_role(ctx): role_id = sql.guild_get_by_id(ctx.guild.id).template_adder r = dget(ctx.guild.roles, id=role_id) if role_id and not r: sql.guild_update(ctx.guild.id, template_adder=None) return None return r
async def invoke_default(self, cmd: str): default_canvas = self.canvas cmds = cmd.split('.') self.command = dget(self.bot.commands, name=cmds[0]) self.view.index = 0 self.view.preview = 0 self.view.get_word() if len(cmds) > 1: for c in cmds[1:]: self.command = dget(self.command.commands, name=c) self.view.skip_ws() self.view.get_word() self.command = dget(self.command.commands, name=default_canvas) self.is_default = True if self.command is not None: await self.bot.invoke(self)
async def alertchannel(self, ctx): channel = dget(ctx.guild.channels, id=sql.guild_get_by_id(ctx.guild.id).alert_channel) if channel: await ctx.send("Alert channel is currently set to {0}.".format( channel.mention)) else: await ctx.send("No alert channel has been set.")
async def alertchannel(self, ctx): channel = dget(ctx.guild.channels, id=sql.guild_get_by_id(ctx.guild.id).alert_channel) if channel: await ctx.send( ctx.s("configuration.alert_channel_current").format( channel.mention)) else: await ctx.send(ctx.s("configuration.alert_channel_none"))
async def on_new_draft(self, drafts): """Create channels for drafts and add correct users if need to keep track of discord channel id -> draft id use send_update_drafts when know the channel ids. """ logger.info("FantasyBot: on new draft") # for guild in self.guilds: # TODO guild = self.get_guild(GUILD_ID) if guild is None: logger.error( f'FantasyBot:on_new_draft: cant find guild with id {GUILD_ID}') return for draft in drafts: logger.info( f'FantasyBot:on_new_draft: handling draft {draft["draft_id"]}') if draft['league_id'] != FANTASY_LEAGUE_ID: logger.error( f'FantasyBot:on_new_draft: unexpected league id {draft["league_id"]}' ) return overwrites = { guild.default_role: PermissionOverwrite(read_messages=False) } for team_draft in draft["team_drafts"]: member = guild.get_member(team_draft["meta"]["discord_id"]) if member is None: logger.error( f'FantasyBot:on_new_draft: failed to find member') # return continue overwrites[member] = PermissionOverwrite(read_messages=True) category = dget(guild.categories, name=CATEGORY_NAME) if category is None: logger.error( "FantasyBot:on_new_draft: failed to find catgeory") return logger.info( f'FantasyBot:on_new_draft: creating new channel for draft {draft["draft_id"]}' ) # TODO CT should go into the fantasydota category (or a drafts subcategory) new_channel = await guild.create_text_channel( f'draft {draft["draft_id"]}', overwrites=overwrites, category=category) self.fantasy_handler.draft_ids_to_channel_ids[ draft["draft_id"]] = new_channel.id self.fantasy_handler.channel_ids_to_draft_ids[ new_channel.id] = draft["draft_id"] await self.fantasy_handler.client.send_update_drafts([ DraftUpdate(draft["draft_id"], meta={'channel_id': new_channel.id}) ]) await new_channel.send(f'Welcome drafters!') await new_channel.send( self.fantasy_handler.future_draft_choices(draft["draft_id"]))
async def get_user_info(state, user_id): users = list(state._users.values()) user = dget(users, id=user_id) if not user: try: data = await state.http.get_user(user_id) except discord.NotFound: return None user = discord.User(state=state, data=data) return user
async def plays(ctx, *, query): FFMPEG_OPTS = {'before_options':'-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'} video, source = search(query) # guild = discord.utils.get(bot.guilds, name=GUILD) voice = dget(bot.voice_clients, guild=ctx.guild) #await join(ctx) #await ctx.send(f'Now playing {info['title']}.') voice.play(discord.FFmpegPCMAudio(source, **FFMPEG_OPTS), after=lambda e: print('done', e)) voice.is_playing()
async def delete_fantasydota_channels(self, ctx): """Delete all channels""" if not self.confirm_flag: await ctx.send("Are you sure? (type command again to confirm)") self.confirm_flag = True return category = dget(ctx.guild.categories, name=CATEGORY_NAME) for channel in category.channels: await channel.delete() await category.delete() await ctx.send("Finished cleaning. Bery nice.") self.confirm_flag = False
async def private_channel(self, ctx, name, *members): if len(members) == 0: await ctx.send("Please gimmie some members") return overwrites = {ctx.guild.default_role: PermissionOverwrite(read_messages=False)} for m in members: # who even likes comprehensions? member = dget(ctx.guild.members, name=m) if member: overwrites[member] = PermissionOverwrite(read_messages=True) if len(overwrites) == 0: await ctx.send("You didnt give me any valid members") return new_channel = await ctx.guild.create_text_channel(name, overwrites=overwrites) await ctx.send(f'Created new channel - {new_channel.name} some people who shall not be named because i cant be arse to implement it')
async def role_update(bot, config, sleep_time): await bot.wait_until_ready() while 1: try: leaderboard = get_leaderboard() guild = bot.get_guild(598903919602696202) players = leaderboard["players"] for member in guild.members: set_exit = 0 for role in member.roles: # If member has role Constant(743022066365890592) if role.id == 743022066365890592: set_exit = 1 break if set_exit: continue for player in players: selected_role = 743042483474268210 if int(player["id"]) == member.id: if player['xp'] > 15000 and player[ 'xp'] < 20000: # Рыцарь-Джедай (658687217694146590) selected_role = 658687217694146590 elif player['xp'] > 10000 and player[ 'xp'] < 15000: # Падаван(668752138998120448) selected_role = 668752138998120448 elif player['xp'] > 5000 and player[ 'xp'] < 10000: # Юнлинг(598907144607367199) selected_role = 598907144607367199 elif player['xp'] < 5000 and player[ 'xp'] > 100: # Пездюк(685921321082683525) selected_role = 685921321082683525 else: # TEST(743042483474268210) selected_role = 743042483474268210 role_exist = 0 for role in member.roles: if role.id == selected_role: role_exist = 1 break if not role_exist: await member.add_roles( dget(guild.roles, id=selected_role)) await asyncio.sleep(60) pass except: await asyncio.sleep(180)
async def on_ready(self): """Initial discord related set up TODO: - Do we need to worry about the below warning? Warning This function is not guaranteed to be the first event called. Likewise, this function is not guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails. """ logger.info("Cog: On Ready enter") for guild in self.bot.guilds: # TODO create method for this logger.info(f"Cog: Checking required channels for {guild.name}") category = dget(guild.categories, name=CATEGORY_NAME) if category: logger.info(f"Cog: Help category found") # For now just assume if catgeory is there we're done else: logger.info(f'Cog: Category not found - creating') # TODO force category at top? overwrites = { guild.default_role: PermissionOverwrite(send_messages=False), } new_category = await guild.create_category( CATEGORY_NAME, overwrites=overwrites) logger.info( f'Cog: New category created - adding and populating channels' ) for name in HELP_CHANNELS: new_channel = await guild.create_text_channel( name, category=new_category, overwrites=overwrites) await new_channel.send(HELP_CHANNELS[name]) logger.info( f'Cog: All help channels added and populated succsfully') for name in PRIVATE_CHANNELS: await guild.create_text_channel(name, category=new_category) overwrites = { guild.default_role: PermissionOverwrite(send_messages=True), } for name in PUBLIC_CHANNELS: await guild.create_text_channel(name, category=new_category, overwrites=overwrites) logger.info(f"Cog: All other channels created") logger.info("Cog On Ready leave")
async def replace_mentions(state, guild, content:str, limit:int=None): match = re.findall(r"(<@!?(\d+)>)", content) if match: if limit: match = match[limit:] for mention, i in match: user = await get_user_info(state, int(i)) if user is not None: content = content.replace(mention, f'@{user}') if guild: match = re.findall(r"(<@&(\d+)>)", content) if match: for mention, i in match: role = dget(guild.roles, id=int(i)) if role: content = content.replace(mention, f'@{role}') return content
async def is_blacklisted(self, message): guild = message.guild if guild and guild.me: perms = message.channel.permissions_for(guild.me) # no perms why bother if not perms.send_messages or not perms.read_messages: return True author = message.author if await self.bot.is_owner(author) or (guild and guild.owner_id == author.id): return False q = await self.query_blacklist(1, author.id) if q: return True if guild is None: return False if await self.is_off(guild.id, author.id): return True if isinstance(author, discord.Member): result = await self.query_blacklist(2, guild.id, single=False) if result: roles = [dget(guild.roles, id=x['role']) for x in result] for i, role in enumerate(roles): if role is None: await self.cursor.execute( f"DELETE FROM `except_blacklist` WHERE guild={guild.id} AND role={result[i]['role']}" ) return not any(x in roles for x in author.roles) q = await self.query_blacklist(3, guild.id, author.id) if q: return True q = await self.query_blacklist(4, message.channel.id) if q: return 'blacklist' not in message.content return False
async def on_init_leaderboards(self, leaderboards): """Init our leaderboards This should probably be in fantasydota cog seeing as that is where discordy stuff like printing output is supposed to happen. It's also where the leaderboard channels are created. OH YEAH... thought could have this here for now but channels wont even be made yet... """ logger.info("FantasyBot: on init leaderboards enter") # for guild in self.guilds: # TODO guild = self.get_guild(GUILD_ID) try: new_leaderboard = leaderboards[FANTASY_USER_LEADERBOARD_ID] new_pro_leaderboard = leaderboards[FANTASY_PLAYER_LEADERBOARD_ID] except KeyError: logger.error( f'FantasyBot:on_init_leaderboards: failed to find leaderboards' ) return leaderboard_channel = dget(guild.channels, name="leaderboard") pro_leaderboard_channel = dget(guild.channels, name="pro-leaderboard") if leaderboard_channel is None or pro_leaderboard_channel is None: logger.error( 'FantasyBot:on_init_leaderboards: failed to find leaderboard channels' ) return # stats here should be LatestStat objects but theyre not # (well really maybe they should be Stat objects but theyre definltey not them atm!) # Do user leaderboard data = [] # data = [{self.fantasy_handler.users[stat["player_id"]].meta["discord_id"]: stat["points"]} for stat in new_leaderboard.leaderboard] for stat in new_leaderboard.leaderboard: member_id = self.fantasy_handler.users[ stat["player_id"]].meta["discord_id"] member = guild.get_member(member_id) if member is None and DEV: Dummy = namedtuple("Dummy", "name") member = Dummy("tpain0") data.append({"name": member.name, "points": stat["points"]}) table = tabulate(sorted(data, key=lambda x: x["points"], reverse=True), headers="keys", tablefmt=LEADERBOARD_FORMAT) out = f'__**{new_leaderboard.name}**__\n```{table}```' await leaderboard_channel.purge() await leaderboard_channel.send(out) # Do player leaderboard data = [] for stat in new_pro_leaderboard.leaderboard: player_name = self.player_handler.player_id_to_names[ stat["player_id"]] data.append({"name": player_name, "points": stat["points"]}) table = tabulate(sorted(data, key=lambda x: x["points"], reverse=True), headers="keys", tablefmt=LEADERBOARD_FORMAT) out = f'__**{new_pro_leaderboard.name}**__\n```{table}```' await pro_leaderboard_channel.purge() await pro_leaderboard_channel.send(out)
def is_template_admin(ctx): role_id = sql.guild_get_by_id(ctx.guild.id).template_admin r = dget(ctx.author.roles, id=role_id) return bool(r)
def is_admin(ctx): role_id = sql.guild_get_by_id(ctx.guild.id).bot_admin r = dget(ctx.author.roles, id=role_id) return bool(r) or ctx.author.permissions_in(ctx.channel).administrator
def is_admin(ctx): guild = ctx.session.query(Guild).get(ctx.guild.id) r = dget(ctx.author.roles, id=guild.bot_admin) return bool(r) or ctx.author.permissions_in(ctx.channel).administrator
def is_template_adder(ctx): role_id = sql.guild_get_by_id(ctx.guild.id).template_adder r = dget(ctx.author.roles, id=role_id) return bool(not role_id or r)
def is_template_admin(ctx): guild = ctx.session.query(Guild).get(ctx.guild.id) r = dget(ctx.author.roles, id=guild.template_admin) return bool(r)
async def on_message(message): if message.author.bot: return ctx = await bot.get_context(message) if ctx.invoked_with: await bot.invoke(ctx) return if message.guild is not None and not message.channel.permissions_for(message.guild.me).send_messages: return if sql.select_guild_by_id(ctx.guild.id)['autoscan'] == 1: default_canvas = sql.select_guild_by_id(ctx.guild.id)['default_canvas'] if re.search('pixelcanvas\.io/@-?\d+,-?\d+', message.content) is not None: ctx.command = dget(dget(bot.commands, name='preview').commands, name='pixelcanvas') elif re.search('pixelz\.io/@-?\d+,-?\d+', message.content) is not None: ctx.command = dget(dget(bot.commands, name='preview').commands, name='pixelzio') elif re.search('pixelzone\.io/\?p=-?\d+,-?\d+', message.content) is not None: ctx.command = dget(dget(bot.commands, name='preview').commands, name='pixelzone') elif re.search('pxls\.space/#x=\d+&y=\d+', message.content) is not None: ctx.command = dget(dget(bot.commands, name='preview').commands, name='pxlsspace') elif re.search('@\(?-?\d+, ?-?\d+\)?', message.content) is not None: ctx.command = dget(dget(bot.commands, name='preview').commands, name=default_canvas) elif re.search('\(?-?\d+, ?-?\d+\)?', message.content) is not None and len(message.attachments) > 0 \ and message.attachments[0].filename[-4:].lower() == ".png": ctx.command = dget(dget(bot.commands, name='diff').commands, name=default_canvas) if ctx.command is not None: await bot.invoke(ctx)
def is_template_adder(ctx): guild = ctx.session.query(Guild).get(ctx.guild.id) role_id = guild.template_adder r = dget(ctx.author.roles, id=role_id) return bool(not role_id or r)