def gen_color(user_id): random.seed(user_id) c_r = random.randint(0, 255) c_g = random.randint(0, 255) c_b = random.randint(0, 255) return discord.Color((c_r << 16) + (c_g << 8) + c_b)
def getColor(): color = colorsys.hsv_to_rgb(getHue(), 1, 1) color = (round(color[0] * 255), round(color[1] * 255), round(color[2] * 255)) return discord.Color((color[0] << 16) + (color[1] << 8) + color[2])
def random_discord_color(): return discord.Color(value=randint(0, 16777215))
async def setprofile(self, ctx): """Creates a profile.""" if not ctx.guild: ctx.guild = self.bot.get_guild(690032997466243188) data = Handlers.Mongo.read() ctx.author = ctx.guild.get_member(ctx.author.id) if str(ctx.author.id) in data["sonas"]: return await ctx.send(self.bot.translate("SONA_EXISTS")) guild_config = self.config["guilds"][str(ctx.guild.id)] genderrole = list(guild_config["gender"]) orientationrole = list(guild_config["orientation"]) personalityrole = list(guild_config["personality"]) pingsettingsrole = list(guild_config["pingSettings"]) relationshiprole = list(guild_config["relationship"]) verificationrole = list(guild_config["verification"]) # for role in ctx.author.roles: # if not genderrole in ctx.author.roles: # return await ctx.send("You are missing your Gender role, visit the <#690055478796877890> channel.") # if not orientationrole in ctx.author.roles: # return await ctx.send("You are missing your Orientation role, visit the <#690055478796877890> channel.") # if not personalityrole in ctx.author.roles: # return await ctx.send("You are missing your Personality role, visit the <#690055478796877890> channel.") # if not pingsettingsrole in ctx.author.roles: # return await ctx.send("You are missing your Ping Settings role, visit the <#690055478796877890> channel.") # if not relationshiprole in ctx.author.roles: # return await ctx.send("You are missing your Relationship role, visit the <#690055478796877890> channel.") # if not verificationrole in ctx.author.roles: # return await ctx.send("You are missing your Verification role, visit the <#690055478796877890> channel.") try: ctx.channel = (await ctx.author.send(self.bot.translate("SONA_START") )).channel except: return await ctx.send(self.bot.translate("CLOSED_DMS")) def check(answer): return ctx.channel == answer.channel and ctx.author == answer.author def check2(reaction, user): return ctx.channel == reaction.message.channel and ctx.author == user answers = {} questions = self.questions # Verification Roles type = "Verification Roles" ver = [] for role in ctx.author.roles: if role.id in verificationrole: ver.append('<@&%s>' % role.id) if not ver: return await ctx.send( "You are missing your Verification role, visit the <#690055478796877890> channel." ) ver = str(ver) ver = ver.replace('[', '') ver = ver.replace(']', '') ver = ver.replace('\'', '') answers[type] = ver # Gender type = "Gender" ver1 = [] for role in ctx.author.roles: if role.id in genderrole: ver1.append('<@&%s>' % role.id) if not ver1: return await ctx.send( "You are missing your Gender role, visit the <#690055478796877890> channel." ) ver1 = str(ver1) ver1 = ver1.replace('[', '') ver1 = ver1.replace(']', '') ver1 = ver1.replace('\'', '') answers[type] = ver1 # Orientation type = "Orientation" ver2 = [] for role in ctx.author.roles: if role.id in orientationrole: ver2.append('<@&%s>' % role.id) if not ver2: return await ctx.send( "You are missing your Orientation role, visit the <#690055478796877890> channel." ) ver2 = str(ver2) ver2 = ver2.replace('[', '') ver2 = ver2.replace(']', '') ver2 = ver2.replace('\'', '') answers[type] = ver2 # Personality type = "Personality" ver3 = [] for role in ctx.author.roles: if role.id in personalityrole: ver3.append('<@&%s>' % role.id) if not ver3: return await ctx.send( "You are missing your Personality role, visit the <#690055478796877890> channel." ) ver3 = str(ver3) ver3 = ver3.replace('[', '') ver3 = ver3.replace(']', '') ver3 = ver3.replace('\'', '') answers[type] = ver3 # Ping Settings type = "Ping Settings" ver4 = [] for role in ctx.author.roles: if role.id in pingsettingsrole: ver4.append('<@&%s>' % role.id) if not ver4: return await ctx.send( "You are missing your Ping Settings role, visit the <#690055478796877890> channel." ) ver4 = str(ver4) ver4 = ver4.replace('[', '') ver4 = ver4.replace(']', '') ver4 = ver4.replace('\'', '') answers[type] = ver4 # Relationship type = "Relationship" ver5 = [] for role in ctx.author.roles: if role.id in relationshiprole: ver5.append('<@&%s>' % role.id) if not ver5: return await ctx.send( "You are missing your Relationship role, visit the <#690055478796877890> channel." ) ver5 = str(ver5) ver5 = ver5.replace('[', '') ver5 = ver5.replace(']', '') ver5 = ver5.replace('\'', '') answers[type] = ver5 # SFW or NSFW question = "Is your fursona's picture or bio NSFW?" type = "NSFW" answers[type] = False # embed = discord.Embed(color=discord.Color(0x7289DA)) # embed.description = question # message = await ctx.send(embed=embed) # await message.add_reaction("✅") # await message.add_reaction("🚫") # try: # reaction, user = await self.bot.wait_for("reaction_add", check=check2, timeout=1800) # except: # return await ctx.send(self.bot.translate("TIMED_OUT", ctx=ctx)) # if str(reaction) == "✅": # sfw_role = ctx.guild.get_role(self.config["guilds"][str(ctx.guild.id)]["sfw_role"]) # if sfw_role in ctx.author.roles: # return await ctx.send(self.bot.translate("NSFW_REQUIRED")) # answers[type] = True # elif str(reaction) == "🚫": # answers[type] = False # else: # return await ctx.send(self.bot.translate("INVALID_OPTION")) for type in questions: question = questions[type] embed = discord.Embed(color=discord.Color(0x7289DA)) embed.description = question await ctx.send(embed=embed) try: answer = await self.bot.wait_for("message", check=check, timeout=1800) except: return await ctx.send(self.bot.translate("TIMED_OUT", ctx=ctx)) answers[type] = str(answer.content) # Picture question = "Post a link of a picture you'd like to include with your profile or send the image. If you don't have one, say `None`." type = "Picture" embed = discord.Embed(color=discord.Color(0x7289DA)) embed.description = question await ctx.send(embed=embed) try: answer = await self.bot.wait_for("message", check=check, timeout=1800) except: return await ctx.send(self.bot.translate("TIMED_OUT", ctx=ctx)) if answer.attachments == []: answers[type] = str(answer.content) else: answers[type] = answer.attachments[0].url await ctx.send(self.bot.translate("SUBMIT_SUCCESS")) try: embed = discord.Embed(color=discord.Color( int(str(answers["Color"]).replace("#", ""), 16))) except: embed = discord.Embed(color=discord.Color(0x00ff7e)) embed.set_author(name=f"{ctx.author} | {str(ctx.author.id)}", icon_url=ctx.author.avatar_url) for question in answers: embed.add_field(name=question, value=answers[question]) embed.set_image(url=answers["Picture"]) embed.timestamp = ctx.message.created_at sona_queue_channel = ctx.guild.get_channel(self.config["guilds"][str( ctx.guild.id)]["sona_queue_channel"]) try: message = await sona_queue_channel.send("<@&690055427463053372>", embed=embed) except: embed.set_image( url= "https://media.discordapp.net/attachments/579350335059918858/587607748653350944/Seperate_1.gif" ) message = await sona_queue_channel.send("<@&690055427463053372>", embed=embed) reactions = ["⬆", "⬇", "✅", "🚫"] for reaction in reactions: await message.add_reaction(reaction)
async def userinfo(ctx, user: discord.Member): r, g, b = tuple(int(x * 255) for x in colorsys.hsv_to_rgb(random.random(), 1, 1)) embed = discord.Embed(title="{}'s info".format(user.name), description="Here's what I could find.", color = discord.Color((r << 16) + (g << 8) + b)) embed.add_field(name="Name", value=user.name, inline=True) embed.add_field(name="ID", value=user.id, inline=True) embed.add_field(name="Status", value=user.status, inline=True) embed.add_field(name="Highest role", value=user.top_role) embed.add_field(name="Joined", value=user.joined_at) embed.set_thumbnail(url=user.avatar_url) await client.say(embed=embed)
async def sync_setup(self, ctx): """Setup process for ingame ranks to discord member roles synchronization""" def check(m): return m.author == ctx.author and m.channel == ctx.channel if not ctx.guild.me.guild_permissions.manage_roles: await ctx.send( "I require the 'Manage Roles' permission to do this.") return doc = await self.bot.database.get_guild(ctx.guild, self) if not doc: await self.bot.database.set_guild(ctx.guild, { "sync.on": False, "sync.setupdone": False }, self) doc = await self.bot.database.get_guild(ctx.guild, self) enabled = self.sync_enabled(doc) if enabled: message = await ctx.send( "You have already ran setup on this guild before, continuing " "will reset existing settings and delete previously " "created roles, reply Yes to confirm.") try: answer = await self.bot.wait_for("message", timeout=30, check=check) except asyncio.TimeoutError: return await message.edit(content="No response in time") if answer.content.lower() != "yes": return else: await self.clearsync(ctx) message = await ctx.send( "Please type the name of the in-game guild you want to sync " "to into the chat now. Please ensure you respond with it " "exactly as it is in-game.") try: answer = await self.bot.wait_for("message", timeout=30, check=check) except asyncio.TimeoutError: return await message.edit(content="No response in time") scopes = ["guilds"] endpoint_id = "guild/search?name=" + answer.content.replace(' ', '%20') try: guild_id = await self.call_api(endpoint_id) guild_id = guild_id[0] endpoints = [ "guild/{}/members".format(guild_id), "guild/{}/ranks".format(guild_id) ] results, ranks = await self.call_multiple(endpoints, ctx.author, scopes) except (IndexError, APINotFound): return await ctx.send("Invalid guild name") except APIForbidden: return await ctx.send( "You need to have guild leader permissions ingame to be able " "to use this synchronization.") except APIKeyError: return await ctx.send( "You need to add an API key to your account first.") except APIError as e: return await self.error_handler(ctx, e) roles = {} for rank in ranks: try: role = await ctx.guild.create_role( name=rank["id"], reason="GW2Bot Sync Role [$guildsync]", color=discord.Color(self.embed_color)) roles[rank["id"]] = role.id except discord.Forbidden: return await ctx.send("Couldn't create role {0}".format( rank["name"])) await self.bot.database.set_guild( ctx.guild, { "sync.ranks": roles, "sync.leader": ctx.author.id, "sync.setupdone": True, "sync.on": True, "sync.gid": guild_id }, self) guidelines = ( "Guild sync requires leader permissions in game\n" "Guild sync is tied to your account. If you remove your API key, " "guild sync will break\n" "**Always ensure that GW2Bot is above the synced roles, or the " "bot won't be able to assign them**\n" "You can modify and change permissions of the roles created by " "the bot.\n" "Only server members with API key added to the bot will " "participate in the sync, and no input is required from them. " "New members which add their API key after sync is " "setup will also be synced automatically.\n" "Guild sync isn't instant - it can take even 30 minutes before " "your settings are synced. To force a sync, you can use " "**guildsync now**\n") await ctx.send( "Setup complete, you can toggle the synchronization on and off " "at any time with $guildsync toggle on/off. Now, some guidelines. " "In case of issues, refer to this message - you can also find it " "on the website https://gw2bot.info under FAQ") await ctx.send(guidelines) doc = await self.bot.database.get_guild(ctx.guild) await self.sync_guild_ranks(doc, True)
async def on_raw_reaction_add(self, payload): guild = self.bot.get_guild(payload.guild_id) emoji = payload.emoji try: channel = guild.get_channel(payload.channel_id) except: return message = await channel.fetch_message(payload.message_id) user = guild.get_member(payload.user_id) guild_config = self.config["guilds"][str(guild.id)] admin_role = guild.get_role(guild_config["admin_role"]) dev_role = guild.get_role(guild_config["dev_role"]) sona_queue_channel = guild.get_channel( guild_config["sona_queue_channel"]) sona_approved_channel = guild.get_channel( guild_config["sona_approved_channel"]) sona_denied_channel = guild.get_channel( guild_config["sona_denied_channel"]) if user.bot: return if not message.channel == sona_queue_channel: return if not admin_role in user.roles and not dev_role in user.roles: return embed = message.embeds[0] member = guild.get_member(int(embed.author.name.split(" | ")[-1])) #print(member) if str(emoji) == "✅": data = Handlers.Mongo.read() answers = {} for field in embed.fields: answers[str(field.name)] = str(field.value) if answers["NSFW"] == "True": answers["NSFW"] = True else: answers["NSFW"] = False if answers["About"] == "None": answers["About"] = None if answers["Color"] == "None": answers["Color"] == "#00FF7E" data["sonas"][str(member.id)] = answers Handlers.Mongo.save(data) #print(answers) try: await member.send(self.bot.translate("APPROVED_SONA")) except: pass embed.color = discord.Color(0x00ce75) embed.set_footer(text=f"Approved by {user}.") await sona_approved_channel.send(embed=embed) return await message.delete() elif str(emoji) == "🚫": question = await sona_queue_channel.send( self.bot.translate("DENY_SONA", user=user)) def check(reason): return sona_queue_channel == reason.channel and user == reason.author try: reason = await self.bot.wait_for("message", check=check, timeout=300) except: return await question.delete() await question.delete() await reason.delete() embed.color = discord.Color(0xff3f3f) embed.set_footer(text=f"Denied by {user}.") embed.add_field(name="Reason", value=reason.content) try: await member.send( self.bot.translate("DENIED_SONA", reason=reason.content)) except: pass await sona_denied_channel.send(embed=embed) return await message.delete()
async def info(ctx): """Get infomation about the selfbot""" color = discord.Color(value=0x00ff00) em = discord.Embed(color=color, title='Infomation:') em.description = f"**Creator:** L3NNY#0849\n**Ping:**{bot.latency * 1000:.4f}\n**Servers you are in:** {len(bot.guilds)}" await ctx.send(embed=em)
def __init__(self, name, color, channel_id, time, every_x_hours): self.name = name self.color = discord.Color(int(color, 0)) self.channel_id = channel_id self.time = int(time) self.every_x_hours = int(every_x_hours)
async def ping(ctx): """Get the bot's Websocket latency.""" color = discord.Color(value=0x00ff00) em = discord.Embed(color=color, title='Pong! Websocket Latency:') em.description = f"{bot.latency * 1000:.4f} ms" await ctx.send(embed=em)
async def support(ctx): """Get help with the selfbot""" color = discord.Color(value=0x00ff00) em = discord.Embed(color=color, title='Need help? Join!') em.description = f"https://discord.gg/FEPNu3A" await ctx.send(embed=em)
async def bump(self, ctx): guild = ctx.guild if not db.exists(guild): ctx.command.reset_cooldown(ctx) return await ctx.send(embed=discord.Embed( description= f"{emoji('cross')} This server seems to not exist in the Database! Use `=setup`!", color=discord.Color.red())) invchannel, description, color = db.get(guild)["fetch_invite"], db.get( guild)["description"], db.get(guild)["color"] try: invite = await ctx.guild.get_channel(invchannel).create_invite( max_uses=0, temporary=False, max_age=0, unique=False) except Exception as e: ctx.command.reset_cooldown(ctx) return await ctx.send(embed=discord.Embed( description= f"{emoji('cross')} Cannot fetch invite! Please review the following error, and if you can't solve it, please contact the developers in the [Support Server](https://discord.gg/r2rAUJZ)!", color=discord.Color.red()).add_field(name="Exception", value=f"```{e}```")) embed = discord.Embed(title=guild.name, description=description, color=discord.Color(value=color), url=invite.url) embed.add_field(name="👑 **Owner**", value=guild.owner.name) embed.add_field(name=f"{emoji('boost')} **Boosts**", value=guild.premium_subscription_count) embed.add_field(name=f"{emoji('online')} **Members**", value=len(guild.members)) embed.add_field(name=f"{emoji('emojis')} **Emojis**", value=f"{len(guild.emojis)}/{guild.emoji_limit}") embed.add_field(name=f"{emoji('region')} **Region**", value=str(guild.region).capitalize()) embed.add_field(name=f"{emoji('ccheck')} **Join**", value=f"**[Join {guild.name}!]({invite.url})**") embed.set_thumbnail(url=guild.icon_url_as(static_format="png")) embed.set_footer(text="Powered by • BytesBump") msg = await ctx.send(embed=discord.Embed( description= f"{emoji('loading')} **Bumping your server...!**\nThis might take some time, so don't worry!", color=discord.Color.orange())) success, fail = 0, 0 channels = [ i["listing"] for i in db.get_all() if not i["listing"] == None ] for channel in channels: try: await asyncio.sleep(0.3) await self.bot.get_channel(channel).send(embed=embed) success += 1 except: try: temp = self.bot.get_guild( db.find({"listing": channel})["_id"]) db.delete(temp) except: return db.delete(db.find({"listing": channel})["_id"]) await temp.owner.send(embed=discord.Embed( title=f"{emoji('warn')} ATTENTION REQUIRED {emoji('warn')}", description= f"The bot cannot find or send messages in your listing channel, therefore we have removed your server ({temp.name}) from the Database! Run `=setup` again to set it up!", color=discord.Color.red())) fail += 1 await msg.edit(embed=discord.Embed( title=f"{emoji('ccheck')} Guild Bumped!", description= f"Your server was successfully bumped to `{success}` guilds! There were {fail} errors encountered on guilds, and they were removed from the database!", color=discord.Color.green())) await asyncio.sleep(60) await msg.edit(embed=discord.Embed( title="BytesBump | Promotional", description=Files.read("Admin/Messages/promotional.txt"), color=discord.Color.green()))
async def help(self, ctx, *, arg=None): """ Shows the help message. :Usage=$help `[inquiry]` :Param=inquiry - the name of a command or command category. If none is provided, all categories are shown. """ if arg is None: embed = discord.Embed(title="Help", color=discord.Color(0xB565D9), description=f"Run `{config.command_prefix}help category` to list commands from " f"that category.") for c in self.bot.cogs.values(): if self.showcog(c): if not c.description: c.description = "No Description." embed.add_field(name=c.qualified_name, value=c.description) await ctx.reply(embed=embed) # if the command argument matches the name of any of the cogs that contain any not hidden commands elif arg.lower() in [c.lower() for c, v in self.bot.cogs.items() if self.showcog(v)]: cogs_lower = {k.lower(): v for k, v in self.bot.cogs.items()} cog = cogs_lower[arg.lower()] embed = discord.Embed(title=cog.qualified_name, description=cog.description + f"\nRun `{config.command_prefix}help command` for " f"more information on a command.", color=discord.Color(0xD262BA)) for cmd in sorted(cog.get_commands(), key=lambda x: x.name): if not cmd.hidden: desc = cmd.short_doc if cmd.short_doc else "No Description." embed.add_field(name=f"{config.command_prefix}{cmd.name}", value=desc) await ctx.reply(embed=embed) # elif arg.lower() in [c.name for c in self.bot.commands]: else: for all_cmd in self.bot.commands: if (all_cmd.name == arg.lower() or arg.lower() in all_cmd.aliases) and not all_cmd.hidden: cmd: discord.ext.commands.Command = all_cmd break else: await ctx.reply( f"{config.emojis['warning']} `{arg}` is not the name of a command or a command category!") return embed = discord.Embed(title=config.command_prefix + cmd.name, description=cmd.cog_name, color=discord.Color(0xEE609C)) if cmd.help: fields = {} fhelp = [] for line in cmd.help.split("\n"): if line.startswith(":"): if line.split("=")[0].strip(":") in fields: fields[line.split("=")[0].strip(":")] += "\n" + "=".join(line.split("=")[1:]) else: fields[line.split("=")[0].strip(":")] = "=".join(line.split("=")[1:]) else: fhelp.append(line) fhelp = "\n".join(fhelp) embed.add_field(name="Command Information", value=fhelp.replace("m.", config.command_prefix), inline=False) for k, v in fields.items(): if k == "Param": k = "Parameters" embed.add_field(name=k, value=v.replace("m.", config.command_prefix), inline=False) else: embed.add_field(name="Command Information", value="This command has no information.") if cmd.aliases: embed.add_field(name="Aliases", value=", ".join([config.command_prefix + a for a in cmd.aliases])) await ctx.reply(embed=embed)
async def clans(self, ctx, *args): """Display clan info. [p]clans -m Disable member count [p]clans -t Disable clan tag """ await self.bot.type() config = self.clans_config clan_tags = [clan.tag for clan in config.clans] use_cache = False clans = [] try: clans = await self.get_clans(clan_tags) dataIO.save_json(CACHE, clans) except json.decoder.JSONDecodeError: use_cache = True except asyncio.TimeoutError: use_cache = True if use_cache: data = dataIO.load_json(CACHE) clans = data await self.bot.say("Cannot load from API. Loading info from cache." ) em = discord.Embed(title=config.name, description=config.description, color=discord.Color(int(config.color, 16))) badge_url = None show_member_count = "-m" not in args show_clan_tag = "-t" not in args for clan in clans: desc = clan.get('description') match = re.search('[\d,O]{4,}', desc) pb_match = re.search('PB', desc) name = clan.get('name') if match is not None: trophies = match.group(0) trophies = trophies.replace(',', '') trophies = trophies.replace('O', '0') trophies = '{:,}'.format(int(trophies)) else: trophies = clan.required_score pb = '' if pb_match is not None: pb = ' PB' member_count = '' if show_member_count: member_count = ', {} / 50'.format(len(clan.get('members'))) clan_tag = '' if show_clan_tag: clan_tag = ', {}'.format(clan.get('tag')) value = '`{trophies}{pb}{member_count}{clan_tag}`'.format( clan_tag=clan_tag, member_count=member_count, trophies=trophies, pb=pb) em.add_field(name=name, value=value, inline=False) if badge_url is None: badge_url = clan['badge']['image'] if badge_url is not None: em.set_thumbnail(url=badge_url) for inf in config.info: em.add_field(name=inf.name, value=inf.value) await self.bot.say(embed=em)
async def cocprofile(self, ctx, coctag=None): '''Gets a Clash of Clans profile! Yay!''' if coctag is None: coctag = await self.get_tag(ctx.author.id) if not coctag: return await ctx.send("Oops, looks like you don't have a saved tag yet! Use `*cocsave [tag]` to save your tag to your Discord profile.") coctag = coctag.strip('#').replace("O", "0") coctag = coctag.upper() else: coctag = coctag.strip('#').replace("O", "0") coctag = coctag.upper() resp = await self.session.get(f'https://api.clashofclans.com/v1/players/%23{coctag}', headers=self.client) resp = await resp.json() color = discord.Color(value=0xe5f442) try: resp['name'] except KeyError: return await ctx.send("Invalid COC tag. Please check your tag!") em = discord.Embed(color=color, title=f"{resp['name']}, {resp['tag']}") em.add_field(name="Home Base", value=self.emoji(f"th{resp['townHallLevel']}"), inline=False) em.add_field(name='XP Level', value=resp['expLevel']) em.add_field(name='Trophies', value=resp['trophies']) try: leaguename = resp['league']['name'] except KeyError: leaguename = 'Unranked' em.add_field(name='League', value=leaguename) em.add_field(name='Best Trophies', value=resp['bestTrophies']) em.add_field(name='Town Hall', value=resp['townHallLevel']) em.add_field(name='Attack Wins', value=resp['attackWins']) em.add_field(name='Defense Wins', value=resp['defenseWins']) em.add_field(name='Donations', value=resp['donations']) em.add_field(name='Donations Received', value=resp['donationsReceived']) em.add_field(name='War Stars', value=resp['warStars']) try: em.set_thumbnail(url=resp['league']['iconUrls']['medium']) except KeyError: em.set_thumbnail(url='http://clash-wiki.com/images/progress/leagues/no_league.png') try: em.add_field(name="Builder Base", value=self.emoji(f"bh{resp['builderHallLevel']}"), inline=False) em.add_field(name='Builder Hall', value=resp['builderHallLevel']) em.add_field(name='Trophies', value=resp['versusTrophies']) em.add_field(name='Personal Best', value=resp['bestVersusTrophies']) em.add_field(name='Attack Wins', value=resp['versusBattleWins']) except KeyError: em.add_field(name="Builder Hall", value='Builder Base is not unlocked yet! Hit Town Hall 4 to unlock.') try: em.add_field(name="Clan", value=f"{resp['clan']['name']}, {resp['clan']['tag']}", inline=False) em.add_field(name='Clan Level', value=resp['clan']['clanLevel']) types = { 'member': 'Member', 'admin': 'Elder', 'coLeader': 'Co-Leader', 'leader': 'Leader' } em.add_field(name='Clan Role', value=types[resp['role']]) em.set_author(name='Clan Info') #em.set_thumbnail(url=resp['clan']['badgeUrls']['medium']) except KeyError: em.add_field(name="Clan", value=f"No Clan", inline=False) await ctx.send(embed=em)
## Main Discord bot settings # Bot"s token (DO NOT SHARE WITH ANYONE ELSE!) (To find your token go to https://discordapp.com/developers/appli~cations/ > Your Wumpus-Bot Application > Bot (Turn the application into a bot if you haven"t already) > Token) # if testing: TOKEN = "TEST_BOT_TOKEN" # TEST BOT TOKEN else: TOKEN = "MAIN_BOT_TOKEN" # main bot token # Owner IDS (People who have access to restart the bot) OWNERIDS = [] # Main Color (Replace the part after 0x with a hex code) MAINCOLOR = discord.Colour(0xdb58dd) TURNCOLOR = discord.Color.blue() NOTTURN = discord.Color(0x000000) DAMAGE = discord.Color.red() OK = discord.Color.green() CLAN_EMOTE_HOSTS = [] OPEN_QUEUES = True # Error Color (Replace the part after the 0x with a hex code) ERRORCOLOR = 0xED4337 TITLES = [ ' the Warrior', ' the Guard', ' the Bard', ' I', ' II', ' III', ' IV', ' V', ' VI', ' VII', ' VIII', ' IX', ' X', ' the Holy', ' the One', ' the Only', ' the Emperor', ' the King', ' the Queen', ' the Duke', ' the Duchess', ' the Knight', ' <:Crystal:672975609135366145>'
async def sync_guild_ranks(self, doc, initial=False): name = self.__class__.__name__ guilddoc = doc["cogs"][name]["sync"] enabled = guilddoc.get("on", False) if not enabled: return guild = self.bot.get_guild(doc["_id"]) if guild is None: return savedranks = guilddoc["ranks"] gid = guilddoc["gid"] endpoint = "guild/{0}/ranks".format(gid) lid = guilddoc["leader"] scopes = ["guilds"] leader = await self.bot.get_user_info(lid) currentranks = [] existingranks = [] newranks = [] newsaved = {} if not initial: if len(guild.roles) <= 1: return try: ranks = await self.call_api(endpoint, leader, scopes) except APIError: return for rank in ranks: try: discordrole = discord.utils.get( guild.roles, id=guilddoc["ranks"][rank["id"]]) if discordrole: existingranks.append(discordrole) newsaved[rank["id"]] = discordrole.id else: newranks.append(rank["id"]) except KeyError: newranks.append(rank["id"]) for role_id in savedranks.values(): discordrole = discord.utils.get(guild.roles, id=role_id) currentranks.append(discordrole) todelete = set(currentranks) - set(existingranks) for rank in todelete: try: await rank.delete() except discord.Forbidden: pass except AttributeError: pass for role in newranks: newrole = await guild.create_role( name=role, reason="GW2Bot Sync Role [$guildsync]", color=discord.Color(self.embed_color)) newsaved[role] = newrole.id guilddoc["ranks"] = newsaved await self.bot.database.set_guild(guild, {"sync.ranks": newsaved}, self) gw2members = await self.getmembers(leader, gid) rolelist = [] for role_id in newsaved.values(): discordrole = discord.utils.get(guild.roles, id=role_id) rolelist.append(discordrole) if gw2members is not None: for member in guild.members: rank = None try: keydoc = await self.fetch_key(member) name = keydoc["account_name"] for gw2user in gw2members: if gw2user["name"] == name: rank = gw2user["rank"] if rank: try: desiredrole = discord.utils.get( guild.roles, id=guilddoc["ranks"][rank]) if desiredrole not in member.roles: for role in rolelist: try: await member.remove_roles( role, reason= "GW2Bot Integration [$guildsync]") except discord.Forbidden: self.log.debug( "Permissions error when trying to " "remove {0} role from {1} " "user in {2} server.".format( role.name, member.name, guild.name)) except discord.HTTPException: # usually because user doesn't have role pass except AttributeError: # role no longer exists - deleted? pass try: await member.add_roles( desiredrole, reason="GW2Bot Integration [$guildsync]" ) except discord.Forbidden: self.log.debug( "Permissions error when trying to " "give {0} role to {1} user " "in {2} server.".format( desiredrole.name, member.name, guild.name)) except AttributeError: # role no longer exists - deleted? pass except Exception as e: self.log.debug( "Couldn't get the role object for {0} user " "in {1} server {2}.".format( member.name, guild.name, e)) except APIKeyError: pass else: self.log.debug( "Unable to obtain member list for {0} server.".format( guild.name))
async def cGif(client,message,params={}): '''Takes a live gif from the bot. Parameters: effectname, eff=effectname, s=length_seconds, fps=fps''' if not lowpower: await message.channel.send( f'Gifs are not available in timelapse mode.') return timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC+1 ') timestampshort = datetime.now().strftime('%Y%m%d_%H%M%S') shortname = re.sub('[^0-9a-zA-Z]','',message.author.name) filepath = path.join(client.dirs['live'],f'{timestampshort}_{shortname}.h264') embed = discord.Embed() embed.title = f'Recording GIF for {message.author.name}' embed.type = 'rich' embed.description = '' embed.colour = discord.Color.red() embed.set_footer(text=timestamp) field1 = embed.add_field(name='Status',value='Preparing',inline=True) embedm = await message.channel.send(embed=embed) global camera if not camera.closed: field1 = embed.set_field_at(index=0,name='Status',value='Waiting for Camera',inline=True) await embedm.edit(embed=embed) while not camera.closed: await asyncio.sleep(0.1) camera = PiCamera() camera.start_preview() try: delay = max(1,min(float(params.get('s')),59,)) except TypeError: delay = 3 try: fps = max(1,min(int(params.get('fps')),30)) except TypeError: fps = 30 effect = None if params.get('eff'): effect = valideffect(params.get('eff')) else: for param in params.keys(): if valideffect(param): effect = valideffect(param) fGif = functools.partial(camera.start_recording,filepath, format='h264') field1 = embed.set_field_at(index=0,name='Status',value='Waiting for Camera',inline=True) await embedm.edit(embed=embed) camera.image_effect = effect or 'none' camera.resolution = (1640,1232) camera.framerate = fps await client.loop.run_in_executor(None, fGif) field1 = embed.set_field_at(index=0,name='Status',value='Recording',inline=True) embed.colour = discord.Color(0xFFFF00) await embedm.edit(embed=embed) waituntil = time() + delay while waituntil >= time(): try: camera.wait_recording() await asyncio.sleep(0.25) except Exception as e: print(e) camera.stop_recording() camera.close() filepathmp4 = f"{filepath[:-5]}.mp4" command = f"MP4Box -add {filepath} {filepathmp4}" try: output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True) except subprocess.CalledProcessError as e: print('FAIL:\ncmd:{}\noutput:{}'.format(e.cmd, e.output)) field1 = embed.set_field_at(index=0,name='Status',value='FAILED',inline=True) embed.colour = discord.Color(0xFF0000) await embedm.edit(embed=embed) return doembed = not params.get('noembed') and os.path.getsize(filepathmp4) < 8e+6 or params.get('embed') or params.get('nogfy') if not doembed: field1 = embed.set_field_at(index=0,name='Status',value='Uploading',inline=True) embed.colour = discord.Color.green() await embedm.edit(embed=embed) gfyname = await GfycatClient.upload(filepathmp4) print(gfyname) # embed.set_field_at(index=0,name='Status',value='FAILED',inline=True) # embed.add_field(name='Error',value='Failed during upload',inline=True) # embed.colour = discord.Color(0xFF0000) # await embedm.edit(embed=embed) field1 = embed.set_field_at(index=0,name='Status',value='Waiting for gfycat',inline=True) await embedm.edit(embed=embed) first = True oldprogress = '' progress = '0' while True: gfystatus = await GfycatClient.status(gfyname) print(gfystatus) if 'gfyname' in gfystatus: gfylink = f'https://gfycat.com/{gfystatus["gfyname"]}' break elif 'errorMessage' in gfystatus: field1 = embed.set_field_at(index=0,name='Status',value='FAILED',inline=True) embed.set_field_at(index=1,name='Error',value=f'{message.author.mention} Upload failed with Error: `{gfystatus["errorMessage"]["code"]} : {gfystatus["errorMessage"]["description"]}`',inline=True) embed.colour = discord.Color.red() await embedm.edit(embed=embed) return elif 'task' in gfystatus and gfystatus['task'] == 'encoding': if first: field1 = embed.set_field_at(index=0,name='Status',value='Encoding',inline=True) field2 = embed.add_field(name='Progress',value='0%',inline=True) first = False if 'progress' in gfystatus: pvalue = round(float(gfystatus['progress']) / 1.17 * 100,2) field2 = embed.set_field_at(index=1,name='Progress',value=f'{pvalue}%',inline=True) progress = gfystatus['progress'] if oldprogress != progress: oldprogress = progress await embedm.edit(embed=embed) await asyncio.sleep(1) else: await asyncio.sleep(1) gfylog = await aiofiles.open(path.join(client.dirs['logs'],'gfy.log'),'a+',loop=client.loop) await gfylog.write(f'\n{gfylink}') await gfylog.close() await embedm.delete() xtemp,_,_ = await getTemp() if doembed: await message.channel.send( f'Gif taken for {message.author.mention} at: {timestamp} \n**Temperature:** {round(xtemp,2)}°C',file=discord.File(filepathmp4)) else: await message.channel.send( f'Gfy taken for {message.author.mention} at: {timestamp} \n**Temperature:** {round(xtemp,2)}°C \n{gfylink}')
class CDT(commands.Cog): """Library functions for CollectorDevTeam """ ID = 3246316013445447780012 COLLECTOR_ICON = 'https://raw.githubusercontent.com/CollectorDevTeam/assets/master/data/cdt_icon.png' COLLECTOR_FEATURED = 'https://raw.githubusercontent.com/CollectorDevTeam/assets/master/data/images/featured/collector.png' BASEPATH = "https://raw.githubusercontent.com/CollectorDevTeam/assets/master/data/" PATREON = 'https://patreon.com/collectorbot' KABAM_ICON = 'https://imgur.com/UniRf5f.png' COLORS = { 1: discord.Color(0x3c4d3b), 2: discord.Color(0xa05e44), 3: discord.Color(0xa0aeba), 4: discord.Color(0xe1b963), 5: discord.Color(0xf55738), 6: discord.Color(0x07c6ed), 'Cosmic': discord.Color(0x2799f7), 'Tech': discord.Color(0x0033ff), 'Mutant': discord.Color(0xffd400), 'Skill': discord.Color(0xdb1200), 'Science': discord.Color(0x0b8c13), 'Mystic': discord.Color(0x7f0da8), 'All': discord.Color(0x03f193), 'Superior': discord.Color(0x03f193), 'default': discord.Color.gold(), 'easy': discord.Color.green(), 'beginner': discord.Color.green(), 'medium': discord.Color.gold(), 'normal': discord.Color.gold(), 'heroic': discord.Color.red(), 'hard': discord.Color.red(), 'expert': discord.Color.purple(), 'master': discord.Color.purple(), 'epic': discord.Color(0x2799f7), 'uncollected': discord.Color(0x2799f7), 'symbiote': discord.Color.darker_grey(), } # def _init__(self): # pass def cdt_embed(self, ctx=None): """Discord Embed constructor with CollectorDevTeam defaults.""" emauthor_icon_url = CDT.COLLECTOR_ICON if ctx is not None: emcolor = ctx.message.author.color emauthor = "Requested by {0.display_name} | {0.id}".format( ctx.message.author) emauthor_icon_url = ctx.message.author.avatar_url else: emcolor = discord.Color.gold() emauthor = "CollectorDevTeam" embed = discord.Embed(color=emcolor) embed.set_footer(text=emauthor, icon_url=emauthor_icon_url) return embed @staticmethod async def fetch_json(ctx, url): await ctx.send("Initializing 'fetch_json(ctx, url)'") async with aiohttp.ClientSession() as session: async with session.get(url) as response: #Cuation - all json data is loaded into memory await ctx.send(response.status) await ctx.send("Returning json data") json_data = dirtyjson.loads(await response.text()) # json_data = await response.json() return json_data # # ################################################## # # Hashtag grammar # ################################################## # # class HashtagPlusError(TypeError): # pass # # class HashtagToken(modgrammar.Grammar): # grammar = modgrammar.WORD('#', "_a-zA-Z:*'0-9-"), modgrammar.WORD('_a-zA-Z:*0-9') # # def match_set(self, roster): # return roster.raw_filtered_ids(set([self.string])) # # def sub_aliases(self, aliases): # if self.string in aliases: # return '({})'.format(aliases[self.string]) # else: # return self.string # # # class HashParenExpr(modgrammar.Grammar): # grammar = (modgrammar.L('('), modgrammar.REF("HashExplicitSearchExpr"), modgrammar.L(")")) # # def match_set(self, roster): # return self[1].match_set(roster) # # def sub_aliases(self, aliases): # return '({})'.format(self[1].sub_aliases(aliases)) # # # class HashUnaryOperator(modgrammar.Grammar): # grammar = modgrammar.L('!') # # def op(self, roster): # return roster.ids_set().difference # # # class HashBinaryOperator(modgrammar.Grammar): # grammar = modgrammar.L('&') | modgrammar.L('|') | modgrammar.L('-') | modgrammar.L('+') # # def op(self, roster): # if self.string == '&': # return set.intersection # elif self.string == '|': # return set.union # elif self.string == '-': # return set.difference # elif self.string == '+': # raise HashtagPlusError("Operator '+' is not defined for Hashtag Syntax") # # def sub_aliases(self, aliases): # if self.string == '+': # raise HashtagPlusError("Operator '+' is not defined for Hashtag Syntax") # else: # return self.string # # # class HashP0Term(modgrammar.Grammar): # grammar = (HashParenExpr | HashtagToken) # # def match_set(self, roster): # return self[0].match_set(roster) # # def sub_aliases(self, aliases): # return self[0].sub_aliases(aliases) # # # class HashP0Expr(modgrammar.Grammar): # grammar = (HashUnaryOperator, HashP0Term) # # def match_set(self, roster): # return self[0].op(roster)(self[1].match_set(roster)) # # def sub_aliases(self, aliases): # return self[0].string + self[1].sub_aliases(aliases) # # # class HashP1Term(modgrammar.Grammar): # grammar = (HashP0Expr | HashParenExpr | HashtagToken) # # def match_set(self, roster): # return self[0].match_set(roster) # # def sub_aliases(self, aliases): # return self[0].sub_aliases(aliases) # # # class HashP1Expr(modgrammar.Grammar): # grammar = (HashP1Term, modgrammar.ONE_OR_MORE(HashBinaryOperator, HashP1Term)) # # def match_set(self, roster): # matches = self[0].match_set(roster) # for e in self[1]: # matches = e[0].op(roster)(matches, e[1].match_set(roster)) # return matches # # def sub_aliases(self, aliases): # ret = self[0].sub_aliases(aliases) # for e in self[1]: # ret += e[0].sub_aliases(aliases) + e[1].sub_aliases(aliases) # return ret # # # class HashExplicitSearchExpr(modgrammar.Grammar): # grammar = (HashP1Expr | HashP0Expr | HashParenExpr | HashtagToken) # # def match_set(self, roster): # return self[0].match_set(roster) # # def sub_aliases(self, aliases): # return self[0].sub_aliases(aliases) # # def filter_roster(self, roster): # filt_ids = self.match_set(roster) # filt_roster = roster.filtered_roster_from_ids(filt_ids) # return filt_roster # # # class HashImplicitSearchExpr(modgrammar.Grammar): # grammar = modgrammar.ONE_OR_MORE(HashtagToken, collapse=True) # # def match_set(self, roster): # filt_ids = roster.ids_set() # for token in self: # filt_ids = filt_ids.intersection(token.match_set(roster)) # return filt_ids # # def sub_aliases(self, aliases): # ret = [token.sub_aliases(aliases) for token in self] # return ' & '.join(ret) # # # class HashAttrSearchExpr(modgrammar.Grammar): # grammar = (modgrammar.OPTIONAL(AttrExpr), # modgrammar.OPTIONAL(HashImplicitSearchExpr | HashExplicitSearchExpr), # modgrammar.OPTIONAL(AttrExpr)) # # def sub_aliases(self, ctx, aliases): # attrs = self[0].get_attrs() if self[0] else {} # attrs = self[2].get_attrs(attrs) if self[2] else attrs # return (attrs, self[1].sub_aliases(aliases)) if self[1] else (attrs, '') # # class HashUserSearchExpr(modgrammar.Grammar): # grammar = (modgrammar.OPTIONAL(UserExpr), # modgrammar.OPTIONAL(HashImplicitSearchExpr | HashExplicitSearchExpr)) # # def sub_aliases(self, ctx, aliases): # user = self[0].get_user(ctx) if self[0] else ctx.message.author # return (user, self[1].sub_aliases(aliases)) if self[1] else (user, '') # # # class HashParser: # # def __init__(self): #, bot): # # self.bot = bot # self.attr_parser = HashAttrSearchExpr.parser() # self.user_parser = HashUserSearchExpr.parser() # self.explicit_parser = HashExplicitSearchExpr.parser() # # async def parse_1st_pass(self, ctx, parser, hargs, aliases=None): # try: # result1 = parser.parse_string(hargs) # except modgrammar.ParseError as e: # await self.generic_syntax_error_msg(hargs, e) # raise # try: # return result1.sub_aliases(ctx, aliases) # except HashtagPlusError as e: # await self.hashtag_plus_error_msg() # raise # # async def parse_2nd_pass(self, roster, expl_hargs): # if expl_hargs: # try: # result2 = self.explicit_parser.parse_string(expl_hargs) # except modgrammar.ParseError as e: # await self.generic_syntax_error_msg(hargs, e) # return # try: # return result2.filter_roster(roster) # except HashtagPlusError as e: # await self.hashtag_plus_error_msg() # return # else: # return roster # # async def parse_with_attr(self, ctx, hargs, roster_cls, aliases=None): # '''Parser implies no user roster so use bot. Parse attrs to pass to roster creation.''' # aliases = aliases if aliases else {} # try: # attrs, expl_hargs = await self.parse_1st_pass(ctx, # self.attr_parser, hargs, aliases) # except (HashtagPlusError, modgrammar.ParseError) as e: # #logger.info('SyntaxError caught ', str(e)) # return # roster = roster_cls(ctx.bot, ctx.bot.user, attrs=attrs) # return await self.parse_2nd_pass(roster, expl_hargs) # # async def parse_with_user(self, ctx, hargs, roster_cls, aliases=None): # '''Parser implies user roster.''' # aliases = aliases if aliases else {} # try: # user, expl_hargs = await self.parse_1st_pass(ctx, self.user_parser, # hargs, aliases) # except (HashtagPlusError, modgrammar.ParseError) as e: # #logger.info('SyntaxError caught ', str(e)) # return # roster = roster_cls(ctx.bot, user) # ## Temporarily disabled until loading functions can be addressed. # ## Loading will probably be using the new Config.get(self, identifier=user.id) # ## Frist I need to ident the user. # # await roster.load_champions() # return await self.parse_2nd_pass(roster, expl_hargs) # # async def generic_syntax_error_msg(self, hargs, e=None): # em = discord.Embed(title='Input Error', description='Syntax problem', # color=discord.Color.red()) # em.add_field(name="Don't mix implicit and explicit operators", # value=hargs) # await ctx.bot.send(embed=em) # return # # async def hashtag_plus_error_msg(self): # em = discord.Embed(title='Input Error', description='Syntax problem', # color=discord.Color.red()) # em.add_field(name="`+` operator is not defined for hashtags.", # value="You probably want the `|` operator. Call " # "`/help hashtags` for detailed syntax.") # await ctx.bot.send(embed=em) # return # # async def filter_and_display(self, ctx, hargs, roster_cls, aliases=None): # filtered = await self.parse_with_attr(ctx, hargs, roster_cls, aliases) # if filtered: # await filtered.display() # elif filtered is not None: # await filtered.warn_empty_roster(hargs) # # # ################################################## # # End Grammar definitions # ##################################################
async def on_run_check_loop(): while True: to_check = set(bot._guild_check_queue) # inb4 another value is added here before I clear it haha bot._guild_check_queue = [] for guild in to_check: try: # Check if still in guild if not (guild and bot.get_guild(guild.id)): continue # Check if guild can be posted to if not guild.me.guild_permissions.view_audit_log: continue guild_config = await get_guild_configs(guild.id) if not guild_config.guild_id: continue channel = guild_config.post_channel channel = guild.get_channel(channel) if not channel or not channel.permissions_for(guild.me).send_messages: continue # Get entries entries = await check_guild_logs(guild, guild_config) await post_entries(entries, channel, guild_config) except Exception as e: text = "".join(traceback.TracebackException.from_exception(e).format()) embed_limit = 10 size = 2048 - 10 print(f"Error in guild {guild.id}") print(text) # Report errors to webhook await send_webhook( content=f"<@{cfg['owner_id']}> Error in guild {guild.id} ({guild.name})", embeds=[ discord.Embed( color=discord.Color(value=0xC62828), description=f"```py\n{text[i:i+size]}\n```", ) for i in range(0, len(text), size)[-embed_limit:] ], ) # Check in every hour now = datetime.datetime.utcnow() if now.timestamp() - bot.last_check_in > 3660: await send_webhook( content=f"Hourly check-in successful. `{now.strftime('%Y-%m-%d %H:%M')}`" ) bot.last_check_in = now.timestamp() await asyncio.sleep(2)
async def _profile(self, ctx, member: discord.Member = None): guild_config = self.config["guilds"][str(ctx.guild.id)] admin_role = ctx.guild.get_role(guild_config["admin_role"]) dev_role = ctx.guild.get_role(guild_config["dev_role"]) if (not admin_role in ctx.author.roles) and (not dev_role in ctx.author.roles): return if member == None: member = ctx.author data = Handlers.Mongo.read() if member == None: member = ctx.author try: sona = data["sonas"][str(member.id)] except: return await ctx.send(self.bot.translate("NO_SONA_FOUND")) # if not ctx.channel.is_nsfw(): # return await ctx.send(self.bot.translate("FORBIDDEN_COMMAND_CHANNEL", ctx=ctx)) def check(answer): return ctx.channel == answer.channel and ctx.author == answer.author def check2(reaction, user): return ctx.channel == reaction.message.channel and ctx.author == user options = { "🖼": "Display", "📄": "Raw", "✅": "Set", "🚫": "Delete" } try: embed = discord.Embed(color=discord.Color( int(str(sona["Color"]).replace("#", ""), 16))) except: embed = discord.Embed(color=discord.Color(0x00ff7e)) embed.set_author(name=f"{member} ({str(member.id)})'s profile.", icon_url=ctx.author.avatar_url) embed.description = "Pick an option\n**Options:**:" for option in options: embed.description = f"{embed.description}\n{option} - {options[option]}" answer = await ctx.send(embed=embed) for option in options: await answer.add_reaction(option) try: reaction, user = await self.bot.wait_for("reaction_add", check=check2, timeout=1800) except: return await ctx.send(self.bot.translate("TIMED_OUT", ctx=ctx)) option = options[str(reaction)] await answer.clear_reactions() if not str(reaction) in options: return await ctx.send(self.bot.translate("INVALID_OPTION")) if option == "Display": try: embed = discord.Embed(color=discord.Color( int(str(sona["Color"]).replace("#", ""), 16))) except: embed = discord.Embed(color=discord.Color(0x00ff7e)) embed.set_author(name=f"{member} | {str(member.id)}", icon_url=member.avatar_url) for question in sona: embed.add_field(name=question, value=sona[question]) embed.set_image(url=sona["Picture"]) embed.timestamp = ctx.message.created_at try: message = await ctx.send(embed=embed) except: embed.set_image( url= "https://media.discordapp.net/attachments/579350335059918858/587607748653350944/Seperate_1.gif" ) message = await ctx.send(embed=embed) elif option == "Raw": for key in sona: if not key == "NSFW" and not sona[key] == None: sona[key] = sona[key].replace("'", "\\`").replace('"', "“") else: sona[key] == sona[key] rawsona = str(sona).replace("'", '"').replace( "True", "\"True\"").replace("False", "\"False\"").replace("None", "\"None\"") return await ctx.send(f"```json\n{rawsona}\n```") elif option == "Set": try: embed = discord.Embed(color=discord.Color( int(str(sona["Color"]).replace("#", ""), 16))) except: embed = discord.Embed(color=discord.Color(0x00ff7e)) embed.set_author(name=f"{member} ({str(member.id)})'s profile.", icon_url=ctx.author.avatar_url) embed.description = "Send the new profile value." await ctx.send(embed=embed) try: answer = await self.bot.wait_for("message", check=check, timeout=1800) except: return await ctx.send(self.bot.translate("TIMED_OUT", ctx=ctx)) newsona = (answer.content).replace("'", '\\\`') newsona = json.loads(newsona) if newsona["NSFW"] == "True": newsona["NSFW"] = True else: newsona["NSFW"] = False if newsona["Picture"] == "None": newsona["Picture"] = None if newsona["About"] == "None": newsona["About"] = None data["sonas"][str(member.id)] = newsona Handlers.Mongo.save(data) embed = discord.Embed(color=ctx.author.color) embed.set_author(name=f"{member} ({str(member.id)})'s profile.", icon_url=ctx.author.avatar_url) embed.description = "Successfully modified the profile." return await ctx.send(embed=embed) elif option == "Delete": question = "Are you sure?" embed = discord.Embed(color=discord.Color(0x7289DA)) embed.description = question message = await ctx.send(embed=embed) await message.add_reaction("✅") await message.add_reaction("🚫") try: reaction, user = await self.bot.wait_for("reaction_add", check=check2, timeout=1800) except: return await ctx.send(self.bot.translate("TIMED_OUT", ctx=ctx)) if str(reaction) == "✅": pass elif str(reaction) == "🚫": return await ctx.send(self.bot.translate("EXIT")) else: return await ctx.send(self.bot.translate("INVALID_OPTION")) Handlers.Mongo.remove_field("sonas", str(member.id)) embed = discord.Embed(color=ctx.author.color) embed.set_author(name=f"{member} ({str(member.id)})'s profile.", icon_url=ctx.author.avatar_url) embed.description = "Successfully deleted the profile." return await ctx.send(embed=embed)
def default_color() -> discord.Color: return discord.Color(659493)
def RandomColor(): randcolor = discord.Color(random.randint(0x000000, 0xFFFFFF)) return randcolor
async def modhelp(ctx): author = ctx.message.author r, g, b = tuple( int(x * 255) for x in colorsys.hsv_to_rgb(random.random(), 1, 1)) embed = discord.Embed(color=discord.Color((r << 16) + (g << 8) + b)) embed.set_author(name='Moderation Commands Help') embed.set_image(url='https://image.ibb.co/caM2BK/help.gif') embed.add_field(name='/say(Admin permission required) ', value='Use it like ``/say <text>``', inline=False) embed.add_field(name='/embed(Admin permission required) ', value='Use it like ``/embed <text>``', inline=False) embed.add_field(name='/membercount(Kick members Permission Required) ', value='Use it like ``/membercount`` to get membercount', inline=False) embed.add_field( name='/removemod(Admin Permission Required)', value= 'Use it like ``/removemod @user`` to remove him from mod. Note-You need Moderator role in your server below darkbot to use it.', inline=False) embed.add_field( name='/makemod(Admin Permission Required)', value= 'Use it like ``/makemod @user`` to make him mod. Note-You need Moderator role in your server below darkbot to use it.', inline=False) embed.add_field( name='/setup(Admin Permission Required)', value= 'Use it to add channels, voice channels and roles if your server is not developed currently and you have just 1-2 channels. Note- Use it only 1 time. If you will use same command again then it will do same thing again .i.e It will add true copy of previous channels + true copy of roles that made in previous command use. So be careful.', inline=False) embed.add_field( name='/friend(Admin Permission Required) ', value= 'Use it like ``/friend @user`` to give anyone Friend of Owner role', inline=False) embed.add_field(name='/role(Manage Roles Permission Required)', value='Use it like ``/role @user <rolename>``.', inline=False) embed.add_field( name='/setnick(Manage nickname permission required)', value= 'Use it like ``/setnick @user <New nickname>`` to change the nickname of tagged user.', inline=False) embed.add_field( name='/english(Kick members Permission Required)', value= 'Use it like ``/english @user`` when someone speaks languages other than English.', inline=False) embed.add_field(name='/serverinfo(Kick members Permission Required) ', value='Use it like ``/serverinfo`` to get server info', inline=False) embed.add_field( name='/userinfo(Kick members Permission Required) ', value= 'Use it like ``/userinfo @user`` to get some basic info of tagged user', inline=False) embed.add_field(name='/kick(Kick members Permission Required)', value='Use it like ``/kick @user`` to kick any user', inline=False) embed.add_field(name='/roles(Kick members Permission Required) ', value='Use it to check roles present in server', inline=False) embed.add_field( name='/clear(Manage Messages Permission Required)', value='Use it like ``/clear <number>`` to clear any message', inline=False) embed.add_field( name='/mute(Mute members Permission Required)', value='Use it like ``/mute @user <time>`` to mute any user', inline=False) embed.add_field(name='/unmute(Mute members Permission Required) ', value='Use it like ``d!unmute @user`` to unmute anyone', inline=False) embed.add_field(name='/ban(Ban members Permission Required) ', value='Use it like ``/ban @user`` to ban any user', inline=False) embed.add_field( name='/rules(Kick members Permission Required)', value='Use it like ``/rules @user <violation type>`` to warn user', inline=False) embed.add_field( name='/warn(Kick members Permission Required)', value='Use it like ``/warn @user <violation type>`` to warn any user', inline=False) embed.add_field( name='/norole(Kick members Permission Required) ', value= 'Use it like ``/norole @user`` to warn anyone if he/she asks for promotion', inline=False) embed.add_field( name='/getuser(Kick members Permission Required) ', value= 'Use it like ``/getuser @rolename`` to get list of all users having a particular role', inline=False) await client.send_message(author, embed=embed) await client.say('📨 Check DMs For Information') embed.set_footer(text="made with chetan/lucky")
async def weather(self, ctx): location = ctx.message.content cold = False rain = False if location[9].lower() == 'c': location = location[14:] cold = True elif location[9].lower() == 'r': location = location[14:] rain = True else: location = location[8:] myarr = location.split() url = "https://api.weatherbit.io/v2.0/forecast/3hourly?city=" + myarr[ 0] + "&country=" + myarr[ 1] + "&days=1&units=I&key=YOUR-API-KEY-HERE" #Getting data from url and loading into json format in python response = urlopen(url) d = response.read().decode() data = json.loads(d) if cold == True: for x in range(1, 7): dt = str(data['data'][x]['timestamp_local']) dt = dt[:10] + ' ' + dt[11:] temp = str(data['data'][x]['temp']) tempA = str(data['data'][x]['app_temp']) snow = str(data['data'][x]['snow']) pop = str(data['data'][x]['pop']) precip = str(data['data'][x]['precip']) hum = str(data['data'][x]['rh']) weath = str(data['data'][x]['weather']['description']) temp_temp = float(temp) if temp_temp <= 45.0: await self.bot.send_message( ctx.message.channel, ":snowflake: :snowflake: :snowflake: :snowflake: :snowflake: :snowflake: :snowflake: " ) embed = discord.Embed(title="Location", description=myarr[0] + "," + myarr[1], color=discord.Color(0x0ae1fd)) embed.set_author(name="Weather Forecast Today") embed.add_field(name="Weather Discription", value=weath, inline=True) embed.add_field(name="Date Time", value=dt, inline=True) embed.add_field(name="Temperature", value=str("Temp: " + temp + "\nApp Temp: " + tempA), inline=True) embed.add_field(name='Precipitation', value=str(precip + "%"), inline=True) embed.add_field(name='Snow', value=str(snow + "%"), inline=True) embed.add_field(name='Chance of Rain', value=str(pop + "%"), inline=True) embed.add_field(name='Humidity', value=str(hum + "%"), inline=True) await self.bot.send_message(ctx.message.channel, embed=embed) elif rain == True: for x in range(1, 7): dt = str(data['data'][x]['timestamp_local']) dt = dt[:10] + ' ' + dt[11:] temp = str(data['data'][x]['temp']) tempA = str(data['data'][x]['app_temp']) snow = str(data['data'][x]['snow']) pop = str(data['data'][x]['pop']) precip = str(data['data'][x]['precip']) hum = str(data['data'][x]['rh']) weath = str(data['data'][x]['weather']['description']) temp_pop = int(pop) if temp_pop >= 50: await self.bot.send_message( ctx.message.channel, ":umbrella2: :umbrella2: :umbrella2: :umbrella2: :umbrella2: :umbrella2: :umbrella2:" ) embed = discord.Embed(title="Location", description=myarr[0] + "," + myarr[1], color=discord.Color(0x0ae1fd)) embed.set_author(name="Weather Forecast Today") embed.add_field(name="Weather Discription", value=weath, inline=True) embed.add_field(name="Date Time", value=dt, inline=True) embed.add_field(name="Temperature", value=str("Temp: " + temp + "\nApp Temp: " + tempA), inline=True) embed.add_field(name='Precipitation', value=str(precip + "%"), inline=True) embed.add_field(name='Snow', value=str(snow + "%"), inline=True) embed.add_field(name='Chance of Rain', value=str(pop + "%"), inline=True) embed.add_field(name='Humidity', value=str(hum + "%"), inline=True) await self.bot.send_message(ctx.message.channel, embed=embed) else: for x in range(1, 7): dt = str(data['data'][x]['timestamp_local']) dt = dt[:10] + ' ' + dt[11:] temp = str(data['data'][x]['temp']) tempA = str(data['data'][x]['app_temp']) snow = str(data['data'][x]['snow']) pop = str(data['data'][x]['pop']) precip = str(data['data'][x]['precip']) hum = str(data['data'][x]['rh']) weath = str(data['data'][x]['weather']['description']) temp_pop = int(pop) temp_temp = float(temp) if temp_pop >= 50: await self.bot.send_message( ctx.message.channel, ":umbrella2: :umbrella2: :umbrella2: :umbrella2: :umbrella2: :umbrella2: :umbrella2:" ) if temp_temp <= 45.0: await self.bot.send_message( ctx.message.channel, ":snowflake: :snowflake: :snowflake: :snowflake: :snowflake: :snowflake: :snowflake: " ) embed = discord.Embed(title="Location", description=myarr[0] + "," + myarr[1], color=discord.Color(0x0ae1fd)) embed.set_author(name="Weather Forecast Today") embed.add_field(name="Weather Discription", value=weath, inline=True) embed.add_field(name="Date Time", value=dt, inline=True) embed.add_field(name="Temperature", value=str("Temp: " + temp + "\nApp Temp: " + tempA), inline=True) embed.add_field(name='Precipitation', value=str(precip + "%"), inline=True) embed.add_field(name='Snow', value=str(snow + "%"), inline=True) embed.add_field(name='Chance of Rain', value=str(pop + "%"), inline=True) embed.add_field(name='Humidity', value=str(hum + "%"), inline=True) await self.bot.send_message(ctx.message.channel, embed=embed)
async def generalhelp(ctx): author = ctx.message.author r, g, b = tuple( int(x * 255) for x in colorsys.hsv_to_rgb(random.random(), 1, 1)) embed = discord.Embed(color=discord.Color((r << 16) + (g << 8) + b)) embed.add_field( name='/poll ', value= 'Use it like ``/poll "Question" "Option1" "Option2" ..... "Option9"``.', inline=False) embed.add_field( name='/guess ', value= 'To play guess game use ``/guess <number> and number should be between 1-10``', inline=False) embed.add_field(name='/github ', value='Use it like- ``/github uksoftworld/DarkBot``', inline=False) embed.add_field( name='/bottutorial ', value='Use it like ``/bottutorial <tutorial name by darklegend>``', inline=False) embed.add_field(name='/dyno ', value='Use it like ``/dyno <dyno command name>``', inline=False) embed.add_field( name='/donate ', value= 'Use it to donate us and get a special post on Official DarkBot server.', inline=False) embed.add_field(name='/ownerinfo ', value='To get basic information about owner.', inline=False) embed.add_field(name='/sourcecode ', value='Use it to see darkbot sourcecode.', inline=False) embed.add_field(name='/upvote ', value='Use it to Upvote our bot and help us to grow', inline=False) embed.add_field( name='/authlink ', value= 'Use it to get authorizing link to authorize this bot to your server.', inline=False) embed.add_field(name='/happybirthday @user ', value='To wish someone happy birthday', inline=False) embed.add_field(name='/technews ', value='Use it to get tech news', inline=False) embed.add_field(name='/googlefy ', value='Use it like ``d!googlefy <string>``.', inline=False) embed.add_field(name='/spacenews ', value='Use it to get space news', inline=False) embed.add_field(name='/phynews ', value='Use it to get physycs', inline=False) embed.add_field( name='/verify ', value='Use it to get verified role. Note- It needs proper setup.', inline=False) embed.add_field(name='/flipcoin ', value='Flipps coin', inline=False) embed.add_field(name='/rolldice ', value='Rolls dice', inline=False) embed.add_field(name='/avatar @user ', value='Shows avatar', inline=False) await client.send_message(author, embed=embed) await client.say('📨 Check DMs For Information') embed.set_footer(text="made with chetan/lucky")
async def av(ctx): embed = discord.Embed(title="Avatar", color=discord.Color(0x3cd63d)) embed.set_image(url=ctx.author.avatar_url) await ctx.send(embed=embed)
async def cocclan(self, ctx, clantag=None): """Gets clan info for a Clash of Clans clan.""" if clantag is None: coctag = await self.get_tag(ctx.author.id) if not coctag: return await ctx.send("Oops, looks like you don't have a saved tag yet! Use `*cocsave [tag]` to save your tag to your Discord profile.") resp = await self.session.get(f'https://api.clashofclans.com/v1/players/%23{coctag}', headers=self.client) resp = await resp.json() try: clantag = resp['clan']['tag'] clantag = clantag.strip('#') except KeyError: return await ctx.send("Oops! You aren't in a clan yet. \nTo search for a clan by clan tag, use `*cocclan [clan tag]`.") respclan = await self.session.get(f'https://api.clashofclans.com/v1/clans/%23{clantag}', headers=self.client) clan = await respclan.json() color = discord.Color(value=0xe5f442) em = discord.Embed(color=color, title='Clan Info') em.add_field(name='Location', value=clan.get('location', {}).get('name')) em.add_field(name='Clan Level', value=clan.get('clanLevel', 1)) em.add_field(name='Clan Points - Home Base', value=clan.get('clanPoints', 0)) em.add_field(name='Clan Points - Builder Base', value=clan.get('clanVersusPoints', 0)) clanmembers = clan.get('members', 0) em.add_field(name='Members', value=f'{clanmembers}/50') em.add_field(name='Required Trophies', value=clan.get('requiredTrophies', 0)) em.add_field(name='War Frequency', value=clan.get('warFrequency', 0)) em.add_field(name='War Win Streak', value=clan.get('warWinStreak', 0)) em.add_field(name='War Wins', value=clan.get('warWins', 0)) em.add_field(name='War Draws', value=clan.get('warTies', 0)) em.add_field(name='War Losses', value=clan.get('warLosses', 0)) if clan['isWarLogPublic'] is True: warlog = 'Public' else: warlog = 'Private' em.add_field(name='War Log', value=warlog) em.set_author(name=f"{clan.get('name', '[Unknown Name]')} ({clan.get('tag', '[Unknown Tag]')})") em.set_thumbnail(url=clan['badgeUrls']['medium']) await ctx.send(embed=em) else: clantag = clantag.strip('#') clantag = clantag.upper() respclan = await self.session.get(f'https://api.clashofclans.com/v1/clans/%23{clantag}', headers=self.client) clan = await respclan.json() color = discord.Color(value=0xe5f442) em = discord.Embed(color=color, title='Clan Info') em.add_field(name='Location', value=clan.get('location', {}).get('name')) em.add_field(name='Clan Level', value=clan.get('clanLevel', 0)) em.add_field(name='Clan Points - Home Base', value=clan.get('clanPoints', 0)) em.add_field(name='Clan Points - Builder Base', value=clan.get('clanVersusPoints', 0)) clanmembers = clan.get('members', 0) em.add_field(name='Members', value=f'{clanmembers}/50') em.add_field(name='Required Trophies', value=clan.get('requiredTrophies', 0)) em.add_field(name='War Frequency', value=clan.get('warFrequency', 0)) em.add_field(name='War Win Streak', value=clan.get('warWinStreak', 0)) em.add_field(name='War Wins', value=clan.get('warWins', 0)) em.add_field(name='War Draws', value=clan.get('warTies', 0)) em.add_field(name='War Losses', value=clan.get('warLosses', 0)) if clan['isWarLogPublic'] is True: warlog = 'Public' else: warlog = 'Private' em.add_field(name='War Log', value=warlog) em.set_author(name=f"{clan.get('name', '[Unknown Name]')} ({clan.get('tag', '[Unknown Tag]')})") em.set_thumbnail(url=clan['badgeUrls']['medium']) await ctx.send(embed=em)
class CommandsList: e = discord.Embed(color=discord.Color(0x6441A4)) e.title = emoji.twitch_icon + "TwitchBot 指令" e.description = ":warning: __**請勿在指令中輸入 `<>` 或 `[]`。**__" e.add_field( name="一般", value=textwrap.dedent("""\ `!twitch help` - 顯示機器人幫助 `!twitch info` - 顯示機器人資訊 `!twitch lang` - 設定使用語言 `!twitch invite` - 顯示TwitchBot伺服器邀請鏈結 `!twitch status` - 顯示Twitch API 狀態 `!twitch ping` - Pong! """), inline=False ) e.add_field( name="Twitch", value=textwrap.dedent("""\ `!twitch user <user>` - 取得Twitch 頻道資訊 `!twitch stream user <user>` - 取得使用者直播資訊 `!twitch stream watch <user>` - 在Discord上觀看Twitch直播 `!twitch stream game <name>` - 觀看某人遊玩特定的遊戲直播 `!twitch stream top` - 取得最多人觀看的直播資訊 `!twitch game <name>` - 取得Twitch遊戲資訊 `!twitch top` - 取得最熱門的Twitch遊戲 """), inline=False ) e.add_field( name="影片", value=textwrap.dedent("""\ `!twitch clips from <user>` - 從Twitch使用者取得特定的影片 `!twitch clips trending` - 取得熱門影片 `!twitch clips game <game>` - 取得特定遊戲的影片 `!twitch clips uservoted` - 尋找TwitchBot使用者們投票出最熱門的影片 """), inline=False ) e.add_field( name="直播者通知", value=textwrap.dedent("""\ `!twitch notif add [#discord_channel] [streamer_name] [message]` - 在特定的頻道新增一個直播者通知給直 `!twitch notif remove <#discord_channel> <streamer_name>` - 在特定的頻道移除一個給直播者的直播者通知。 `!twitch notif list [#discord_channel]` - 在特定的頻道列出直播者通知 `!twitch notif formatting` - 顯示可新增至直播者通知的變數 """), inline=False ) e.add_field( name="直播身分", value=textwrap.dedent("""\ `!twitch live_role set` - 在此伺服器上設置一個直播身分 `!twitch live_role filter` - 限制有直播身分的使用者特定的身分 `!twitch live_role delete` - 刪除直播身分的設置 `!twitch live_role view` - 告訴你現在有那些身分已設置 """), inline=False ) e.add_field( name="音訊", value=textwrap.dedent("""\ `!twitch listen <user>` - 在現在的語音頻道收聽直播 `!twitch nowplaying` - 顯示現在正在播放的直播,如果有的 `!twitch leave` - 離開語音頻道 """), inline=False ) e.add_field( name="遊戲狀態", value=textwrap.dedent("""\ `!twitch overwatch <pc/psn/xbl> <player>` - 顯示鬥陣特工玩家狀態 `!twitch fortnite <pc/psn/xbl> <player>` - 顯示Fortnite玩家狀態 """), inline=False ) e.add_field( name="訊息過濾器", value=textwrap.dedent("""\ `!twitch filter set <sensitivity>` - 設定伺服器端病毒過濾器 `!twitch filter remove` - 移除伺服器端病毒過濾器 """), inline=False )
async def ping(self, ctx): """Sends the latency of the bot""" em = discord.Embed(title='Latency', description='🏓Pong {0}'.format(math.trunc(self.bot.latency * 1000)) + 'ms', color=discord.Color(0x4293f5)) await ctx.send(embed=em)