You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

181 lines
5.8KB

  1. import random
  2. import requests
  3. from lxml import html
  4. from bs4 import BeautifulSoup
  5. from discord.ext.commands import bot
  6. from Roxbot import checks
  7. from Roxbot.logging import log
  8. from Roxbot.settings import guild_settings
  9. # Warning, this cog sucks so much but hopefully it works and doesn't break the bot too much.
  10. # Just lazily edited old code and bodged it into this one.
  11. # There is redundant code here that if removed would make it easier.
  12. # Edit, cleaned up a lot more. But it still is a bit dodgy, when discord allows for the video object to be used in embeds, then we need to convert the cog to output embeds.
  13. def _imgur_removed(url):
  14. page = requests.get(url)
  15. soup = BeautifulSoup(page.content, 'html.parser')
  16. if "removed.png" in soup.img["src"]:
  17. return True
  18. else:
  19. return False
  20. def imgur_get(url):
  21. if url.split(".")[-1] in ("png", "jpg", "jpeg", "gif", "gifv"):
  22. return url
  23. else:
  24. if _imgur_removed(url):
  25. return False
  26. page = requests.get(url)
  27. soup = BeautifulSoup(page.content, 'html.parser')
  28. links = []
  29. for img in soup.find_all("img"):
  30. if "imgur" in img["src"]:
  31. if not img["src"] in links:
  32. links.append(img["src"])
  33. for video in soup.find_all("source"):
  34. if "imgur" in video["src"]:
  35. if not video["src"] in links:
  36. links.append(video["src"])
  37. if len(links) > 1:
  38. return url
  39. else:
  40. if "http" not in links[0]:
  41. links[0] = "https:" + links[0]
  42. return links[0]
  43. def ero_get(url):
  44. if url.contains("eroshare"):
  45. url = "https://eroshae.com/" + url.split("/")[3]
  46. page = requests.get(url)
  47. tree = html.fromstring(page.content)
  48. links = tree.xpath('//source[@src]/@src')
  49. if links:
  50. return False
  51. links = tree.xpath('//*[@src]/@src')
  52. if len(links) > 2:
  53. return False
  54. for link in links:
  55. if "i." in link and "thumb" not in link:
  56. return "https:" + link
  57. def subreddit_request(subreddit):
  58. options = [".json?count=1000", "/top/.json?sort=top&t=all&count=1000"]
  59. choice = random.choice(options)
  60. subreddit += choice
  61. r = requests.get("https://reddit.com/r/"+subreddit, headers={'User-agent': 'RoxBot Discord Bot'})
  62. try:
  63. reddit = r.json()["data"]
  64. except KeyError:
  65. return {}
  66. return reddit
  67. def parse_url(url):
  68. if url.split(".")[-1] in ("png", "jpg", "jpeg", "gif", "gifv", "webm", "mp4", "webp"):
  69. return url
  70. if "imgur" in url:
  71. return imgur_get(url)
  72. elif "eroshare" in url or "eroshae" in url or "erome" in url:
  73. return ero_get(url)
  74. elif "gfycat" in url or "redd.it" in url or "i.reddituploads" in url or "media.tumblr" in url or "streamable" in url:
  75. return url
  76. else:
  77. return False
  78. class Reddit():
  79. def __init__(self, bot_client):
  80. self.bot = bot_client
  81. @bot.command()
  82. async def subreddit(self, ctx, subreddit):
  83. """
  84. Grabs an image or video (jpg, png, gif, gifv, webm, mp4) from the subreddit inputted.
  85. Example:
  86. {command_prefix}subreddit pics
  87. """
  88. subreddit = subreddit.lower()
  89. links = subreddit_request(subreddit)
  90. title = ""
  91. if not links:
  92. return await ctx.send("Error ;-; That subreddit probably doesn't exist. Please check your spelling")
  93. else:
  94. if not links["after"]: # This is if we are given a search page that has links in it.
  95. return await ctx.send("Error ;-; That subreddit probably doesn't exist. Please check your spelling")
  96. url = ""
  97. for x in range(10):
  98. choice = random.choice(links["children"])
  99. if choice["data"]["over_18"] and not checks.nsfw_predicate(ctx):
  100. return await ctx.send("This server/channel doesn't have my NSFW stuff enabled. This extends to posting NFSW content from Reddit.")
  101. url = parse_url(choice["data"]["url"])
  102. if url:
  103. title = "**{}** \nby /u/{} from /r/{}\n".format(choice["data"]["title"], choice["data"]["author"], subreddit)
  104. break
  105. if not url:
  106. return await ctx.send("I couldn't find any images from that subreddit.")
  107. if url.split("/")[-2] == "a":
  108. text = "This is an album, click on the link to see more.\n"
  109. else:
  110. text = ""
  111. if ctx.invoked_with == "subreddit":
  112. # Only log the command when it is this command being used. Not the inbuilt commands.
  113. logging = guild_settings.get(ctx.guild).logging
  114. log_channel = self.bot.get_channel(logging["channel"])
  115. await log(ctx.guild, log_channel, "subreddit", User=ctx.author, Subreddit=subreddit, Returned="<{}>".format(url), Channel=ctx.channel, Channel_Mention=ctx.channel.mention)
  116. return await ctx.send(title + text + url)
  117. @bot.command()
  118. async def aww(self, ctx):
  119. """
  120. Gives you cute pics from reddit
  121. """
  122. subreddit = "aww"
  123. return await ctx.invoke(self.subreddit, subreddit=subreddit)
  124. @bot.command()
  125. async def feedme(self, ctx):
  126. """
  127. Feeds you with food porn. Uses multiple subreddits.
  128. Yes, I was very hungry when trying to find the subreddits for this command.
  129. Subreddits: "foodporn", "food", "DessertPorn", "tonightsdinner", "eatsandwiches", "steak", "burgers", "Pizza", "grilledcheese", "PutAnEggOnIt", "sushi"
  130. """
  131. subreddits = ["foodporn", "food", "DessertPorn", "tonightsdinner", "eatsandwiches", "steak", "burgers", "Pizza", "grilledcheese", "PutAnEggOnIt", "sushi"]
  132. subreddit_choice = random.choice(subreddits)
  133. return await ctx.invoke(self.subreddit, subreddit=subreddit_choice)
  134. @bot.command()
  135. async def feedmevegan(self, ctx):
  136. """
  137. Feeds you with vegan food porn. Uses multiple subreddits.
  138. Yes, I was very hungry when trying to find the subreddits for this command.
  139. Subreddits: "veganrecipes", "vegangifrecipes", "veganfoodporn"
  140. """
  141. subreddits = ["veganrecipes", "vegangifrecipes", "VeganFoodPorn"]
  142. subreddit_choice = random.choice(subreddits)
  143. return await ctx.invoke(self.subreddit, subreddit=subreddit_choice)
  144. @bot.command(aliases=["gssp"])
  145. async def gss(self, ctx):
  146. """
  147. Gives you the best trans memes ever
  148. """
  149. subreddit = "gaysoundsshitposts"
  150. return await ctx.invoke(self.subreddit, subreddit=subreddit)
  151. def setup(bot_client):
  152. bot_client.add_cog(Reddit(bot_client))