This repository has been archived on 2022-03-31. You can view files and clone it, but cannot push or open issues or pull requests.
bot-licence/cogs/internet.py

150 lines
7.5 KiB
Python
Raw Normal View History

2020-12-11 15:45:42 +01:00
import discord, praw, json, requests, datetime, time, feedparser
from discord.ext import commands
from random import randint, choice
from tokens import token_reddit as token # à l'importation de l'extension, le fichier se retrouve dans le '/' et non dans 'cogs/', ignorez l'erreur pylint si il y a
def setup(bot):
bot.add_cog(Internet(bot))
class Internet(commands.Cog):
"""Commandes relatives à ce qui provient d'internet."""
def __init__(self, bot):
self.bot = bot
@commands.command(name='memes', aliases = ['meme'])
async def _memes(self, ctx, *, args = ""):
"""Envois un meme de reddit.\n ➡ Syntaxe: .memes/meme [subreddit]"""
try:
2020-12-11 15:43:11 +01:00
reddit = praw.Reddit(client_id = token['client_id'], client_secret = token['client_secret'], user_agent = f"disreddit /u/{token['user_agent']}, http://localhost:8080")
if args != "": # si il y a un arg différent d'un meme
subredditchoix = args
else: # si il n'y a pas d'arguments
subredditchoix = choice(['memes', 'anime_irl', 'goodanimemes', 'BikiniclienttomTwitter', 'dankmemes', 'DeepFriedMemes',
'educationalmemes', 'funny', 'marvelmemes', 'me_irl', 'meme', 'MemeEconomy', 'Memes_Of_The_Dank', 'MinecraftMemes',
'physicsmemes', 'reactiongifs', 'blackpeopletwitter', 'metal_me_irl', 'bee_irl', '195',
'shittyadviceanimals', 'meirl', '2meirl4meirl', 'AdviceAnimals', 'weirdmemes'])
memes_submissions = reddit.subreddit(subredditchoix).hot()
post_to_pick = randint(1, 10)
for i in range(0, post_to_pick): # i pas important
i = i #retire l'erreur sur vscode
submission = next(x for x in memes_submissions if not x.stickied)
image = ["png", "jpg", "jpeg", "bmp", "gif"]
if submission.url[-3:] in image:
embed = discord.Embed(title = f"r/{subredditchoix} pour {ctx.author.name}", color = randint(0, 0xFFFFFF), description = f"[lien du meme]({submission.url})")
embed.set_footer(text = f"Meme de Reddit")
embed.set_image(url = submission.url)
message = await ctx.send(embed = embed)
else:
await ctx.send(f"```r/{subredditchoix} pour {ctx.author.name}```\n{submission.url}")
message = await ctx.send("```Meme de Reddit```")
await ctx.message.add_reaction(emoji = '')
await message.add_reaction('👍')
return await message.add_reaction('👎')
except Exception as error:
print(f"args: {args}, subreddit: {subredditchoix}, error: {error}")
await ctx.message.add_reaction(emoji = '')
return await ctx.send(f"Ce subreddit est interdit, mis en quarantaine ou n'existe pas. ({subredditchoix})")
def _random_image(self, link):
temps_requete = int(round(time.time() * 1000))
try:
request_data = requests.get(link)
except Exception as e:
raise Exception(f"Une erreur s'est produite lors de la tentative de demande de l'API {link} : {e}")
if not request_data.status_code == 200:
raise Exception(f"Code HTTP {request_data.status_code} au lieu de HTTP 200 à l'appel de {link} : {request_data.text}")
try:
json_data = json.loads(request_data.text)
except Exception as e:
raise Exception(f"Erreur lors de la transformation les données de {link} en json : {e}")
temps_requete = int(round(time.time() * 1000)) - temps_requete
return (json_data, temps_requete)
@commands.command(name='cat', aliases = ['chat'])
async def _cat(self, ctx):
"""Te montre un magnifique chat\n ➡ Syntaxe: .cat/chat"""
if ctx.author.nick:
name = f"{ctx.author.nick} ({ctx.author.name}#{ctx.author.discriminator})"
else:
name = f"{ctx.author.name}"
embed = discord.Embed(title = f"Poticha pour {name}", colour = randint(0, 0xFFFFFF))
cat = self._random_image("http://aws.random.cat/meow")
embed.set_image(url = cat[0]['file'])
embed.set_footer(text = f"random.cat a pris {cat[1]} ms.")
await ctx.message.add_reaction(emoji = '')
message = await ctx.send(embed=embed)
return await message.add_reaction('❤️')
@commands.command(name='dog', aliases = ['chien'])
async def _dog(self, ctx):
"""Te montre un magnifique chien\n ➡ Syntaxe: .dog/chien"""
if ctx.author.nick:
name = f"{ctx.author.nick} ({ctx.author.name}#{ctx.author.discriminator})"
else:
name = f"{ctx.author.name}"
embed = discord.Embed(title = f"Potichien pour {name}", colour = randint(0, 0xFFFFFF))
dog = self._random_image("https://dog.ceo/api/breeds/image/random")
embed.set_image(url = dog[0]['message'])
embed.set_footer(text = f"dog.ceo a pris {dog[1]} ms.")
await ctx.message.add_reaction(emoji = '')
message = await ctx.send(embed=embed)
return await message.add_reaction('❤️')
2020-12-11 15:45:42 +01:00
@commands.command(name='news', aliases=['rss'])
async def _news(self, ctx, *, arg = ""):
"""Info random dans le domaine de l'informatique\n ➡ Syntaxe: .news/rss [site/liste]"""
rss_website = {
"anandtech": "https://www.anandtech.com/rss/",
"arstechnica": "https://arstechnica.com/feed",
"certssi": "https://www.cert.ssi.gouv.fr/feed/",
"frenchlegion": "http://frenchlegion.eu/feed/",
"guru3d": "https://www.guru3d.com/news_rss",
"hardwareleaks": "https://hardwareleaks.com/feed",
"lesnumeriques": "https://www.lesnumeriques.com/rss.xml",
"overclock3d": "https://www.overclock3d.net/xmlfeed",
"overclocking": "https://overclocking.com/feed/",
"pcper": "https://pcper.com/feed",
"rtings": "https://www.rtings.com/reviews-rss.xml",
"storagereview": "https://www.storagereview.com/feed",
"techpowerupnews": "https://www.techpowerup.com/rss/news",
"techpowerupreviews": "https://www.techpowerup.com/rss/reviews",
"techspot": "https://www.techspot.com/backend.xml",
"videocardz": "https://videocardz.com/feed",
"vonguru": "https://vonguru.fr/feed/"
}
choix_site = choice([key for key in rss_website.keys()])
if arg.lower() in rss_website: # si on specifie la source
choix_site = arg.lower()
if arg.lower() == "liste":
embed = discord.Embed(title = "Liste des sources", color = randint(0, 0xFFFFFF), description = ", ".join([key.capitalize() for key in rss_website.keys()]))
return await ctx.send(embed = embed)
newsfeed = feedparser.parse(rss_website[choix_site])
info = choice([newsfeed.entries[i] for i in range(0, 10 if len(newsfeed.entries) > 10 else len(newsfeed.entries))])
desc = "Pas de description trouvée." if "<p>" in info.description or "</a>" in info.description else info.description
embed = discord.Embed(title = info.title, color = randint(0, 0xFFFFFF), description = f"[**lien de la news**]({info.link})\n\n{desc}")
try:
embed.set_author(name = info.author)
except:
pass
embed.set_footer(text = f"News de {choix_site.capitalize()}")
#embed.set_image(url = submission.url)
await ctx.send(embed = embed)
await ctx.message.add_reaction(emoji = '')