async def run(self, ctx, *, cmd): bot.command_used(ctx, "run") fn_name = "_eval_expr" cmd = cmd.strip("` ") # add a layer of indentation cmd = "\n".join(f" {i}" for i in cmd.splitlines()) # wrap in async def body body = f"async def {fn_name}():\n{cmd}" parsed = ast.parse(body) body = parsed.body[0].body self.insert_returns(body) env = { 'bot': ctx.bot, 'discord': discord, 'commands': commands, 'ctx': ctx, 'time': time, 'client': bot.client, '__import__': __import__, 'reddit': reddit } exec(compile(parsed, filename="<ast>", mode="exec"), env) result = (await eval(f"{fn_name}()", env)) await ctx.send(result)
async def help(self, ctx): bot.command_used(ctx, "help") with open("commands.txt", 'r') as file: commands = file.read() commands_embed = discord.Embed(color=0x7A6C6C) commands_embed.add_field(name="Commands", value=commands, inline=False) commands_embed.set_thumbnail(url=bot_client.user.avatar_url) await ctx.channel.send(embed=commands_embed)
async def mimic(self, ctx, *args): bot.command_used(ctx, "mimic") mimic_message = (" ".join(args)) if '@' in mimic_message: await ctx.send("No pinging.") if mimic_message == "": await ctx.send("Please type a message to mimic.", delete_after=5) else: await ctx.message.delete() await ctx.send(" ".join(args))
async def findsub(self, ctx, sub_name): bot.command_used(ctx, "find sub") subList = "" for subreddit in bot.reddit.subreddits.search_by_name(str(sub_name)): subList += subreddit.display_name+"\n" if subList != "": await ctx.send("Subreddits matching: `" + sub_name + "` ```" + subList + "```") else: await ctx.send("No subs found")
async def crypto(self, ctx, coin, currency): bot.command_used(ctx, "crypto") data = YahooFinancials(coin + "-" + currency) if str(data) != "None" and str(data) != "": await ctx.send( f"**{coin.upper()} - {currency.upper()}**\nCurrent Value: `{str(data.get_current_price())}`\nDaily Low/High: `" + f"{str(data.get_daily_low())} `/` {str(data.get_daily_high())}`\nYearly Low/High: `{str(data.get_yearly_low())} `/` {str(data.get_yearly_high())}`" ) else: await ctx.send( "Invalid Listing or currency, listing and currency must be abbreviated e.g. ETH and GBP", delete_after=7)
async def stocks(self, ctx, stock): bot.command_used(ctx, "stocks") data = YahooFinancials(stock) if str(data.get_current_price()) != "None" and str( data.get_current_price()) != "": print(data.get_current_price()) await ctx.send( f"**{stock.upper()} - USD**\nCurrent Value: `{str(data.get_current_price())}`\nDaily Low/High: `" + f"{str(data.get_daily_low())} `/` {str(data.get_daily_high())}`\nYearly Low/High: `{str(data.get_yearly_low())} `/` {str(data.get_yearly_high())}`" ) else: await ctx.send( "Invalid Listing, listings must be abbreviated e.g. AMZN or TSLA", delete_after=7)
async def nsfw(self, category, ctx, subs): bot.command_used(ctx, category) posts = [] for submission in bot.reddit.subreddit(random.choice(subs)).top(random.choice(("month", "year", "all")), limit=100): posts.append(submission) posts.append(submission) post = random.choice(posts) if "redgif" in post.url or "imgur" in post.url: await ctx.send(f"**Here's some {category} from r/"+str(post.subreddit)+"**\n"+post.url) else: embed = discord.Embed(title=f"Here's some {category} from r/"+str(post.subreddit), timestamp=datetime.utcnow(), color=0x7A6C6C) embed.set_image(url=post.url) await ctx.send(embed=embed)
async def sudo(self, ctx, user, *message): bot.command_used(ctx, "sudo") user_to_copy = ctx.author if ctx.message.mentions: user_to_copy = ctx.message.mentions[0] else: for member in ctx.guild.members: if member.id == user or bot_client.get_user( member.id).name == user or member.display_name == user: user_to_copy = member break sudo_text = " ".join(message) await ctx.message.delete() webhook = await ctx.channel.create_webhook( name=user_to_copy.display_name) await webhook.send(content=sudo_text, avatar_url=user_to_copy.avatar_url) await webhook.delete()
def __init__(self, ctx): self.ctx = ctx bot.command_used(self.ctx, "blackjack") # creating the deck, player and dealer hands self.game_over = False self.vals = [ 2, 3, 4, 5, 6, 7, 8, 9, 10, 'jack', 'queen', 'king', 'ace' ] self.suits = ['spades', 'clubs', 'hearts', 'diamonds'] self.player_hand = [] self.player_score = 0 self.stand = False self.dealer_hand = [] self.dealer_score = 0 self.deck = list(itertools.product(self.vals, self.suits)) random.shuffle(self.deck) self.loop = asyncio.get_event_loop() self.loop.create_task(self.start_game())
async def serverinfo(self, ctx): bot.command_used(ctx, "server info") member_count = len(ctx.guild.members) serverInfoEmbed = discord.Embed(title=" Server Stats for " + str(ctx.guild), timestamp=datetime.utcnow(), color=0x7A6C6C) serverInfoEmbed.set_thumbnail(url=ctx.guild.icon_url) fields = [("ID", ctx.guild.id, True), ("Owner", "\@" + str(ctx.guild.owner), True), ("Region", ctx.guild.region, True), ("Created at", ctx.guild.created_at.strftime("%d/%m/%Y %H:%M:%S"), True), ("Text channels", len(ctx.guild.text_channels), True), ("Voice channels", len(ctx.guild.voice_channels), True), ("Members", str(member_count), True), ("Boosts", str(ctx.guild.premium_subscription_count), True), ("Roles", len(ctx.guild.roles), True)] for name, value, inline in fields: serverInfoEmbed.add_field(name=name, value=value, inline=inline) await ctx.channel.send(embed=serverInfoEmbed)
async def ping(self, ctx): bot.command_used(ctx, "ping") await ctx.send("`" + str(int(bot_client.latency * 1000)) + "`ms")
async def sub(self, ctx, sub_name, type="top", timeframe="all"): error = False try: bot.command_used(ctx, "sub") sub = bot.reddit.subreddit(sub_name) time_filter = "all" filter = "top" subreddit_category_posts = sub.top("all", limit=100) except: await ctx.send("No sub found") error = True # set the time filter based on the input if not error: if str(timeframe).lower() == "hour": time_filter = "hour" elif str(timeframe).lower() == "day": time_filter = "day" elif str(timeframe).lower() == "week": time_filter = "week" elif str(timeframe).lower() == "month": time_filter = "month" # set the trend filter based on the input if str(type).lower() == "hot": subreddit_category_posts = sub.hot(limit=100) filter = "Hot" elif str(type).lower() == "new": time_filter = "all" subreddit_category_posts = sub.new(limit=100) filter = "New" elif str(type).lower() == "controversial": subreddit_category_posts = sub.controversial(time_filter, limit=100) filter = "Controversial" posts = [] post_titles = [] count = 0 # append to list of posts and titles for submission in subreddit_category_posts: if not submission.stickied: posts.append(submission.url) post_titles.append(submission.title) # set reference to message and the template for the embed content message_template = f"**{filter} posts in {str(sub_name)} **\n**Timeframe: {time_filter} **\npost ` {str(count + 1)} / {str(len(posts))} `\n> {(post_titles[count])} \n {posts[count]}" reacted_message = await ctx.send(message_template) # add the reactions for scrolling for x in bot.reaction_emojis: await discord.Message.add_reaction(reacted_message, emoji=x) react_cross = False # check for reactions and update the embed based on the reaction (scroll) while not react_cross: check = Bot.reaction_check(message=reacted_message, author=ctx.author, emoji=('➡️', '⬅️', '⏪', '⏩', '🔀', '❌')) try: reaction, user = await bot_client.wait_for('reaction_add', timeout=90.0, check=check) if reaction.emoji == '➡️': count += 1 if count == (len(posts)): count = 0 elif reaction.emoji == '⬅️': count -= 1 if count == -1: count = (len(posts)-1) elif reaction.emoji == '⏩': count = (len(posts)-1) elif reaction.emoji == '⏪': count = 0 elif reaction.emoji == '🔀': count = random.randint(0, len(posts)) elif reaction.emoji == '❌': react_cross = True await discord.Message.edit(reacted_message, content=f"**{filter} posts in {str(sub_name)} **\n**Timeframe: {time_filter} **\npost ` {str(count + 1)} / {str(len(posts))} `\n> {(post_titles[count])} \n {posts[count]}") # if the check for reactions has expired update the message and catch the error except: await discord.Message.edit(reacted_message, content = message_template + "\n **-------------Timed Out-------------**")
async def img(self, ctx, *args): bot.command_used(ctx, "img") term = (" ".join(args)) url = 'https://bing.com/images/search?q=' + term + '&safeSearch=off' + '&count=100' + '&mkt=en-US' + '&adlt_set=off' user_agent_img = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0" headers = {"user-agent": user_agent_img} page = requests.get(url, headers=headers) soup = BeautifulSoup(page.content, "html.parser") count = 0 link_list = [] results = soup.find_all('a', class_='iusc', limit=100) for i in results: link_list.append(eval(i['m'])['murl']) img_embed = discord.Embed(title="Image results for " + str(term), description=('img `' + str(count + 1) + '/' + str(len(link_list)) + '`'), timestamp=datetime.utcnow(), color=0x7A6C6C) img_embed.set_image(url=link_list[count]) reacted_message = await ctx.channel.send(embed=img_embed) for x in bot.reaction_emojis: await discord.Message.add_reaction(reacted_message, emoji=x) react_cross = False while not react_cross: check = bot.reaction_check(message=reacted_message, author=ctx.author, emoji=('➡️', '⬅️', '⏪', '⏩', '🔀', '❌')) try: reaction, user = await bot_client.wait_for('reaction_add', timeout=90.0, check=check) if reaction.emoji == '➡️': count += 1 if count == (len(link_list)): count = 0 elif reaction.emoji == '⬅️': count -= 1 if count == -1: count = (len(link_list) - 1) elif reaction.emoji == '⏪': count = 0 elif reaction.emoji == '⏩': count = (len(link_list) - 1) elif reaction.emoji == '🔀': count = random.randint(0, len(link_list)) elif reaction.emoji == '❌': react_cross = True await discord.Message.delete(reacted_message) await update_img_search(reacted_message, link_list, count, term) except: img_embed = discord.Embed(title="Image results for " + str(term), description=('Timed Out'), timestamp=datetime.utcnow(), color=0x7A6C6C) await discord.Message.edit(reacted_message, embed=img_embed)