async def quote(self, ctx: commands.Context, character: str = None): await ctx.trigger_typing() if character: char = character.lower() if char not in self.charNames: await ctx.send(f'I don\'t know who "{character}" is') return else: char = random.choice(self.charNames) with open(f'./assets/quote/{char}.txt') as lines: text = lines.read() # Build the model. text_model = CampBuddyMakov(text) generated = text_model.make_sentence() while not generated: generated = text_model.make_sentence() embed = discord.Embed(title=f'{char.capitalize()} once said', description=generated, color=get_color(char)) await ctx.send(embed=embed)
async def ban(self, ctx: commands.Context, locator: str, *, reason: str = None): """Bans the specified member.""" # support = discord.utils.get(ctx.guild.roles, name="Support") member = await commands.MemberConverter().convert(ctx, locator) if not member: member = await commands.UserConverter().convert(ctx, locator) if not member: return await ctx.send("I can't find that member") if isinstance(member, discord.Member): if member.top_role.position >= ctx.author.top_role.position: return await ctx.send("That member has a higher rank than you." ) try: inv = f"https://discordapp.com/oauth2/authorize?client_id={self.bot.user.id}&permissions=0&scope=bot" e = discord.Embed(color=utils.get_color(ctx.bot)) e.description = f"[in case you need my invite to DM me]({inv})." await member.send( "Seems you were banned in the crafting table..\n" "You can either use `ct!appeal your_appeal` to request an unban, " "or fill out a form at https://forms.gle/dCLv2QZq5LHdyTuL8. Do note " "that the command is more likely to get a response", embed=e, ) except discord.errors.Forbidden: pass await ctx.guild.ban(member, reason=reason) e = discord.Embed() e.set_author(name=f"{member} was banned", icon_url=member.avatar_url) await ctx.send(embed=e)
async def on_command_error(self, ctx: commands.Context, error: commands.CommandError): """Command error handler.""" if hasattr(ctx.command, "on_error"): return ignored = ( commands.CommandNotFound, commands.NoPrivateMessage, discord.errors.NotFound, ) error = getattr(error, "original", error) if isinstance(error, ignored): return elif isinstance(error, commands.DisabledCommand): return await ctx.send(f"`{ctx.command}` has been disabled.") elif isinstance(error, commands.BadArgument): return await ctx.send(str(error)) elif isinstance(error, commands.CommandOnCooldown): user_id = str(ctx.author.id) await ctx.message.add_reaction("⏳") if user_id not in self.cd: self.cd[user_id] = 0 if self.cd[user_id] < time() - 10: await ctx.send(str(error)) self.cd[user_id] = time() + 10 elif isinstance(error, commands.MissingRequiredArgument): return await ctx.send(str(error)) elif isinstance(error, commands.CheckFailure): await ctx.send("You can't run this command!") return await ctx.message.add_reaction("⚠") elif isinstance(error, discord.errors.Forbidden): bot = ctx.guild.me if ctx.channel.permissions_for(bot).send_messages: return await ctx.send(str(error)) elif ctx.channel.permissions_for(bot).add_reactions: return await ctx.message.add_reaction("⚠") elif isinstance(error, KeyError): return await ctx.send(f"No data under the key `{error}`") else: await ctx.bot.log( ctx.command.name, f"Ignoring exception in command {ctx.command}: ```py\n" + "".join( traceback.format_exception(type(error), error, error.__traceback__)) + "```", utils.LogLevel.ERROR, ) await ctx.send(embed=discord.Embed( color=utils.get_color(ctx.bot, utils.LogLevel.ERROR), title="Uh oh...There was an error!", description=str(error), ))
async def suggest(self, ctx, *, suggestion): """Submits a suggestion to the dedicated channel.""" channel = self.bot.get_channel( self.bot.config["ids"]["suggestion_channel"]) embed = discord.Embed(color=utils.get_color(ctx.bot)) embed.set_author(name=str(ctx.author), icon_url=ctx.author.avatar_url) embed.add_field(name="Suggestion", value=suggestion) msg = await channel.send(embed=embed) embed.set_footer(text=f"id: {msg.id}") await msg.edit(embed=embed) await ctx.send(f"Sent your suggestion to the dev server. " f"Use `ct!edit {msg.id} Edited suggestion` to update it" )
async def info(self, ctx): """Displays information about the bot.""" e = discord.Embed(color=utils.get_color(ctx.bot)) c = utils.bytes2human p = psutil.Process(os.getpid()) perms = discord.Permissions() perms.update(embed_links=True, kick_members=True, ban_members=True, manage_roles=True) inv = (f"https://discordapp.com/oauth2/authorize" f"?client_id={self.bot.user.id}" f"&permissions={perms.value}" f"&scope=bot") e.set_author(name="CTBot Information", icon_url=self.bot.user.avatar_url) e.set_thumbnail(url=self.bot.config["thumbnail_url"]) e.description = ( f"A handy bot that's dedicated its code to the crafting table religion" ) e.add_field( name="◈ Github", value= "> If you wish to report bugs, suggest changes or contribute to the development " "[visit the repo](https://github.com/FrequencyX4/CTBot)", inline=False, ) e.add_field( name="◈ Credits", value="\n".join([ f"• [{self.bot.get_user(user_id)}](https://discordapp.com/channels/@me/{user_id})" for user_id in self.bot.config["devs"].values() ]), ) e.add_field( name="◈ Links", value=f"• [Crafting Table]({self.bot.config['server_inv']})\n" f"• [Github](https://github.com/FrequencyX4/CTBot)\n" f"• [Dev Discord]({self.bot.config['dev_server_inv']})\n" f"• [Invite Me]({inv})", ) e.set_footer( text= f"CPU: {psutil.cpu_percent()}% | Ram: {c(p.memory_full_info().rss)} ({round(p.memory_percent())}%)", icon_url= "https://media.discordapp.net/attachments/514213558549217330/514345278669848597/8yx98C.gif", ) await ctx.send(embed=e)
async def log(self, title, description, level=utils.LogLevel.INFO): log(title, description, level) if level.value >= self.config["log_level"]: e = discord.Embed( color=utils.get_color(self, level), title=title, description=description[:1997], ) text = [ description[i: i + 1991] for i in range(1997, len(description), 1991) ] code = description[:1997].count("```") % 2 == 1 if code: e.description += "```" for group in text: g = group if code: g = "```py\n" + g if group.count("```") % 2 == 1: code = not code if code: g += "```" e.add_field(name=".", value=g) await self.get_channel(self.config["ids"]["log_channel"]).send(embed=e)
async def appeal(self, ctx, *, appeal): """Appeal a ban from the Followers of the Crafting Table.""" user_id = str(ctx.author.id) if user_id in self.bot.appeal_ban: if self.bot.appeal_ban[user_id]["banned"]: return await ctx.send("You are banned from submitting appeals!") cooldown = self.bot.appeal_ban[user_id][ "cooldown" ] # cooldown until can appeal again if cooldown: cd = cooldown - time() if cd > 0: msg = "You're on a 2-day cooldown due to your appeal being denied. " if cooldown >= 86000: msg += f"{cooldown // 86000} day, " if cooldown >= 3600: h = cooldown // 3600 msg += f"{h} hour" if h % 10 != 1: msg += "s" msg += ", " if cooldown >= 60: m = cooldown // 60 msg += f"{m} minute" if m % 10 != 1: msg += "s" msg += ", " s = cooldown // 60 msg += f"{s} second" if s % 10 != 1: msg += "s" return await ctx.send(msg + " until you can appeal again.") channel = self.bot.get_channel(self.channel_id) try: ban_entry = await channel.guild.fetch_ban(ctx.author) except discord.errors.NotFound: return await ctx.send("You're not banned :D") e = discord.Embed( color=utils.get_color(ctx.bot), description="Appeals need to contain why you are " "banned, and a reason for being unbanned. " "Lack of either, or abuse of this command " "results in not being able to use the " "command anymore!", ) for text_group in [ appeal[i: i + 1000] for i in range(0, len(appeal), 1000) ]: e.add_field(name="◈ Your Appeal", value=text_group, inline=False) e.set_footer(text="React to accept/deny") msg = await ctx.send(embed=e) await msg.add_reaction("👍") await msg.add_reaction("👎") def pred(r, u): """Assures the conditions of the reaction are in the right location.""" return u.id == ctx.author.id and r.message.channel.id == ctx.channel.id try: reaction, user = await self.bot.wait_for( "reaction_add", check=pred, timeout=360 ) except asyncio.TimeoutError: return await msg.edit(content="This menu has expired", embed=e) if str(reaction.emoji) == "👍": e = discord.Embed(color=ctx.author.color) e.set_author(name=str(ctx.author), icon_url=ctx.author.avatar_url) if isinstance(ctx.guild, discord.Guild): e.set_thumbnail(url=ctx.guild.icon_url) e.description = appeal e.add_field(name="◈ Logged Ban Reason", value=str(ban_entry.reason)) e.set_footer(text=str(ctx.author.id)) appeal = await channel.send(embed=e) await appeal.add_reaction("👍") await appeal.add_reaction("👎") await appeal.add_reaction("🛑") await ctx.send("Sent your appeal request to CT") self.bot.appeal_ban[user_id] = { "cooldown": time() + 60 * 60 * 2, "banned": False, } self.bot.save() elif str(reaction.emoji) == "👎": await ctx.send( "Alright, feel free to resubmit with the correct parameters" ) else: await msg.clear_reaction(reaction.emoji)
def start_bot(self): print("Press Ctrl-C to quit.") print("Hold P to pause.") print("Hold I to get info.") try: while True: while True: cooldown_mark = time.time() farm_period = FARM_PERIOD_VALUE - (cooldown_mark - self.farm_period_mark) hire_last_hero_cooldown = HIRE_LAST_HERO_COOLDOWN_VALUE - ( cooldown_mark - self.hire_last_hero_cooldown_mark) rgb = get_color(self.positions["farm_mode"][0], self.positions["farm_mode"][1]) r = rgb[0] if not self.farm_mode and r == 255: if hire_last_hero_cooldown <= 0: print( "Progress stopped. Hiring last hero and assigning auto-clickers" ) reset_auto_clickers() time.sleep(1) set_auto_clickers_to_damage() time.sleep(1) set_auto_clicker_hire_hero( self.positions["hero_last_hireable"]) self.hire_last_hero_cooldown_mark = time.time() time.sleep(1) else: print( f"Farm mode enabled, waiting {FARM_PERIOD_VALUE} to disable." ) self.farm_mode = True if (cooldown_mark - self.farm_period_mark ) <= BOSS_FIGHT_FAIL_INTERVAL: self.boss_fight_fails += 1 if self.boss_fight_fails >= BOSS_FIGHT_FAILS_LIMIT: print( "Progress is not possible. Preparing to ascend" ) self.ascend() print( "Progress stopped. Interval of {:.2f}s. Count: {}. {} consecutive fails remaining to ascend" .format( cooldown_mark - self.farm_period_mark, self.boss_fight_fails, BOSS_FIGHT_FAILS_LIMIT - self.boss_fight_fails, )) print("Upgrading all heroes") upgrade_all() else: self.boss_fight_fails = 0 self.farm_period_mark = time.time() elif self.farm_mode and farm_period <= 0: print("Farm mode disabled") pyautogui.click( x=self.positions["farm_mode"][0], y=self.positions["farm_mode"][1], ) self.farm_mode = False try: # used try so that if user pressed other than the given key error will not be shown if keyboard.is_pressed("p"): # if key 'p' is pressed print("Bot stopped, press R to resume") break # finishing the loop elif keyboard.is_pressed("i"): self.output_cooldowns() else: pass except: pass # if user pressed other than the given key the loop will break self.pickup_gold() self.clickstorm_cooldown = POWERS[1]["cooldown_value"] - ( cooldown_mark - POWERS[1]["cooldown_mark"]) self.powersurge_cooldown = POWERS[2]["cooldown_value"] - ( cooldown_mark - POWERS[2]["cooldown_mark"]) self.lucky_strikes_cooldown = POWERS[3][ "cooldown_value"] - (cooldown_mark - POWERS[3]["cooldown_mark"]) self.metal_detector_cooldown = POWERS[4][ "cooldown_value"] - (cooldown_mark - POWERS[4]["cooldown_mark"]) self.golden_clicks_cooldown = POWERS[5][ "cooldown_value"] - (cooldown_mark - POWERS[5]["cooldown_mark"]) self.super_clicks_cooldown = POWERS[6][ "cooldown_value"] - (cooldown_mark - POWERS[6]["cooldown_mark"]) self.dark_ritual_cooldown = POWERS[7]["cooldown_value"] - ( cooldown_mark - POWERS[7]["cooldown_mark"]) self.energize_cooldown = POWERS[8]["cooldown_value"] - ( cooldown_mark - POWERS[8]["cooldown_mark"]) self.reload_cooldown = POWERS[9]["cooldown_value"] - ( cooldown_mark - POWERS[9]["cooldown_mark"]) self.check_and_use_power( 1, self.clickstorm_cooldown, self.energize_cooldown, self.reload_cooldown, ) self.check_and_use_power( 2, self.powersurge_cooldown, self.energize_cooldown, self.reload_cooldown, ) self.check_and_use_power( 3, self.lucky_strikes_cooldown, self.energize_cooldown, self.reload_cooldown, ) self.check_and_use_power( 4, self.metal_detector_cooldown, self.energize_cooldown, self.reload_cooldown, ) self.check_and_use_power( 5, self.golden_clicks_cooldown, self.energize_cooldown, self.reload_cooldown, ) self.check_and_use_power( 6, self.super_clicks_cooldown, self.energize_cooldown, self.reload_cooldown, ) if self.dark_ritual_cooldown <= 0 and self.reload_cooldown <= 0: time.sleep( 5 ) # Garante que o poder esteja carregado por conta do lag no jogo pyautogui.click( x=self.positions["powers"][0], y=self.positions["powers"][POWERS[7]["position"]], ) POWERS[7]["cooldown_mark"] = time.time() POWERS[7]["cooldown_value"] = ( POWERS[7]["cooldown_initial"] - 3600 ) # Reload effect pyautogui.click( x=self.positions["powers"][0], y=self.positions["powers"][POWERS[9]["position"]], ) # Reload POWERS[9]["cooldown_mark"] = time.time() keyboard.wait("r") print("Bot resumed") except KeyboardInterrupt: print("\n") print("Exiting...")
async def help(self, ctx, command=None): """Displays the help menu sorted by cog/class name.""" async def add_reactions(message): """Add reactions in the background to speed things up.""" for emoji_ in emojis: await message.add_reaction(emoji_) index = {} for cmd in [cmd for cmd in self.bot.commands if not cmd.hidden]: category = type(cmd.cog).__name__ if category not in index: index[category] = {} index[category][cmd.name] = cmd.description if command and command not in index.keys(): for cmd in self.bot.commands: if cmd.name == command: if not cmd.usage: return await ctx.send("That command has no usage") return await ctx.send(embed=cmd.usage) return await ctx.send("There's no help for that command") default = discord.Embed(color=utils.get_color(ctx.bot)) default.set_author(name="Help Menu", icon_url=self.bot.user.avatar_url) default.set_thumbnail(url=self.bot.config["thumbnail_url"]) value = "\n".join([ f"• `{category}` - {len(commands_)} commands" for category, commands_ in index.items() ]) default.add_field(name="◈ Categories", value=value) embeds = [default] for category, commands_ in index.items(): e = discord.Embed(color=utils.get_color(ctx.bot)) e.set_author(name=category, icon_url=self.bot.user.avatar_url) e.set_thumbnail(url=ctx.guild.icon_url) e.description = "\n".join( [f"\n• `{cmd}` - {desc}" for cmd, desc in commands_.items()]) embeds.append(e) pos = 0 if command: pos = [c.lower() for c in index.keys()].index(command.lower()) + 1 await ctx.message.delete() msg = await ctx.send(embed=embeds[pos]) emojis = ["⏮", "◀️", "⏹", "▶️", "⏭"] self.bot.loop.create_task(add_reactions(msg)) while True: def pred(react, usr): return (react.message.id == msg.id and usr == ctx.author and str(react.emoji) in emojis) try: reaction, user = await self.bot.wait_for("reaction_add", timeout=60.0, check=pred) except asyncio.TimeoutError: return await msg.clear_reactions() emoji = str(reaction.emoji) await msg.remove_reaction(reaction, ctx.author) i = emojis.index(emoji) if pos > 0 and i < 2: if i == 0: pos = 0 else: pos -= 1 elif pos < len(embeds) - 1 and i > 2: if i == 3: pos += 1 else: pos = len(embeds) - 1 elif i == 2: return await msg.delete() else: continue embeds[pos].set_footer(text=f"Page {pos + 1}/{len(embeds)}") await msg.edit(embed=embeds[pos])