This repository has been archived on 2022-06-13. You can view files and clone it, but cannot push or open issues or pull requests.
KassouBot/src/cogs/internet.py

184 lines
10 KiB
Python
Raw Normal View History

import discord, json, requests, time, feedparser, os
2020-11-29 11:39:41 +01:00
from discord.ext import commands
from random import choice
from asyncpraw import Reddit
2020-11-29 11:39:41 +01:00
def setup(client):
client.add_cog(Internet(client))
class Internet(commands.Cog):
"""Commandes relatives à ce qui provient d'internet."""
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_message(self, message):
if message.channel.id == 770805818487865404 or message.channel.id == 772239638240165928: # Le groupe de l'amour ❤❤ -- channel chien/chat
chiens = ["dog", "chien", "potichien"]
chats = ["kat", "mace", "kater", "katze", "sinta", "minoos", "cat", "qitt", "besseh", "katu", "caun", "kazh",
"bisig", "moggy", "kotka", "maow", "gat", "we'sa", "guigna", "kodkod", "mao", "koyangi", "ghjattu", "míw", "pussi",
"gato", "gata", "kato", "kass", "domadh", "demmat", "kissa", "chat", "minou", "piscín", "cath", "k'at'a", "muca", "gali",
"gatos", "popoki", "kike", "chatul", "chatula", "billa", "kat poes", "macska", "cica", "kutjing", "kucing", "köttur",
"gatto", "gattina", "neko", "chma", "pising", "feles", "felix", "kakis", "katé", "qattus", "qattusa", "ngeru", "miz", "felino",
"felina", "muur", "katt", "shimii", "billi", "gorbe", "pusa", "kot", "giat", "pisica", "koshka", "pusi", "macka", "mizhu",
"kotsur", "bisad", "büsi", "chatz", "paka", "muc", "poonai", "puunay", "kocour", "kocka", "maa-oh", "kedi", "kit", "con mêo",
2020-12-23 00:47:17 +01:00
"tchèt", "mouss", "ologbo", "kats", "", "кот", "고양이", "poticha", "😼", "ʇɐɥɔ"]
2020-11-29 11:39:41 +01:00
if message.content.lower() in chiens:
await self._dog(await self.client.get_context(message))
if message.content.lower() in chats:
await self._cat(await self.client.get_context(message))
@commands.command(name='memes', aliases = ['meme'])
2021-05-12 02:46:04 +02:00
async def _memes(self, ctx, *, args = None):
"""Envois un meme de reddit.\n ➡ Syntaxe: {PREFIX}memes/meme [subreddit]"""
2020-11-29 11:39:41 +01:00
2021-05-12 02:46:04 +02:00
if args: # s'il y a un subreddit de défini
subredditchoix = args
else: # s'il n'y en a pas
subredditchoix = choice(['memes', 'anime_irl', 'goodanimemes', 'BikiniclienttomTwitter', 'dankmemes', 'DeepFried',
'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'])
2020-11-29 11:39:41 +01:00
2021-05-12 02:46:04 +02:00
try:
async with Reddit(client_id = os.environ['TOKEN_REDDIT_CLIENT_ID'], client_secret = os.environ['TOKEN_REDDIT_CLIENT_SECRET'], user_agent = f"disreddit /u/{os.environ['TOKEN_REDDIT_USER_AGENT']}, http://localhost:8080") as reddit:
subreddit = await reddit.subreddit(subredditchoix) # récupération du subreddit
hot = subreddit.top(limit = 20) # récupération des memes avec une limite aux 10 premiers memes
all_subs = [item async for item in hot] # liste des memes
submission = choice(all_subs) # choix aléatoire
2020-11-29 11:39:41 +01:00
image = ["png", "jpg", "jpeg", "bmp", "gif"]
if submission.url[-3:] in image:
embed = discord.Embed(title = f"r/{subredditchoix} pour {ctx.author.name}", color = discord.Colour.random(), description = f"[lien du meme]({submission.url})")
2020-11-29 11:39:41 +01:00
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:
2021-05-12 02:46:04 +02:00
print(f"Error in _memes command = args: {args}, subreddit: {subredditchoix}, error: {error}")
2020-11-29 11:39:41 +01:00
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: {PREFIX}cat/chat"""
2020-11-29 11:39:41 +01:00
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 = discord.Colour.random())
2020-11-29 11:39:41 +01:00
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: {PREFIX}dog/chien"""
2020-11-29 11:39:41 +01:00
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 = discord.Colour.random())
2020-11-29 11:39:41 +01:00
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('❤️')
@commands.command(name='sexe', aliases=['sexes', 'nude', 'nudes', 'nsfw'])
async def _sexe(self, ctx, *, choice_of_nsfw = None):
"""Envois une image coquine. (NSFW)\n ➡ Syntaxe: {PREFIX}sexe/sexes/nude/nudes [butts/boobs]"""
2020-11-29 11:39:41 +01:00
liste_hot = ['butts', 'boobs']
if choice_of_nsfw in liste_hot:
pass
else:
choice_of_nsfw = choice(liste_hot)
if ctx.channel.is_nsfw():
embed = discord.Embed(title = f"{choice_of_nsfw.capitalize()} pour {ctx.author.name}", colour = discord.Colour.random())
2020-11-29 11:39:41 +01:00
nsfw = self._random_image(f'http://api.o{choice_of_nsfw}.ru/noise/')
embed.set_image(url = f"http://media.o{choice_of_nsfw}.ru/{nsfw[0][0]['preview']}")
embed.set_footer(text = f"o{choice_of_nsfw}.ru a pris {nsfw[1]} ms.")
await ctx.message.add_reaction(emoji = '')
await ctx.send(embed = embed)
else:
await ctx.message.add_reaction(emoji = '')
2020-11-29 11:59:49 +01:00
await ctx.send(f"Désolé mais je n'envois ce genre de message seulement dans les salons NSFW !")
2020-12-11 12:58:58 +01:00
@commands.command(name='news', aliases=['rss'])
2020-12-11 14:26:17 +01:00
async def _news(self, ctx, *, arg = ""):
"""Info random dans le domaine de l'informatique\n ➡ Syntaxe: {PREFIX}news/rss [site/liste]"""
2020-12-11 14:26:17 +01:00
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()])
2020-12-11 12:58:58 +01:00
2020-12-11 14:26:17 +01:00
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 = discord.Colour.random(), description = ", ".join([key.capitalize() for key in rss_website.keys()]))
2020-12-11 14:26:17 +01:00
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))])
2020-12-11 14:33:03 +01:00
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 = discord.Colour.random(), description = f"[**lien de la news**]({info.link})\n\n{desc}")
2020-12-11 14:34:48 +01:00
try:
embed.set_author(name = info.author)
except:
pass
2020-12-11 14:26:17 +01:00
embed.set_footer(text = f"News de {choix_site.capitalize()}")
await ctx.send(embed = embed)
2020-12-11 12:58:58 +01:00
await ctx.message.add_reaction(emoji = '')