async def rank(self,ctx,member : Member = None): if member != None: what = ["xp","lvl","repo"] result = select("Members",what,f"id = '{member.id}'") for row in result: xp = int(row[0]) lvl = int(row[1]) repo = int(row[2]) em = Embed( colour = Colour.purple() ) em.set_author(name = member.name,icon_url = member.avatar_url) em.add_field(name='Уровень:',value=lvl) em.add_field(name='Xp:',value=xp) em.add_field(name="Осталось до следушего уровня:",value=str(lvl*(lvl * 50)- xp)+ ' xp') em.add_field(name='Количество "Спасибо":',value=repo) await ctx.send(embed = em) else: what = ["xp","lvl","repo"] result = select("Members",what,f"id = '{ctx.message.author.id}'") for row in result: xp = int(row[0]) lvl = int(row[1]) repo = int(row[2]) em = Embed( colour = Colour.purple() ) em.set_author(name = ctx.message.author.name,icon_url = ctx.message.author.avatar_url) em.add_field(name='Ваш уровень:',value=lvl) em.add_field(name='Ваш Xp:',value=xp) em.add_field(name="Вам осталось до следушего уровня:",value=str(lvl*(lvl * 50)- xp)+ ' xp') em.add_field(name='Ваше количество "Спасибо":',value=repo) await ctx.send(embed = em)
async def unmute(self, ctx, member: Member): """Unmutes a user. (Staff Only)""" if (self.bot.staff_role in member.roles and self.bot.owner_role not in ctx.message.author.roles): await ctx.send("You cannot unmute other staffers!") return elif ctx.me is member: await ctx.send("I can not unmute myself!") return try: if self.bot.muted_role not in member.roles: await ctx.send("{} is not muted!".format(member)) return elif member == ctx.message.author: await ctx.send( "You cannot unmute yourself! " "How did you even manage to send this if you are muted?") return await member.remove_roles(self.bot.muted_role) await ctx.send("{} is no longer muted!".format(member)) msg = "You have been unmuted in {}.".format(ctx.guild.name) await self.dm(member, msg) emb = Embed(title="Member Unmuted", colour=Colour.purple()) emb.add_field(name="Member:", value=member, inline=True) emb.add_field(name="Mod:", value=ctx.message.author, inline=True) logchannel = self.bot.logs_channel await logchannel.send("", embed=emb) except errors.Forbidden: await ctx.send("💢 I dont have permission to do this.")
async def test_eightball_gives_response(sleep, choice, random, bot, context): clazz = EightBall(bot) await clazz.eightball(context, "will this test pass?") embed = Embed(colour=Colour.purple()).add_field( name=f"{context.author.display_name}, my :crystal_ball: says:", value="_8ball_") context.send.assert_called_once_with(embed=embed)
async def report(self, ctx, *, message: str): try: await ctx.message.delete() except Exception: pass if self.length_checker(message=message): ticket_no = str(uuid4()) time_of_request = datetime.utcnow() if support_sys_mng.check_if_support_activated( community_id=ctx.guild.id): if await self.send_ticket_message_channel( ctx=ctx, message=message, department='Report', color_code=Colour.purple(), ticket_id=ticket_no, time_of_request=time_of_request): if await self.send_ticket_message_author( ctx=ctx, time_of_request=time_of_request, department='Marketing', ticket_id=ticket_no, support_msg=message, colour=Colour.magenta()): return else: title = '__Support System Internal Error__' message = f'System could deliver a copy of the ticket to your DM however support ' \ f'has recieved it and will be in touch as soon as possible. We apologize for' \ f' inconvinience!' await custom_message.system_message( ctx, message=message, color_code=1, destination=1, sys_msg_title=title) else: title = '__Support System Internal Error__' message = f'System could not process you request at this moment. Please try again later.' \ f' We apologize for inconvinience!' await custom_message.system_message(ctx, message=message, color_code=1, destination=1, sys_msg_title=title) else: message = f'{ctx.guild} does not have activate support ticket service. Please contact' \ f' administrators directly' await custom_message.system_message(ctx, message=message, color_code=1, destination=1) else: message = f'Message needs to be between 20 and 200 characters in length!' await custom_message.system_message(ctx, message=message, color_code=1, destination=1)
def __init__(self) -> None: self.colour = Colour.purple() self.historyEventsTable = json.loads( open(historyEventsPath, "r").read()) self.redditClient = asyncpraw.Reddit( client_id=Config.redditID, client_secret=Config.redditSecret, user_agent="linux:LiSBot:1.0 (by u/JackAshwell1)") self.bot = None self.posts = None
async def rank(self,ctx,*,id=None): "Gived you your card." if id is None: user = get_user(ctx.author.id) embed = Embed(title="Твоя карточка", colour = Colour.purple() ) else: id = int(id) user = get_user(id) member = ctx.guild.get_member(id) embed = Embed(title=f"Карточка {member.name}", colour = Colour.purple() ) embed.add_field(name="Уровень:",value=user.level) embed.add_field(name="Опыт:",value=user.experience) embed.add_field(name="Деньги:",value=user.money) embed.set_author(name=ctx.author.name,icon_url=ctx.author.avatar_url) await ctx.send(embed=embed)
async def feedback(self, ctx, *, suggestion=None): if suggestion: await ctx.send("Feedback received.") feedback_embed = Embed( title="Suggestion", description=f'Suggestion: *{suggestion} by {ctx.author}*', color=Colour.purple()) await self.bot.get_channel(394216813564526614).send( embed=feedback_embed) else: await ctx.send("You have not said what your suggestion is.")
async def addStream(client, member): p = DictionaryReader() channel = client.get_channel(int(p.streamingBroadcastChannel())) currentlyStreaming = utils.find( lambda r: r.name == p.currentlyStreamingRole(), member.guild.roles) await RoleHandler.removeStream(client, member) stream = None for act in member.activities: if act.type == ActivityType.streaming: stream = act if channel is None: print('Streaming Channel not found!') return #if not await TwitchHandler.validateStream(stream.url, Key().twitchApiKey()): # return if not stream.game.startswith('World of Warcraft'): return title, description, avatar, views, followers = await TwitchHandler.fetchStreamInfo( stream.url, Key().twitchApiKey()) emb = Embed() emb.title = title emb.type = 'rich' emb.description = description emb.url = stream.url emb.colour = Colour.purple() emb.set_footer(text='Created by PriestBot', icon_url=p.h2pIcon()) emb.set_thumbnail(url=avatar) emb.set_author(name=member.name, icon_url=member.avatar_url) emb.add_field(name='Views', value=views) emb.add_field(name='Followers', value=followers) if currentlyStreaming not in member.roles: await member.add_roles(currentlyStreaming, reason='User started streaming') await channel.send( '{0.mention} is now Live on Twitch!'.format(member), embed=emb) else: # This could be slow, but shouldn't, assuming there should be few messages in the channel messages = await channel.history(limit=None).flatten() for message in messages: if member in message.mentions: await message.edit(embed=emb)
def __init__(self, bot: commands.Bot) -> None: self.bot = bot self.colour = Colour.purple() self.triviaReactions = {"🇦": 1, "🇧": 2, "🇨": 3, "🇩": 4} self.triviaQuestions = json.loads(open(triviaPath, "r").read()) self.choicesTable = json.loads(open(choicesPath, "r").read()) self.memoryImages = list(memoryPath.glob("*")) self.remasterMemoryImages = list(remasterMemoryPath.glob("*")) self.tcMemoryImages = list(tcMemoryPath.glob("*")) self.lis2MemoryImages = list(lis2MemoryPath.glob("*")) # self.pastInputs = [] # self.pastResponses = [] self.nextTrivia = None random.shuffle(self.triviaQuestions)
async def update_embed(bot): """ Loop through the claimed toons and find whos claimed them """ claimed_toons = {} for toon in toons.values(): claimed, claimed_by = toon.get_status() if claimed: # If the toon is claimed if claimed_by in claimed_toons: claimed_toons[claimed_by].append(toon) else: claimed_toons[claimed_by] = [toon] embed = Embed( title='Toon Statuses', type='rich', description="", colour=Colour.purple(), ) for key in claimed_toons.keys(): clean_names = result = "\n".join( [t.get_name() for t in claimed_toons[key]]) fetched_name = await bot.fetch_user(key) embed.add_field(name=fetched_name, value=clean_names, inline=True) claim_times = "\n".join([t.get_time() for t in claimed_toons[key]]) embed.add_field(name="Time Claimed", value=claim_times, inline=True) embed.add_field( name="\u200b", value="\u200b", inline=True ) # Creates an empty field in 3rd column, embeds don't support 2 columns for inline fields, or I'm just dumb that too if len(claimed_toons.keys()) == 0: embed.set_footer(text="No toons are currently online") else: embed.set_footer(text="Times are automatically updated every minute") global initialized global tracker_messages if initialized: for channel_id in settings.toon_status_channels: msg = tracker_messages[channel_id] await msg.edit(embed=embed) else: for channel_id in settings.toon_status_channels: channel = bot.get_channel(channel_id) tracker_messages[channel_id] = await channel.send(embed=embed) initialized = True
def set_embed_color(embed, card_details): faction = card_details['faction']['name'] if faction == 'Monster': embed.color = Colour.red() elif faction == 'Neutral': embed.color = Colour.dark_orange() elif faction == 'Nilfgaard': embed.color = Colour.darker_grey() elif faction == 'Northern Realms': embed.color = Colour.blue() elif faction == "Scoia'tael": embed.color = Colour.green() elif faction == 'Skellige': embed.color = Colour.purple() return embed
async def mute(self, ctx, member: Member, *, reason=""): """Mutes a user. (Staff Only)""" if member is ctx.message.author: await ctx.send("You cannot mute yourself!") return elif (self.bot.staff_role in member.roles and self.bot.owner_role not in ctx.message.author.roles): await ctx.send("You cannot mute other staffers!") return elif self.bot.muted_role in member.roles: await ctx.send("{} is already muted!".format(member)) return elif ctx.me is member: await ctx.send("I can not mute myself!") return try: await member.add_roles(self.bot.muted_role) await ctx.send("{} can no longer speak!".format(member)) if not reason: msg = ( "You have been muted in {} by {}. You will be DM'ed when a mod unmutes you." "\n**Do not ask mods to unmute you, as doing so might extend the duration " "of the mute**".format(ctx.guild.name, ctx.message.author)) else: msg = ( "You have been muted in {} by {}. The given reason is {}. You will be DM'ed" " when a mod unmutes you.\n**Do not ask mods to unmute you, as doing so " "might extend the duration of the mute**" "".format(ctx.guild.name, ctx.message.author, reason)) await self.dm(member, msg) emb = Embed(title="Member Muted", colour=Colour.purple()) emb.add_field(name="Member:", value=member, inline=True) emb.add_field(name="Mod:", value=ctx.message.author, inline=True) if reason == "": emb.add_field(name="Reason:", value="No reason specified.", inline=True) else: emb.add_field(name="Reason:", value=reason, inline=True) logchannel = self.bot.logs_channel await logchannel.send("", embed=emb) except errors.Forbidden: await ctx.send("💢 I dont have permission to do this.")
async def support_reply(self, ctx, user_id: int, ticket_id: str, *, answer: str): time_of_response = datetime.utcnow() recipient = await self.bot.fetch_user(user_id=int(user_id)) answer = Embed(title='__Support response message__', colour=Colour.purple(), timestamp=time_of_response) answer.set_thumbnail(url=self.bot.user.avatar_url) answer.add_field(name='Response to ticket ID:', value=f'{ticket_id}', inline=False) answer.add_field(name='Author', value=f'{ctx.message.author}\n{ctx.message.author.id}', inline=False) answer.add_field(name='Support Response', value=f'{answer}', inline=False) answer.set_footer(text='Service provided by Launch Pad Investments') await recipient.send(embed=answer)
async def eightball(self, context: commands.Context, question: str): if question is None: await context.send( "You need to ask a question to get an answer. :unamused:") elif len(question.replace("?", "")) == 0: await context.send( "Who do you think you are? I AM!\nhttps://youtu.be/gKQOXYB2cd8?t=10" ) elif not question.endswith("?"): await context.send("I can't tell if that's a question, brother.") else: async with context.typing(): if random.random() < 3.0 / 10.0: await asyncio.sleep(3.0) await context.send(random.choice(joke_phrases)) await asyncio.sleep(5.0) await context.send(embed=Embed(colour=Colour.purple( )).add_field( name= f"{context.author.display_name}, my :crystal_ball: says:", value=f"_{random.choice(phrases)}_"))
async def on_message(self, message, **kwargs): assert isinstance(message, Message) client = self.client prefix = kwargs.get("prefix") if not is_valid_command(message.content, valid_commands, prefix=prefix): return else: self.stats.add(MESSAGE) def startswith(*args): for a in args: if message.content.startswith(a): return True return False if startswith(prefix + "osu"): username = message.content[len(prefix + "osu "):] t_start = time.time() user = self.osu.get_user(username) if not user: await client.send_message(message.channel, "User does not exist.") return # About inverting: this inverts the number before and after the splitting def prepare(this): if not type(this) in (float, int): return None return invert_str(",".join( split_every(str(invert_num(this)), 3))) global_rank = prepare(user.world_rank) country_rank = prepare(user.country_rank) total_score = prepare(user.total_score) ranked_score = prepare(user.ranked_score) try: acc = str(round(float(user.accuracy), 2)) + " %" except TypeError: await client.send_message(message.channel, ":warning: Something went wrong...") return pp_amount = str(int(float(user.pp))) osu_level = int(float(user.level)) avatar_url = "http://a.ppy.sh/{}".format(user.id) # Color is determined by the level range if osu_level < 10: color = Colour.darker_grey() elif osu_level < 25: color = Colour.light_grey() elif osu_level < 40: color = Colour.dark_teal() elif osu_level < 50: color = Colour.teal() elif osu_level < 75: color = Colour.dark_purple() elif osu_level < 100: color = Colour.purple() # Only the masters get the gold ;) else: color = Colour.gold() desc = "**Level**: {}\n**Rank**: \n\t" \ "**Global**: #{}\n\t" \ "**Country** (**{}**): #{}\n" \ "Total PP: **{}**".format(osu_level, global_rank, user.country, country_rank, pp_amount) embed = Embed(url=user.profile_url, description=desc, colour=color) embed.set_author(name=user.name) embed.set_thumbnail(url=avatar_url) embed.add_field(name="Total score", value=total_score) embed.add_field(name="Ranked score", value=ranked_score) embed.add_field(name="Average accuracy", value=acc) delta = int((time.time() - t_start) * 1000) embed.set_footer(text="Search took {} ms".format(delta)) try: await client.send_message(message.channel, embed=embed) except errors.HTTPException: await client.send_message( message.channel, "Something went wrong " + StandardEmoji.THINKING)
"https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/twitter/248/rocket_1f680.png", "void": "https://cdn.discordapp.com/attachments/700683544103747594/711013699841687602/void.png" } errorIcon = "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/twitter/248/exclamation-mark_2757.png" winIcon = "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/twitter/248/trophy_1f3c6.png" rocketIcon = "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/120/twitter/248/rocket_1f680.png" # colours to use in faction-related embed strips factionColours = { "terran": Colour.gold(), "vossk": Colour.dark_green(), "midorian": Colour.dark_red(), "nivelian": Colour.dark_blue(), "neutral": Colour.purple() } # Data representing all ship items in the game. These are used to create bbShip objects, # which are stored in builtInShipObjs in a similar dict format. # Ships to not have tech levels in GOF2, so tech levels will be automaticaly generated # for the sake of the bot during bot.on_ready. builtInShipData = {} # Data representing all module items in the game. These are used to create bbModule objects, # which are stored in builtInModuleObjs in a similar dict format. builtInModuleData = {} # Data representing all primary weapon items in the game. These are used to create bbWeapon objects, # which are stored in builtInWeaponObjs in a similar dict format. builtInWeaponData = {}
async def mine(self, ctx): if not miner(ctx.author): await send_notminer_msg(ctx) return if not has_wallet(ctx.author): embed = Embed( title="ERROR", description="You don't have a crypto wallet!\n**TIP:** `!crypto download wallet`", colour=Colour.red() ) await ctx.send(embed=embed) return alphabet = string.ascii_letters rand_letter_1 = random.choices(population=alphabet, k=10) rand_letter_2 = random.choices(population=alphabet, k=5) rand_letter_3 = random.choices(population=alphabet, k=15) joined_ouput = ("".join(rand_letter_1), "".join(rand_letter_2), "".join(rand_letter_3)) formatted_output = "-".join(joined_ouput) embed = Embed( title="Decoding hashed equation...", description=f"Hash: `{formatted_output.casefold()}`\n\n" + f"**Progress:**\n" + ":white_large_square:" * 10, colour=Colour.purple() ) time = datetime.datetime.now() embed.set_footer(text=time.strftime(f"Date: %B %d, %Y | %I:%M %p")) progress = await ctx.send(embed=embed) ii = 10 for i in range(1, 10): rand_letter_1 = random.choices(population=alphabet, k=10) rand_letter_2 = random.choices(population=alphabet, k=5) rand_letter_3 = random.choices(population=alphabet, k=15) joined_ouput = ("".join(rand_letter_1), "".join(rand_letter_2), "".join(rand_letter_3)) formatted_output = "-".join(joined_ouput) ii -= 1 await asyncio.sleep(2) embed = Embed( title="Decoding hashed equation...", description=f"Hash: `{formatted_output.casefold()}`\n\n" + f"**Progress:**\n" + ":green_square:" * i + ":white_large_square:" * ii, colour=Colour.purple() ) time = datetime.datetime.now() embed.set_footer(text=time.strftime(f"Date: %B %d, %Y | %I:%M %p")) await progress.edit(embed=embed) earnings = "0.000000000000" + str(random.randint(1, 20)) bitcoin = utils.get(self.bot.emojis, name="bitcoin") await asyncio.sleep(2) embed = Embed( title="Success!", description=f"**Equation Solved!**\n" + ":green_square:" * 10 + f"\n\n**Earnings:** {bitcoin}{earnings}", colour=Colour.purple() ) time = datetime.datetime.now() embed.set_footer(text=time.strftime(f"Date: %B %d, %Y | %I:%M %p")) embed.set_thumbnail(url="https://cdn.pixabay.com/photo/2015/08/27/11/20/bitcoin-910307_960_720.png") await progress.edit(embed=embed) query = """ UPDATE crypto SET crypto_currency=crypto_currency+? WHERE uid=? """ Connection.SQL_Cursor.execute(query, (earnings, user.get_uid(ctx.author))) Connection.SQL_Handle.commit() file = open(f"cache/{ctx.author.id}_bitcoin.history", "a") file.write(f"{earnings}\n") file.close() query = """ SELECT record_bitcoin_mined FROM record WHERE uid=? """ Connection.SQL_Cursor.execute(query, (user.get_uid(ctx.author),)) result = Connection.SQL_Cursor.fetchone() Connection.SQL_Handle.commit() if float(result[0]) < float(earnings): query = f"UPDATE record SET record_bitcoin_mined={earnings} WHERE uid=?" Connection.SQL_Cursor.execute(query, (user.get_uid(ctx.author),)) Connection.SQL_Handle.commit()
from discord import Embed, Colour COLOURS = { "red": Colour.red(), "orange": Colour.orange(), "yellow": Colour.gold(), "green": Colour.green(), "blue": Colour.blue(), "purple": Colour.purple(), } # Input colour as either a hex code or a name string def get_colour(colour): try: return COLOURS[colour] except KeyError: return colour def create_embed(title, content, colour): colour = get_colour(colour) return Embed(title=title, description=content, color=colour) def create_error(content): return create_embed("Error", content, "red")
from discord import Colour from random import seed, randint from datetime import datetime seed(datetime.now()) colours = [ Colour.teal(), Colour.dark_teal(), Colour.green(), Colour.dark_green(), Colour.blue(), Colour.dark_blue(), Colour.purple(), Colour.dark_purple(), Colour.magenta(), Colour.dark_magenta(), Colour.gold(), Colour.dark_gold(), Colour.orange(), Colour.dark_orange(), Colour.red(), Colour.dark_red(), Colour.lighter_grey(), Colour.light_grey(), Colour.dark_grey(), Colour.darker_grey(), Colour.blurple(), Colour.greyple(), Colour.from_rgb(randint(0, 255), randint(0, 255), randint(0, 255)) ]
async def process_server_response(ctx, data, query_key: str, user_query: str): if query_key == 'address': desc = f'Detail for:\n' \ f':map:`{user_query}`' elif query_key == "ledger": desc = f'Detail for :ledger: {user_query}' elif query_key == 'transaction hash': desc = f'Detail for \n' \ f':hash: `{user_query}`' payment_details = Embed(title=f':mag_right: Payments for {query_key.capitalize()} :mag_right: ', description=desc, colour=Colour.lighter_gray()) payment_details.add_field(name=f':file_folder: Complete List of Payments :file_folder: ', value=f'[Explorer Link]({data["_links"]["self"]["href"]})') payment_details.add_field(name=f'Last 3 Payment activities', value=f':arrow_double_down:', inline=False) await ctx.author.send(embed=payment_details) payments = data["_embedded"]["records"] counter = 0 for p in payments: if counter <= 2: # Check if transaction type is payment if p["type"] == 'payment': # Check if transaction was incoming or outgoing if p['to'] == p["source_account"]: c = Colour.green() else: c = Colour.red() else: # Some other account action has been done c = Colour.purple() payment_info = Embed(title=f':money_with_wings: {p["type"].capitalize()} Details :money_with_wings: ', description=f':id: `{p["id"]}` ', colour=c) payment_info.add_field(name=f':calendar: Date and time :calendar: ', value=f'`{p["created_at"]}`') payment_info.add_field(name=f':page_facing_up: Paging Token :page_facing_up: ', value=f'`{p["paging_token"]}`', inline=True) payment_info.add_field(name=':incoming_envelope: From :incoming_envelope: ', value=f'```{p["from"]}```', inline=False) payment_info.add_field(name=':map: To :map: ', value=f'```{p["to"]}```', inline=False) if not p.get('asset_code'): payment_info.add_field(name=':money_mouth: Amount :money_mouth: ', value=f'```{p["amount"]} XLM```', inline=False) else: payment_info.add_field(name=':bank: Asset Issuer :bank: ', value=f'```{p["asset_issuer"]}```', inline=False) payment_info.add_field(name=':money_mouth: Amount :money_mouth: ', value=f'```{p["amount"]} {p["asset_code"]}```', inline=False) payment_info.add_field(name=f':hash: Transaction Hash :hash:', value=f'`{p["transaction_hash"]}`', inline=False) payment_info.add_field(name=f':sunrise: Horizon Link :sunrise: ', value=f'{p["_links"]["transaction"]["href"]}', inline=False) await ctx.author.send(embed=payment_info) counter += 1