def process_commands(self, message): _internal_channel = message.channel _internal_author = message.author view = StringView(message.content) if message.author == self.user: return prefix = self._get_prefix(message) invoked_prefix = prefix if not isinstance(prefix, (tuple, list)): if not view.skip_string(prefix): ## procesar emoticons yield from self.process_emotes(message, view) return else: invoked_prefix = discord.utils.find(view.skip_string, prefix) if invoked_prefix is None: return invoker = view.get_word() tmp = { 'bot': self, 'invoked_with': invoker, 'message': message, 'view': view, 'prefix': invoked_prefix } ctx = Context(**tmp) del tmp if invoker in self.commands: command = self.commands[invoker] self.dispatch('command', command, ctx) ctx.command = command yield from command.invoke(ctx) self.dispatch('command_completion', command, ctx) else: exc = CommandNotFound('Command "{}" is not found'.format(invoker)) self.dispatch('command_error', exc, ctx) ## Invocar Kaomojis si existen key = invoker if(key not in kaomoji.keys()): key = random.sample(kaomoji.keys(), 1)[0] kao = random.sample(kaomoji[key],1)[0] yield from self.say(kao)
async def pick_player(self, ctx: Context, *, player: str): async with ctx.typing(): try: answer = self.fantasy.pick_player(ctx.author.id, player) except TimeError: return await ctx.send( "You're not allowed to make transfers right now, probably because there are games currently happening or the previous games have not yet been entered into the database. Please contact arco if you think this is an error." ) except AccountNotFoundError: return await ctx.send( f"You don't currently have an account! Use {prefix}new to make an account" ) except PlayerNotFoundError: return await ctx.send( "That player couldn't be found in the database. Make sure you spelled their name correctly" ) except TeamFullError: return await ctx.send( "You already have 5 players on your team. Please drop someone before picking your next player" ) except IllegalPlayerError: return await ctx.send("This player is not available to be picked.") except SalaryError as error: return await ctx.send( f"This player would cause you to exceed the salary cap of {error.salary_cap} by {error.excess}. Please choose a different player, or drop someone on your team." ) except AlreadyPickedError: return await ctx.send("You already have this player on your team!") await ctx.send(answer)
async def mmr(self, ctx: Context, *, player: str): async with ctx.typing(): return await ctx.send("This command isn't fully implemented and can't currently be used.") players = self.p4sheet.to_df("Players!A1:R") player, league = self.capitalize_username(player) mmrs = {} try: players.loc[player] except: await ctx.send(f"Coudn't find player {player}") return for url in players.loc[player, "Tracker"].split(", "): platform, name = url.split("/")[-2:] mmrs[name] = {} mmrs[name]["Duels"] = mmr.playlist(platform, name, "1s") mmrs[name]["Doubles"] = mmr.playlist(platform, name, "2s") mmrs[name]["Solo Standard"] = mmr.playlist(platform, name, "ss") mmrs[name]["Standard"] = mmr.playlist(platform, name, "3s") embed = discord.Embed(title=f"{player}'s MMRs", color=0xFFFFFF) for playlist in list(mmrs[name]): embed.add_field( name=playlist, value=f'{mmrs[name][playlist]["rank"]} ({mmrs[name][playlist]["rating"]})', ) await ctx.send(embed=embed)
async def on_message(msg): if not msg.content.startswith('/mc') \ and msg.author.id != OP_USER_ID \ and msg.author.id != bot.user.id \ and msg.channel.id == STATUS_CHANNEL_ID: log(f"Message from {msg.author.name}: {msg.content}") await msg.delete() if msg.content.startswith('/mc'): await mc(Context(message=msg, prefix='/'), msg.content)
async def generate_leaderboard(self, ctx: Context, limit: int = 15): async with ctx.typing(): answer = self.fantasy.fantasy_lb().head(limit) leaderboard = discord.Embed(title="Fantasy Leaderboard", color=0xFFFF00) for i, player in enumerate(answer.index): leaderboard.add_field( name=f"{i+1}: {player}", value=round(answer.loc[player]), inline=False, ) await ctx.send(embed=leaderboard)
async def get_newest(self, ctx: Context): async with ctx.typing(): post = reddit.get_post("new", 1) await ctx.send( f'**Title: {post[0]}, author: {post[1]}, score: {post[2]-post[3]}**' ) if len(post[4]) > 2000: await ctx.send( f'{post[4][0:1000]}... \n\n *This post is too long for discord, see the full post at: https://www.reddit.com{post[5]}*' ) await ctx.send(post[4])
async def show_team(self, ctx: Context, *, author: str = "none"): async with ctx.typing(): if author == "none" or author == "me": author = ctx.author.name author_id = self.session.fantasy.find_one({"username": author}) if author_id == None: return await ctx.send(f"Couldn't find a fantasy account for {author}") else: author_id = author_id["discord_id"] try: answer = self.fantasy.show_team(author_id) except AccountNotFoundError: return await ctx.send(f"Couldn't find a fantasy account for {author}") team = discord.Embed(title=f"{author}'s team", color=0x008080) if answer["account_league"] != "": team.add_field( name="Account League", value=answer["account_league"], inline=True ) else: team.add_field(name="Account League", value="None", inline=True) for i in range(5): # Get players and points and add to embed try: player_id = answer["players"][i] player: dict = self.session.players.find_one({"_id": player_id}) player_history: list = [ x for x in answer["player_history"] if x["Player"] == player_id ] # Gets points of most recent entry of player points: int = round(player_history[-1]["Points"]) team.add_field( name=f"Player {i+1}", value=f"{player['username']} ({points})", inline=True, ) except IndexError: team.add_field( name=f"Player {i+1}", value="Not Picked", inline=True ) team.add_field( name="Transfers Left", value=answer["transfers_left"], inline=True ) team.add_field(name="Salary", value=answer["salary"], inline=True) team.add_field(name="Total Points", value=answer["points"], inline=True) await ctx.send(embed=team)
async def sHelp(self, ctx: Context, specified: str = ""): async with ctx.typing(): path = '/'.join(os.getcwd().split('\\')) + '/help_text/' if specified.lower() == 'commands': path = path + "Stocks_Commands.txt" else: path = path + "Stocks.txt" with open(path) as f: text = f.read() text = text.replace('{prefix}', prefix) return await ctx.send(text, allowed_mentions = AllowedMentions(users=False, everyone=False, roles=False, replied_user=True))
def get_trashcan_listener(bot): ctx = Context(bot=bot, prefix="", message=FakeMessage()) async def trashcan_listener(payload): message_id = payload.message_id channel_id = payload.channel_id message = await MessageConverter().convert( ctx, f"{channel_id}-{message_id}") if payload.member.bot or message.author.id != ctx.bot.user.id: return if payload.emoji.name == Emoji.wastebasket: await message.delete() return trashcan_listener
async def process_commands(self, message, c, p): _internal_channel = message.channel _internal_author = message.author view = commands.view.StringView(message.content) prefix = p invoked_prefix = prefix if not isinstance(p, (tuple, list)): if not view.skip_string(p): return else: invoked_prefix = discord.utils.find(view.skip_string, prefix) if invoked_prefix is None: return invoker = view.get_word() tmp = { 'bot': self.bot, 'invoked_with': invoker, 'message': message, 'view': view, 'prefix': invoked_prefix } ctx = Context(**tmp) del tmp if c in self.bot.commands: command = self.bot.commands[c] self.bot.dispatch('command', command, ctx) # import pdb; pdb.set_trace() try: if command in (self.bot.commands['repl'], self.bot.commands['debug']): await command.invoke(ctx) else: with async_timeout.timeout(60): await command.invoke(ctx) except (aiohttp.errors.TimeoutError, asyncio.TimeoutError, CancelledError, TimeoutError): try: await self.bot.send_message( message.channel, ':warning: **Command timed out...**') return except: return except CommandError as e: ctx.command.dispatch_error(e, ctx) else: self.bot.dispatch('command_completion', command, ctx) elif invoker: exc = commands.errors.CommandNotFound( 'Command "{0}" is not found'.format(invoker)) self.bot.dispatch('command_error', exc, ctx)
async def get_post(self, ctx: Context, sort: str, number: int): number = int(number) if number < 1: await ctx.send("Please choose an integer number greater than 1.") else: pass async with ctx.typing(): post = reddit.get_post(sort, number) await ctx.send( f'**Title: {post[0]}, author: {post[1]}, score: {post[2]-post[3]}**' ) if len(post[4]) > 2000: await ctx.send( f'{post[4][0:1000]}... \n\n *This post is too long for discord, see the full post at: https://www.reddit.com{post[5]}*' ) await ctx.send(post[4])
async def google(ctx: context.Context, arg): ''' Bot command to let user perform a google search and get top 5 links Ex: !google node !google "game of thrones" ''' # Don't need to wait for the delivery of message hence not using await asyncio.create_task(ctx.send(f'Fetching top 5 links for {arg}')) # This gives user typing symbol in UI with ctx.channel.typing(): # Google search is not dependent on the storage hence not awaiting it asyncio.create_task( storage_manager.save_recent_search(ctx.author.id, arg)) for link in await google_search.get_top_5_links(arg): # The sequence of links matter await ctx.send(link)
async def sJoin(self, ctx: Context): async with ctx.typing(): discord_id = str(ctx.author.id) # First check to see if there's already an account for this person cursor = self.session.stock_accounts.find({"_id": discord_id}) if len(list(cursor)) > 0: return await ctx.send(f"You already have an account! If you recently changed your username, you may need to use `{prefix}sUpdate` to update it.") self.session.stock_accounts.insert_one({ "_id": discord_id, "username": ctx.author.name, "balance": 1000, "portfolio_value": 1000, "value_history": {datetime.now().strftime("%D"): 1000}, "portfolio": [], "transaction_history": [] }) return await ctx.send("Your account has been created! Use `$sHelp` to see what you can do with it.")
async def drop_player(self, ctx: Context, *, player: str): async with ctx.typing(): try: answer = self.fantasy.drop_player(ctx.author.id, player) except AccountNotFoundError: return await ctx.send( "You don't currently have an account! Use {prefix}new to make an account" ) except NoTransactionError: return await ctx.send( "You don't have any transfers left for this week! They will reset after Thursday's games are processed on Friday morning." ) except PlayerNotFoundError: return await ctx.send( "That player couldn't be found in the database. Make sure you spelled their name correctly" ) except IllegalPlayerError: return await ctx.send(f"{player} isn't on your team!") await ctx.send(answer)
async def sPortfolio(self, ctx: Context, user: str = "me"): async with ctx.typing(): if user.lower() == "me": account = self.session.stock_accounts.find_one({"_id": str(ctx.author.id)}) else: account = self.session.stock_accounts.find_one({"username": user}) if not account: return await ctx.send(f"This person doesn't appear to have an RLPC Stocks account! `{prefix}sJoin` can be used to create one, or `{prefix}sUpdate can be used to change your account name.") embed = discord.Embed( title=f"{account['username']}'s Portfolio", description=f"Balance: {account['balance']}", color=0xCBCE32, ) for stock in account['portfolio']: if (stock['num'] + stock['in_market']) > 0: embed.add_field(name = stock['id'], value = f"{stock['num'] + stock['in_market']} ({stock['in_market']} being sold)") return await ctx.send(embed = embed)
async def new_fantasy_player(self, ctx: Context, league: str = None): async with ctx.typing(): if not league: pass elif league.casefold() not in [ "major", "aaa", "aa", "a", "independent", "indy", "maverick", "mav", ]: return await ctx.send(f"{league} could not be understood") author = ctx.message.author.name id = ctx.message.author.id answer = accounts.create_account( author, id, league=league, session=self.session ) return await ctx.send(answer)
async def process_commands(self, message): _internal_channel = message.channel _internal_author = message.author view = StringView(message.content) if self._skip_check(message.author, self.user): return prefix = await self._get_prefix(message) invoked_prefix = prefix if not isinstance(prefix, (tuple, list)): if not view.skip_string(prefix): return else: invoked_prefix = discord.utils.find(view.skip_string, prefix) if invoked_prefix is None: return invoker = view.get_word().lower() # case-insensitive commands tmp = { 'bot': self, 'invoked_with': invoker, 'message': message, 'view': view, 'prefix': invoked_prefix } ctx = Context(**tmp) del tmp if invoker in self.commands: command = self.commands[invoker] self.dispatch('command', command, ctx) try: await command.invoke(ctx) except CommandError as e: ctx.command.dispatch_error(e, ctx) else: self.dispatch('command_completion', command, ctx) elif invoker: exc = CommandNotFound('Command "{}" is not found'.format(invoker)) self.dispatch('command_error', exc, ctx)
async def players(self, ctx: Context, *, message=None): async with ctx.typing(): league = None num = 10 pergame = False if message != None: for word in message.split(): word: str if word.isdigit(): num = int(word) elif word.lower() in leagues.keys(): league = leagues[word.lower()] if "pergame" in message or "pg" in message: pergame = True lb = self.fantasy.player_lb(league=league, num=num, pergame=pergame) if lb.size == 0: return await ctx.send("There seem to be no players with fantasy points. Contact arco if you think this is a bug.") num = min(num, lb.size) message = f"**1)** {lb.index[0]} ({lb[lb.index[0]]})" for i in range(1, num): message = message + f"\n**{i+1})** {lb.index[i]} ({lb[lb.index[i]]})" await ctx.send( f"**Player Leaderboard for fantasy points**\n*Add 'pg' to the end of the command to divide points by the # of series played*" ) try: await ctx.send(message) except: await ctx.send( "That exceeds discord's 2000 character limit. Please try again with fewer players." )
async def getreddit(self, ctx: Context, sort='new', limit=5): async with ctx.typing(): if limit > 10: limit = 10 if sort.lower() == "top": posts = reddit.list_top(limit) elif sort.lower() == "hot": posts = reddit.list_hot(limit) elif sort.lower() == "new": posts = reddit.list_new(limit) else: return await ctx.send( f'{sort} is not a valid way to sort reddit posts. Please use "new", "hot", or "top".' ) for post in range(len(posts[0])): embed = discord.Embed(title=f'{post+1}. {posts[0][post]}', color=0xff8000) embed.add_field(name="Author:", value=posts[1][post], inline=False) embed.add_field(name="Upvotes:", value=posts[2][post], inline=False) embed.add_field(name="Downvotes:", value=posts[3][post], inline=False) embed.add_field(name="Comments:", value=posts[4][post], inline=False) await ctx.send(embed=embed) return await ctx.send( f"Use '{prefix}get {sort} [number]' to get the contents of any specific post" )
def process_commands(self, message): bot = self.bot log_channel = bot.get_server("107883969424396288").get_channel( "257926036728184832") error_channel = bot.get_server("107883969424396288").get_channel( "257922447205072897") _internal_channel = message.channel _internal_author = message.author self = bot view = StringView(message.content) if self._skip_check(message.author, self.user): pass prefix = yield from self._get_prefix(message) invoked_prefix = prefix if not isinstance(prefix, (tuple, list)): if not view.skip_string(prefix): return else: invoked_prefix = discord.utils.find(view.skip_string, prefix) if invoked_prefix is None: return if invoked_prefix is "c." and message.author != message.server.me: return invoker = view.get_word() invoker_orig = invoker diff = difflib.get_close_matches(invoker, self.commands, n=1, cutoff=0.8) if diff != []: invoker = diff[0] tmp = { 'bot': self, 'invoked_with': invoker, 'message': message, 'view': view, 'prefix': invoked_prefix } ctx = Context(**tmp) del tmp if invoker in self.commands: command = self.commands[invoker] self.dispatch('command', command, ctx) try: yield from command.invoke(ctx) except discord.ext.commands.errors.DisabledCommand as e: yield from self.say("*`{}` is disabled*".format( str(e).split(" ")[0])) except discord.ext.commands.errors.CheckFailure as e: yield from self.say( "```You do not have permission for this command!```") except discord.ext.commands.errors.CommandOnCooldown as e: yield from self.say("```{}```".format(str(e))) except discord.ext.commands.errors.BadArgument as e: yield from self.say("```{}```".format(str(e))) except discord.ext.commands.errors.CommandError as e: ctx.command.dispatch_error(e, ctx) yield from self.say( "An Error Has Occurred: ```py\n{}```". format(traceback.format_exc( ).replace("/home/seacow/Discord-Bot/", "./").split( "The above exception was the direct cause of the following exception:" )[0])) if not message.author == message.server.me: yield from self.send_message( error_channel, "{}```py\n{}```".format( "\"{}\" produced an error on \"{}\" / \"{}\" | Invoked by \"{}\"" .format( message.content, _internal_channel.name, _internal_channel.server.name, _internal_author.name + "#" + _internal_author.discriminator), traceback.format_exc().replace( "/home/seacow/Discord-Bot/", "./" ).replace("\"penny123\"", "********").split( "The above exception was the direct cause of the following exception:" )[0])) except discord.ext.commands.errors.MissingRequiredArgument as e: yield from self.say("```{}```".format(str(e))) except: pass else: self.dispatch('command_completion', command, ctx) elif invoker: close_matches = difflib.get_close_matches(invoker, self.commands) extra = "" if close_matches != []: extra = "\nDid you mean?: {}{}".format( invoked_prefix, ", {}".format(invoked_prefix).join(close_matches)) yield from self.say("```\"{}\" is not a command{}```".format( invoked_prefix + invoker, extra)) exc = discord.ext.commands.errors.CommandNotFound( 'Command "{}" is not found'.format(invoker)) logging.warning('Command "{}" is not found'.format(invoker)) self.dispatch('command_error', exc, ctx)
async def statsrank(self, ctx: Context, *, msg): async with ctx.typing(): pass
async def search( self, ctx: Context, arg1="", arg2="", arg3="", arg4="", arg5="", arg6="", arg7="", arg8="", arg9="", arg10="", arg11="", arg12="", ): async with ctx.typing(): name = "none" minsalary = 0 maxsalary = 700 league = "all" team = "signed" maxdistance = 5 argument_labels = [arg1, arg3, arg5, arg7, arg9, arg11] arguments = [arg2, arg4, arg6, arg8, arg10, arg12] for arg in argument_labels: index = argument_labels.index(arg) if arg.casefold() in [ "name", "username", "player", "name:", "username:"******"player:", ]: name = arguments[index] elif arg.casefold() in [ "min", "min:", "minimum", "minimum:", "minsalary", "minsalary:", "min_salary", "min_salary:", "minimumsalary", "minimumsalary:", "minimum_salary:", "minimum_salary", ]: minsalary = int(arguments[index]) elif arg.casefold() in [ "max", "max:", "maximum", "maximum:", "maxsalary", "maxsalary:", "max_salary", "max_salary:", "maximumsalary", "maximumsalary:", "maximum_salary:", "maximum_salary", ]: maxsalary = int(arguments[index]) elif arg.casefold() in ["team", "team:"]: team = arguments[index] elif arg.casefold() in ["league", "league:"]: league = arguments[index] elif arg.casefold() in [ "maxdistance", "difference", "difference:", "maxdistance:", "strictness", "strictness:", ]: maxdistance = int(arguments[index]) answer = self.fantasy.search( minsalary=minsalary, maxsalary=maxsalary, league=league, team=team, name=name, maxdistance=maxdistance, ) embeds = [] for player in answer: embed = discord.Embed(title=player["username"], color=0x000080) embed.add_field(name="Username", value=player["username"], inline=True) embed.add_field(name="MMR", value=player["info"]["mmr"], inline=True) try: team = self.session.teams.find_one({"_id": player["info"]["team"]})[ "team" ] except TypeError: team = player["info"]["team"] team = ( team if team else "None" ) # Ensure team can't end up as NoneType embed.add_field(name="Team", value=team, inline=True) embed.add_field( name="League", value=player["info"]["league"], inline=True ) embed.add_field( name="Fantasy Value", value=player["fantasy"]["fantasy_value"], inline=True, ) embed.add_field( name="Allowed?", value=player["fantasy"]["allowed"], inline=True ) embeds.append(embed) if len(embeds) == 0: return await ctx.send("There were no players matching those parameters") elif len(embeds) == 1: await ctx.send("Here's the only player matching those parameters") else: await ctx.send(f"Here are {len(embeds)} players matching those parameters:") for i in embeds: await ctx.send(embed=i) return
async def player_info(self, ctx: Context, *, player): async with ctx.typing(): pg = False if "pg" in player.split(): player = player[:-3] pg = True if "me" in player.lower().split(" "): waitingMsg: discord.Message = await ctx.send( "One second, retreiving discord ID and stats" ) try: discord_id = str(ctx.author.id) player = self.bot.stats.get_me(discord_id) except FindMeError: return await ctx.send( "You don't appear to have an up-to-date discord id on record. Try using the name that shows up on the RLPC spreadsheet." ) await waitingMsg.delete() try: answer = self.fantasy.info(player, pg=pg) except PlayerNotFoundError: return await ctx.send(f"Couldn't find a player named {player}.") player_card = discord.Embed(title=f"{player}'s player info", color=0xFF0000) player_card.add_field( name="Region", value=answer["info"]["region"], inline=True ) player_card.add_field( name="Platform", value=answer["info"]["platform"], inline=True ) player_card.add_field(name="MMR", value=answer["info"]["mmr"], inline=True) if answer["info"]["team"] == None: player_card.add_field(name="Team", value="None") elif answer["info"]["team"] == "Not Playing": player_card.add_field(name="Team", value="Not Playing") elif answer["info"]["team"] == "Departed": player_card.add_field(name="Team", value="Departed") elif answer["info"]["team"] == "Free Agent": player_card.add_field(name="Team", value="Free Agent") else: team = self.session.teams.find_one({"_id": answer["info"]["team"]})[ "team" ] player_card.add_field(name="Team", value=team, inline=True) player_card.add_field( name="League", value=answer["info"]["league"], inline=True ) player_card.add_field( name="Fantasy Value", value=answer["fantasy"]["fantasy_value"], inline=True, ) player_card.add_field( name="Allowed?", value=answer["fantasy"]["allowed"], inline=True ) player_card.add_field( name="Fantasy Points", value=answer["fantasy"]["fantasy_points"], inline=True, ) await ctx.send(embed=player_card)