kabot/kabot/kabot/utils/texte.py
2023-12-29 11:54:19 +01:00

471 lines
19 KiB
Python

# -*- coding: utf-8 -*-
"""Main module."""
from __future__ import unicode_literals
import aiocron
import asyncio
import discord
import giphy_client
import gitlab
import logging
import lxml
import os
import random
import requests
import configparser
import argparse
import typing
import functools
from bs4 import BeautifulSoup as bs
from discord.ext import tasks, commands
from giphy_client.rest import ApiException
from logging.handlers import RotatingFileHandler
from pathlib import Path
from subprocess import *
from sys import argv,exit, exc_info
here = os.path.dirname(os.path.abspath(__file__))
class Texte(commands.Cog):
#class Mybot(discord.Client):
#Fonctions necesaires pour Kabot.
def __init__(
self,
bot,
intents=None,
gl_url=None,
gl_token=None,
gif_token=None,
audio_path=None,
nickname=None,
voice_chan=None,
text_chan=None,
):
self.gl_url = gl_url
self.gl_token = gl_token
self.gif_token = gif_token
self.voice_chan = voice_chan
self.text_chan = text_chan
self.bot = bot
self.nickname = nickname
@commands.Cog.listener()
async def on_ready(self):
for channel in bot.get_all_channels():
if channel.name == text_channel:
current_chan = channel
if nickname:
await bot.user.edit(nick=nickname)
await current_chan.send('Le troll est dans la place !')
self.kron.start()
@commands.Cog.listener()
async def on_message(self, message):
if message.author == self.bot.user or message.content.startswith('!'):
if message.content.startswith('!'):
for channel in self.bot.get_all_channels():
if channel.name == self.text_chan:
current_chan = channel
async for msg in current_chan.history(limit=1):
last_message = msg
ctx = await self.bot.get_context(last_message)
ctx.message.content = ""
cmd_name = message.content.split()[0].replace('!','')
cmd = self.bot.get_command(cmd_name)
await cmd.invoke(ctx)
return
else:
if self.bot.user in message.mentions \
and len(message.mentions) < 3 \
and len(message.content.splitlines()) == 1:
path = '/data/log/%s.log' % message.channel
with open(path, 'r') as f:
lines = f.read().splitlines()
if not message.content in lines:
with open(path, 'a') as f:
f.write(message.content + '\n')
response = random.choice(lines).replace(str(self.bot.user.id), str(message.author.id))
async with message.channel.typing():
if "http" in response:
await asyncio.sleep(len(response) / 8)
else:
await asyncio.sleep(len(response) / 6)
await message.channel.send(response)
await self.bot.process_commands(message)
@commands.command(help='list des commits')
async def commits(self, ctx, number = 5):
try:
if self.gl_url and self.gl_token:
number = int(number)
gl = gitlab.Gitlab(self.gl_url, self.gl_token)
gl.auth()
projects = gl.projects.list(search='Kabot')[0]
commits = projects.commits.list(all=True)[:number]
for commit in commits:
detail = commit.attributes
await ctx.channel.send("__" + detail['author_name'] + "__: " + detail['title'] + '\n' + detail['web_url'])
else:
await ctx.channel.send("-_-")
except:
await ctx.channel.send("-_-")
@commands.command(help="Interrogation issues \n Args: list, search[mot clé] et add[nom de l'issue]")
async def issue(self, ctx, *args):
if self.gl_url and self.gl_token:
if args:
args = list(args)
gl = gitlab.Gitlab(self.gl_url, self.gl_token)
gl.auth()
if args[0] == 'list':
projects = gl.projects.list(search='Kabot')[0]
issues = projects.issues.list()
for issue in issues:
if "closed" == issue.state:
pass
else:
await ctx.channel.send('#' + str(issue.id) + ": " + issue.title + '\n' + issue.web_url)
elif args[0] == 'search':
query = ''.join(args[1:])
project = gl.projects.list(search='Kabot')[0]
find_issues = project.search("issues", query)
for issue in find_issues:
await ctx.channel.send("#" + str(issue['id']) + ": " + issue['title'] + '\n' + issue['web_url'])
elif args[0] == 'add':
title = ' '.join(args[1:])
author = title + ' - By ' + ctx.message.author.name
projects = gl.projects.list()
for project in projects:
if "Kabot" == project.name:
issue = project.issues.create({'title': author})
logger.info("Issue created : %s" % issue.web_url)
else:
await ctx.channel.send('unknown command')
@commands.command(help='count lines numbers in quote file')
async def lines(self, ctx):
path = '/data/log/%s.log' % ctx.channel
with open(path, 'r') as f:
lines = f.read().splitlines()
nb_lines = len(lines)
async with ctx.channel.typing():
await asyncio.sleep(0.5)
await ctx.channel.send("j'ai %s lignes dans mon stock" % nb_lines)
@commands.command(help='check if bot always online')
async def ping(self, message):
await message.channel.send('pong')
@commands.command(help='Restart Bot')
async def restart(self, ctx):
cmd = self.bot.get_command('leave')
await cmd.invoke(ctx)
await self.bot.close()
exit()
@commands.command(help='Update local repo')
async def update(self, message):
output = Popen('git pull'.split(), stdout=PIPE).communicate()[0]
cmd_audio = "git -C %s pull" % self.audio_path
output += Popen(cmd_audio.split(), stdout=PIPE).communicate()[0]
await message.channel.send(output.decode('utf-8'))
@commands.command(help="randomsur l'avenir des gens.")
async def avenir(self, ctx):
list_mot = ("tu seras curé, tu t'occuperas plus spécialement du catéchisme. ",
"tu seras animateur de soirées pour les gays pride. ",
"tu seras gynecologue dans une maison de retraite.",
"tu iras vivre en thaïland à cause de ton job. car tu seras ladyboy dans un bar.",
"tu sera DSI chez jacky et Michel",
"tu seras arroseur de plante aquatique.")
choix = random.choice(list_mot)
async with ctx.channel.typing():
await asyncio.sleep(len(choix) / 4)
await ctx.channel.send(choix)
@commands.command(help="j'adore la cuisine")
async def ciboulette(self, ctx):
cmd = self.bot.get_command('gif')
ctx.message.content = "!gif ciboulette"
await cmd.invoke(ctx)
@commands.command(help='Faire des choix')
async def choice(self, ctx, *words):
choices = random.choice(words)
await ctx.channel.send(choices)
@commands.command(help="optionnal args : ")
async def contrepeterie(self, ctx, *args):
response = None
path = here + '/ressources/contrepeteries.txt'
with open(path) as file:
lines = file.read().splitlines()
myline = random.choice(lines)
question, reponse = myline.split(";")
try:
response = '''Question ! : %s Réponse : ||%s||''' % (question, reponse)
except:
response = "Unknow error, try: !contrepeterie [mot clef]"
await ctx.send(response)
@commands.command(help='Gif me')
async def gif(self, ctx):
query = ctx.message.content.replace('!gif ', '')
api_instance = giphy_client.DefaultApi()
api_key = self.gif_token
lang = 'fr'
if api_key:
try:
api_response = api_instance.gifs_search_get(api_key, query, lang=lang, limit=15)
api_response.to_dict()['data'][0]
get_url = random.choice(api_response.to_dict()['data'])
get_url['url']
await ctx.channel.send(get_url['url'])
except ApiException as e:
await ctx.channel.send("Exception when calling DefaultApi->gifs_search_get: %s\n" % e)
else:
await ctx.channel.send("Exception : No api key found")
@commands.command(help="optionnal args : [livre] [character]")
async def kaamelott(self, ctx, *args):
response = None
url = 'https://kaamelott.chaudie.re/api/random'
if args and ctx.message.content:
args = list(args)
if args[0].isdigit():
livre = int(args[0])
args.pop(0)
elif args[-1].isdigit():
livre = int(args[-1])
args.pop(-1)
else:
livre = None
if args:
perso = ' '.join(args)
if perso and livre:
url = 'https://kaamelott.chaudie.re/api/random/livre/%s/personnage/%s' % (livre, perso)
elif perso:
url = 'https://kaamelott.chaudie.re/api/random/personnage/%s' % perso
else:
url = 'https://kaamelott.chaudie.re/api/random/livre/%s' % livre
try:
citation = requests.get(url).json()['citation']
response = "%s :\n```\n%s\n```" % (citation['infos']['personnage'], citation['citation'])
except:
response = "Unknow error, try: !kaamelott [livre] [character]"
await ctx.send(response)
@commands.command(help="Je menotte une cornemuse et je fume Eddy Malou")
async def kamoulox(self, ctx):
sans_verbe = get_word('nom').text + " " + get_word('complement').get('m') + " et " + get_word('nom').text + " " + get_word('complement').get('m') + "."
nom1 = get_word('nom')
nom2 = get_word('nom')
un1 = "un"
un2 = "un"
if nom1.get('gender') == 'F':
un1 = "une"
if nom2.get('gender') == 'F':
un2 = "une"
phrase1 = get_word('verbe').text + " " + un1 + " " + nom1.text + " " + random.choice([get_word('complement').get('m'), ""])
phrase2 = get_word('verbe').text + " " + un2 + " " + nom2.text + " " + random.choice([get_word('complement').get('m'), ""])
avec_verbe = phrase1 + " et " + phrase2 + "."
piece = random.choice(['pile', 'face'])
if piece == "pile":
result = sans_verbe
elif piece == "face":
result = avec_verbe
async with ctx.channel.typing():
await asyncio.sleep(len(result)/6)
await ctx.send(result)
@commands.dm_only()
@commands.command(help="Faire dire des choses au bot")
async def say(self, ctx, *message):
sentence = ' '.join(message)
channel = [x for x in self.bot.get_all_channels() if x.name == self.text_chan][0]
guild = self.bot.guilds[0]
if sentence.startswith('!'):
command_name = sentence.split()[0].replace('!', '')
cmd = self.bot.get_command(command_name)
ctx.channel = channel
ctx.guild = guild
for word in sentence.split():
if word.startswith('@'):
members = guild.members
for member in members:
if member.nick.lower() == wordi.lower()[1:]:
sentence = sentence.replace(word, member.mention)
ctx.message = sentence
await cmd.invoke(ctx)
else:
for word in sentence.split():
if word.startswith('@'):
members = guild.members
for member in members:
if member.display_name.lower() in word.lower():
sentence = sentence.replace(word, member.mention)
await channel.send(sentence)
@commands.command(help='Who the fuck am i?')
async def schizo(self, ctx, *names):
name = ' '.join(names)
list_name = ["Kabot", "Gaspard et Balthazar", "Bender", "Zoidberg", "Gunther", "MissSaugnacEtCambran2022"]
try:
current_name = self.bot.user.name
list_name.remove(current_name)
except:
pass
if not name:
name = random.choice(list_name)
lower_names = [x.lower() for x in list_name]
if name.lower() in lower_names:
if name:
correct_name = [x for x in list_name if x.lower() in name.lower()][0]
name = correct_name
await self.bot.user.edit(username=name)
else:
name = "404"
await self.bot.user.edit(username="Error 404 name not found!")
await ctx.channel.send("Liste des noms = %s" % list_name)
img = open(here + "/ressources/avatar_bot/%s.jpg" % name, 'rb')
await self.bot.user.edit(avatar=img.read())
await self.joke(ctx, name)
@tasks.loop(seconds=3600)
async def kron(self):
kron_choice = random.choice([self.kaamelott, self.slap, self.kamoulox, self.contrepeterie, self.schizo, None, None, None, None, None, None])
if kron_choice != None:
await asyncio.sleep(random.choice(range(3550)))
for channel in self.bot.get_all_channels():
if channel.name == self.text_chan:
current_chan = channel
async for msg in current_chan.history(limit=1):
last_message = msg
ctx = await self.bot.get_context(last_message)
ctx.message.content = ""
await kron_choice(ctx)
@commands.command(help='slap this ass')
async def slap(self, ctx, user=None):
slap_multiple = [
"%s prend un coup de pied au cul",
"Descente du coude sur %s",
"%s est propulsé par dessus la TROISIEME CORDE!",
"Le mec en rose, c'est moi et le mec en jaune c'est %s! https://giphy.com/gifs/gSIz6gGLhguOY",
]
if not user or not ctx.message.mentions:
online_members = []
members = ctx.guild.members
for member in members:
if str(member.status) == "online":
online_members.append(member)
user = random.choice(online_members)
user = user.mention
elif ctx.message.mentions:
user = ctx.message.mentions[0]
user = user.mention
if user == self.bot.user.mention:
async with ctx.channel.typing():
await asyncio.sleep(0.5)
await ctx.channel.send("je tribuche par terre et je sais pas comment")
else:
async with ctx.channel.typing():
await asyncio.sleep(len(slap_multiple) / 4)
await ctx.channel.send(random.choice(slap_multiple) % user)
#Commandes pour troll.
@commands.command(help='Troll commands', hidden=True)
async def jke(self, ctx):
await ctx.channel.send(trollpower())
@commands.command(help='Troll commands', hidden=True)
async def joe(self, ctx):
await ctx.channel.send(trollpower())
@commands.command(help='Troll commands', hidden=True)
async def jok(self, ctx):
await ctx.channel.send(trollpower())
@commands.command(help='Troll commands', hidden=True)
async def joker(self, ctx):
await ctx.channel.send(trollpower(too_long=True))
@commands.command(help='Troll commands', hidden=True)
async def oke(self, ctx):
await ctx.channel.send(trollpower())
def trollpower(too_long=None):
if too_long:
return("Bah alors, on sait plus écrire, je te donne un indice: t'as une lettre en trop! :sweat_drops: :tongue:")
return('Bah alors, on sait plus écrire, je te donne un indice: il te manque une lettre! :sweat_drops: :tongue:')
def get_word(word_type):
"""Chercher les mots pour la fonction kamoulox dans le fichier xml"""
content = []
with open(here + "/ressources/base_kml.xml", "r", encoding="ISO-8859-1") as file:
content = file.readlines()
content = "".join(content)
bs_content = bs(content, 'lxml')
if word_type == 'nom':
nom = bs_content.resources.nom.find_all('word')
result = random.choice(nom)
return result
elif word_type == 'nom_propre':
nom_propre = bs_content.resources.nompropre.find_all('word')
result = random.choice(nom_propre)
return result
elif word_type == 'verbe':
verbe = bs_content.resources.verbe.find_all('word')
result = random.choice(verbe)
return result
elif word_type == 'complement':
complement = bs_content.resources.complement.find_all('word')
result = random.choice(complement)
return result
elif word_type == 'nom_special':
nom_special = bs_content.resources.complement.find_all('word')
result = random.choice(nom_special)
return result
elif word_type == 'prenom':
prenom = bs_content.resources.prenom.find_all('word')
result = random.choice(prenom)
return result
elif word_type == 'prescuse':
prescuse = bs_content.resources.prescuse.find_all('word')
result = random.choice(prescuse)
return result
elif word_type == 'scuse1':
scuse1 = bs_content.resources.scuse1.find_all('word')
result = random.choice(scuse1)
return result
elif word_type == 'scuse2':
scuse2 = bs_content.resources.scuse2.find_all('word')
result = random.choice(scuse2)
return result
elif word_type == 'presulte':
presulte = bs_content.resources.presulte.find_all('word')
result = random.choice(presulte)
return result
elif word_type == 'sulte':
sulte = bs_content.resources.sulte.find_all('word')
result = random.choice(sulte)
return result
elif word_type == 'postsulte':
postsulte = bs_content.resources.presulte.find_all('word')
result = random.choice(postsulte)
return result
elif word_type == 'mail':
mail = bs_content.resources.mail.find_all('word')
result = random.choice(mail)
return result
else:
result = 'Nique bien ta mère!'
return result