From 0c9aeece815d9a1cb168a5187064ffba5d8bbfd8 Mon Sep 17 00:00:00 2001 From: BFlow Date: Tue, 14 Dec 2021 16:22:23 +0100 Subject: [PATCH 01/35] add commande "!cboulette" --- kabot/kabot/kabot.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/kabot/kabot/kabot.py b/kabot/kabot/kabot.py index fe5f702..2dffbb6 100644 --- a/kabot/kabot/kabot.py +++ b/kabot/kabot/kabot.py @@ -203,6 +203,13 @@ class Mybot(commands.Cog): 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 = "!gif ciboulette" + await cmd.invoke(ctx) + + @commands.command(help='Faire des choix') async def choice(self, ctx, *words): choices = random.choice(words) From 1f9fe5dfd1cdcb280fa31fda4214dc2a6c7926dd Mon Sep 17 00:00:00 2001 From: BFlow Date: Tue, 14 Dec 2021 15:31:58 +0000 Subject: [PATCH 02/35] Upload New File --- .../avatar_bot/MissSaugnacEtCambran2022.jpg | Bin 0 -> 8566 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 kabot/kabot/ressources/avatar_bot/MissSaugnacEtCambran2022.jpg diff --git a/kabot/kabot/ressources/avatar_bot/MissSaugnacEtCambran2022.jpg b/kabot/kabot/ressources/avatar_bot/MissSaugnacEtCambran2022.jpg new file mode 100644 index 0000000000000000000000000000000000000000..cbee0d9203e957227b24ed178dc450187795eb85 GIT binary patch literal 8566 zcmbVxXIK=?v+ux?B?rkt7e%6E$qOn;UZQ|xl$?X)v@0MW8AL!pKqN^P2}{m7xRR9& zOArv)C9be6cYV+QIp==3AMU+1-P835+WiHF)0Zt>EB95euJEhjDn1m zl!A(a;szz2NXe;bs3@ub@_%pgSN*RRzEF~plKqwVf1~RzfQ}4!1-t?g+y)5g2tafM z*L?st-d19Qe+h5$zeGR?A|fWin?!K~FVH}XHy;Ed#2ZUYgnyL;VfcQ4h>n>4mY50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z{^bIUL6G2}C^O8T=pQ0Lz1#%r9W>|h%ssTn>cbIx=mQwrx gK@uy{*LmV(`#R>~+xM6DW@A+~O=Bd?3a@|uFL-~0Z~y=R literal 0 HcmV?d00001 From 1f52550d2971bf062c38b61c9fb96404d4379f8a Mon Sep 17 00:00:00 2001 From: BFlow Date: Tue, 14 Dec 2021 16:32:42 +0100 Subject: [PATCH 03/35] update commande "!cboulette" + something --- kabot/kabot/kabot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/kabot/kabot/kabot.py b/kabot/kabot/kabot.py index 2dffbb6..84dd41d 100644 --- a/kabot/kabot/kabot.py +++ b/kabot/kabot/kabot.py @@ -206,7 +206,7 @@ class Mybot(commands.Cog): @commands.command(help="j'adore la cuisine") async def ciboulette(self, ctx): cmd = self.bot.get_command('gif') - ctx.message = "!gif ciboulette" + ctx.message.content = "!gif ciboulette" await cmd.invoke(ctx) @@ -431,7 +431,7 @@ class Mybot(commands.Cog): @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"] + list_name = ["Kabot", "Gaspard et Balthazar", "Bender", "Zoidberg", "Gunther", "MissSaugnacEtCambran2022"] try: current_name = self.bot.user.name list_name.remove(current_name) From a9cc9e20c04ed9a0d3d78317bea8b240e435db17 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Mon, 11 Dec 2023 20:56:46 +0100 Subject: [PATCH 04/35] fix some stuff --- kabot/kabot/kabot.py | 56 +++++++++++++++++++++++++++++++++++++------- 1 file changed, 47 insertions(+), 9 deletions(-) diff --git a/kabot/kabot/kabot.py b/kabot/kabot/kabot.py index 84dd41d..d80147f 100644 --- a/kabot/kabot/kabot.py +++ b/kabot/kabot/kabot.py @@ -43,7 +43,12 @@ stream_handler.setLevel(logging.INFO) logger.addHandler(stream_handler) -class Mybot(commands.Cog): +ffmpeg_options = { + 'options': '-vn -loglevel debug', +} + +#class Mybot(commands.Cog): +class Mybot(discord.Client): #Fonctions necesaires pour Kabot. def __init__( self, @@ -66,13 +71,18 @@ class Mybot(commands.Cog): self.sounds = [] self.nickname = nickname self.sounds_history = [] - self.play_next.start() + #self.play_next.start() - @tasks.loop(seconds=1.5) + async def setup_hook(self) -> None: + # create the background task and run it in the background + self.bg_task = self.loop.create_task(self.play_next()) + + #@tasks.loop(seconds=1.5) async def play_next(self): if self.sounds: audio_file, ctx = self.sounds[0] - source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(audio_file)) + print(type(audio_file)) + source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(audio_file,**ffmpeg_options)) if not ctx.voice_client.is_playing() and ctx.voice_client.is_connected(): ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None) self.sounds.pop(0) @@ -591,6 +601,9 @@ def get_word(word_type): #Le do[main]e de Kabot. def main(): + intents = discord.Intents.default() + intents.members = True + intents.messages = True logger.info("Initialisation de Kabot") parser = argparse.ArgumentParser() parser.add_argument( @@ -632,6 +645,8 @@ def main(): gif_token = config['giphy']['token'] bot = commands.Bot( command_prefix='!', + intents=intents, + audio_path="/home/mika/kabot-audio", ) test = False @@ -658,6 +673,7 @@ def main(): if message.author == bot.user: return else: + print(message.content) if bot.user in message.mentions \ and len(message.mentions) < 3 \ and len(message.content.splitlines()) == 1: @@ -669,6 +685,7 @@ def main(): f.write(message.content + '\n') response = random.choice(lines).replace(str(bot.user.id), str(message.author.id)) if response.startswith('!'): + print('test') command_name = response.split()[0].replace('!', '') cmd = bot.get_command(command_name) await cmd.invoke(message) @@ -681,6 +698,25 @@ def main(): await message.channel.send(response) await bot.process_commands(message) + @bot.command() + async def join(interaction: discord.Interaction): + channel = [x for x in bot.get_all_channels() if x.name == voice_channel][0] + await channel.connect() + await asyncio.sleep(2) + + @bot.command() + async def welcome(interaction: discord.Interaction): + # if ctx.message.author.name == self.bot.user.name: + # return + user = interaction.message.author.name + print(user) + try: + audio_file = random.choice([f for f in os.listdir(bot.audio_path + '/%s/' % user) if f.endswith('.mp3')]) + audio_file = bot.audio_path + '/%s/' % user + audio_file + except: + audio_file = random.choice([f"{f}" for f in Path(bot.audio_path + '/').glob('**/*.mp3')]) + bot.sounds.append((audio_file, interaction)) + @bot.event async def on_ready(): print('yeah baby!') @@ -693,8 +729,8 @@ def main(): await bot.user.edit(nick=nickname) await current_chan.send('Le troll est dans la place !') ctx = await bot.get_context(current_chan.last_message) - join = bot.get_command('join') - await join.invoke(ctx) + #join = bot.get_command('join') + #await join.invoke(ctx) for channel in bot.get_all_channels(): if channel.name == voice_channel: for member in channel.members: @@ -708,9 +744,9 @@ def main(): current_chan = channel ctx = await bot.get_context(current_chan.last_message) ctx.message.author = member - welcome = bot.get_command('welcome') + #welcome = bot.get_command('welcome') await asyncio.sleep(2) - await welcome.invoke(ctx) + #await welcome.invoke(ctx) @aiocron.crontab('*/5 * * * *') async def pipelette(): @@ -726,7 +762,9 @@ def main(): ctx.message.content = "" joke = bot.get_command('joke') await joke.invoke(ctx) - + @bot.command(help='check if bot always online') + async def ping(ctx): + await ctx.channel.send('pong') bot.add_cog( Mybot( bot, From 5792a88911f390a357e4192671955b6e39d798d0 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Wed, 13 Dec 2023 21:22:50 +0100 Subject: [PATCH 05/35] fix intents --- kabot/kabot/kabot.py | 40 ++++++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/kabot/kabot/kabot.py b/kabot/kabot/kabot.py index d80147f..f9509ff 100644 --- a/kabot/kabot/kabot.py +++ b/kabot/kabot/kabot.py @@ -53,6 +53,7 @@ class Mybot(discord.Client): def __init__( self, bot, + intents=None, gl_url=None, gl_token=None, gif_token=None, @@ -181,6 +182,7 @@ class Mybot(discord.Client): @commands.command(help='check if bot always online') async def ping(self, message): + print('trying to repondre') await message.channel.send('pong') @commands.command(help='Restart Bot') @@ -601,7 +603,7 @@ def get_word(word_type): #Le do[main]e de Kabot. def main(): - intents = discord.Intents.default() + intents = discord.Intents.all() intents.members = True intents.messages = True logger.info("Initialisation de Kabot") @@ -648,6 +650,19 @@ def main(): intents=intents, audio_path="/home/mika/kabot-audio", ) + bot.add_cog( + Mybot( + bot, + intents = intents, + gl_url=gl_url, + gl_token=gl_token, + gif_token=gif_token, + audio_path="/home/mika/kabot-audio", + nickname=nickname, + voice_channel=voice_channel, + text_channel=text_channel, + ) + ) test = False if "test" in argv[-1]: @@ -690,7 +705,7 @@ def main(): cmd = bot.get_command(command_name) await cmd.invoke(message) else: - with message.channel.typing(): + async with message.channel.typing(): if "http" in response: await asyncio.sleep(len(response) / 8) else: @@ -698,7 +713,7 @@ def main(): await message.channel.send(response) await bot.process_commands(message) - @bot.command() + @bot.command(help='demerde toi') async def join(interaction: discord.Interaction): channel = [x for x in bot.get_all_channels() if x.name == voice_channel][0] await channel.connect() @@ -711,10 +726,10 @@ def main(): user = interaction.message.author.name print(user) try: - audio_file = random.choice([f for f in os.listdir(bot.audio_path + '/%s/' % user) if f.endswith('.mp3')]) - audio_file = bot.audio_path + '/%s/' % user + audio_file + audio_file = random.choice([f for f in os.listdir(audio_path + '/%s/' % user) if f.endswith('.mp3')]) + audio_file = audio_path + '/%s/' % user + audio_file except: - audio_file = random.choice([f"{f}" for f in Path(bot.audio_path + '/').glob('**/*.mp3')]) + audio_file = random.choice([f"{f}" for f in Path(audio_path + '/').glob('**/*.mp3')]) bot.sounds.append((audio_file, interaction)) @bot.event @@ -764,19 +779,8 @@ def main(): await joke.invoke(ctx) @bot.command(help='check if bot always online') async def ping(ctx): + print("trying to repondre again") await ctx.channel.send('pong') - bot.add_cog( - Mybot( - bot, - gl_url=gl_url, - gl_token=gl_token, - gif_token=gif_token, - audio_path=audio_path, - nickname=nickname, - voice_channel=voice_channel, - text_channel=text_channel, - ) - ) bot.run(token) From c47df4b78c399e636781f05d046fe07693e23b7f Mon Sep 17 00:00:00 2001 From: Milka64 Date: Tue, 26 Dec 2023 13:19:46 +0100 Subject: [PATCH 06/35] code refactoring --- .idea/.gitignore | 2 - .../inspectionProfiles/profiles_settings.xml | 6 - .idea/kabot.iml | 8 - .idea/misc.xml | 4 - .idea/modules.xml | 8 - .idea/vcs.xml | 6 - Dockerfile | 14 - bootstrap-buildout.py | 210 ----- buildout.cfg | 45 - kabot/.github/ISSUE_TEMPLATE.md | 15 - kabot/Makefile | 88 -- kabot/kabot/kabot.py | 779 +----------------- kabot/kabot/utils/__init__.py | 1 + kabot/kabot/utils/audio.py | 304 +++++++ .../avatar_bot => utils/ressources}/.gitkeep | 0 .../utils/ressources/avatar_bot/.gitkeep | 0 .../{ => utils}/ressources/avatar_bot/404.jpg | Bin .../ressources/avatar_bot/Bender.jpg | Bin .../avatar_bot/Gaspard_et_Balthazar.jpg | Bin .../ressources/avatar_bot/Gunther.jpg | Bin .../ressources/avatar_bot/Kabot.jpg | Bin .../avatar_bot/MissSaugnacEtCambran2022.jpg | Bin .../ressources/avatar_bot/Zoidberg.jpg | Bin .../kabot/{ => utils}/ressources/base_kml.xml | 0 .../{ => utils}/ressources/contrepeteries.txt | 0 kabot/kabot/utils/texte.py | 453 ++++++++++ kabot/requirements_dev.txt | 10 - kabot/setup.py | 4 +- kabot/tox.ini | 20 - pinned.cfg | 36 - 30 files changed, 804 insertions(+), 1209 deletions(-) delete mode 100644 .idea/.gitignore delete mode 100644 .idea/inspectionProfiles/profiles_settings.xml delete mode 100644 .idea/kabot.iml delete mode 100644 .idea/misc.xml delete mode 100644 .idea/modules.xml delete mode 100644 .idea/vcs.xml delete mode 100644 Dockerfile delete mode 100644 bootstrap-buildout.py delete mode 100644 buildout.cfg delete mode 100644 kabot/.github/ISSUE_TEMPLATE.md delete mode 100644 kabot/Makefile create mode 100644 kabot/kabot/utils/__init__.py create mode 100644 kabot/kabot/utils/audio.py rename kabot/kabot/{ressources/avatar_bot => utils/ressources}/.gitkeep (100%) create mode 100644 kabot/kabot/utils/ressources/avatar_bot/.gitkeep rename kabot/kabot/{ => utils}/ressources/avatar_bot/404.jpg (100%) rename kabot/kabot/{ => utils}/ressources/avatar_bot/Bender.jpg (100%) rename kabot/kabot/{ => utils}/ressources/avatar_bot/Gaspard_et_Balthazar.jpg (100%) rename kabot/kabot/{ => utils}/ressources/avatar_bot/Gunther.jpg (100%) rename kabot/kabot/{ => utils}/ressources/avatar_bot/Kabot.jpg (100%) rename kabot/kabot/{ => utils}/ressources/avatar_bot/MissSaugnacEtCambran2022.jpg (100%) rename kabot/kabot/{ => utils}/ressources/avatar_bot/Zoidberg.jpg (100%) rename kabot/kabot/{ => utils}/ressources/base_kml.xml (100%) rename kabot/kabot/{ => utils}/ressources/contrepeteries.txt (100%) create mode 100644 kabot/kabot/utils/texte.py delete mode 100644 kabot/requirements_dev.txt delete mode 100644 kabot/tox.ini delete mode 100644 pinned.cfg diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 5c98b42..0000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -# Default ignored files -/workspace.xml \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml deleted file mode 100644 index 105ce2d..0000000 --- a/.idea/inspectionProfiles/profiles_settings.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/kabot.iml b/.idea/kabot.iml deleted file mode 100644 index fa46463..0000000 --- a/.idea/kabot.iml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml deleted file mode 100644 index 45ae0aa..0000000 --- a/.idea/misc.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml deleted file mode 100644 index 9b257af..0000000 --- a/.idea/modules.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 94a25f7..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 48f615b..0000000 --- a/Dockerfile +++ /dev/null @@ -1,14 +0,0 @@ -FROM alpine - -WORKDIR /app -VOLUME /data - -RUN apk add --update musl-dev python3-dev gcc python3 py3-pip git py3-lxml libxml2 libxml2-dev py3-pynacl ffmpeg\ -&& pip3 install --upgrade pip \ -&& pip3 install bs4 requests giphy_client discord.py python-gitlab\ -&& git clone https://git.0w.tf/Milka64/kabot.git -WORKDIR /app/kabot -RUN pip3 install kabot/ -RUN mkdir -p /var/log/kabot/ -RUN chmod 777 /var/log/kabot -CMD kabot -c /data/config.ini diff --git a/bootstrap-buildout.py b/bootstrap-buildout.py deleted file mode 100644 index a459921..0000000 --- a/bootstrap-buildout.py +++ /dev/null @@ -1,210 +0,0 @@ -############################################################################## -# -# Copyright (c) 2006 Zope Foundation and Contributors. -# All Rights Reserved. -# -# This software is subject to the provisions of the Zope Public License, -# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. -# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED -# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS -# FOR A PARTICULAR PURPOSE. -# -############################################################################## -"""Bootstrap a buildout-based project - -Simply run this script in a directory containing a buildout.cfg. -The script accepts buildout command-line options, so you can -use the -c option to specify an alternate configuration file. -""" - -import os -import shutil -import sys -import tempfile - -from optparse import OptionParser - -__version__ = '2015-07-01' -# See zc.buildout's changelog if this version is up to date. - -tmpeggs = tempfile.mkdtemp(prefix='bootstrap-') - -usage = '''\ -[DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] - -Bootstraps a buildout-based project. - -Simply run this script in a directory containing a buildout.cfg, using the -Python that you want bin/buildout to use. - -Note that by using --find-links to point to local resources, you can keep -this script from going over the network. -''' - -parser = OptionParser(usage=usage) -parser.add_option("--version", - action="store_true", default=False, - help=("Return bootstrap.py version.")) -parser.add_option("-t", "--accept-buildout-test-releases", - dest='accept_buildout_test_releases', - action="store_true", default=False, - help=("Normally, if you do not specify a --version, the " - "bootstrap script and buildout gets the newest " - "*final* versions of zc.buildout and its recipes and " - "extensions for you. If you use this flag, " - "bootstrap and buildout will get the newest releases " - "even if they are alphas or betas.")) -parser.add_option("-c", "--config-file", - help=("Specify the path to the buildout configuration " - "file to be used.")) -parser.add_option("-f", "--find-links", - help=("Specify a URL to search for buildout releases")) -parser.add_option("--allow-site-packages", - action="store_true", default=False, - help=("Let bootstrap.py use existing site packages")) -parser.add_option("--buildout-version", - help="Use a specific zc.buildout version") -parser.add_option("--setuptools-version", - help="Use a specific setuptools version") -parser.add_option("--setuptools-to-dir", - help=("Allow for re-use of existing directory of " - "setuptools versions")) - -options, args = parser.parse_args() -if options.version: - print("bootstrap.py version %s" % __version__) - sys.exit(0) - - -###################################################################### -# load/install setuptools - -try: - from urllib.request import urlopen -except ImportError: - from urllib2 import urlopen - -ez = {} -if os.path.exists('ez_setup.py'): - exec(open('ez_setup.py').read(), ez) -else: - exec(urlopen('https://bootstrap.pypa.io/ez_setup.py').read(), ez) - -if not options.allow_site_packages: - # ez_setup imports site, which adds site packages - # this will remove them from the path to ensure that incompatible versions - # of setuptools are not in the path - import site - # inside a virtualenv, there is no 'getsitepackages'. - # We can't remove these reliably - if hasattr(site, 'getsitepackages'): - for sitepackage_path in site.getsitepackages(): - # Strip all site-packages directories from sys.path that - # are not sys.prefix; this is because on Windows - # sys.prefix is a site-package directory. - if sitepackage_path != sys.prefix: - sys.path[:] = [x for x in sys.path - if sitepackage_path not in x] - -setup_args = dict(to_dir=tmpeggs, download_delay=0) - -if options.setuptools_version is not None: - setup_args['version'] = options.setuptools_version -if options.setuptools_to_dir is not None: - setup_args['to_dir'] = options.setuptools_to_dir - -ez['use_setuptools'](**setup_args) -import setuptools -import pkg_resources - -# This does not (always?) update the default working set. We will -# do it. -for path in sys.path: - if path not in pkg_resources.working_set.entries: - pkg_resources.working_set.add_entry(path) - -###################################################################### -# Install buildout - -ws = pkg_resources.working_set - -setuptools_path = ws.find( - pkg_resources.Requirement.parse('setuptools')).location - -# Fix sys.path here as easy_install.pth added before PYTHONPATH -cmd = [sys.executable, '-c', - 'import sys; sys.path[0:0] = [%r]; ' % setuptools_path + - 'from setuptools.command.easy_install import main; main()', - '-mZqNxd', tmpeggs] - -find_links = os.environ.get( - 'bootstrap-testing-find-links', - options.find_links or - ('http://downloads.buildout.org/' - if options.accept_buildout_test_releases else None) - ) -if find_links: - cmd.extend(['-f', find_links]) - -requirement = 'zc.buildout' -version = options.buildout_version -if version is None and not options.accept_buildout_test_releases: - # Figure out the most recent final version of zc.buildout. - import setuptools.package_index - _final_parts = '*final-', '*final' - - def _final_version(parsed_version): - try: - return not parsed_version.is_prerelease - except AttributeError: - # Older setuptools - for part in parsed_version: - if (part[:1] == '*') and (part not in _final_parts): - return False - return True - - index = setuptools.package_index.PackageIndex( - search_path=[setuptools_path]) - if find_links: - index.add_find_links((find_links,)) - req = pkg_resources.Requirement.parse(requirement) - if index.obtain(req) is not None: - best = [] - bestv = None - for dist in index[req.project_name]: - distv = dist.parsed_version - if _final_version(distv): - if bestv is None or distv > bestv: - best = [dist] - bestv = distv - elif distv == bestv: - best.append(dist) - if best: - best.sort() - version = best[-1].version -if version: - requirement = '=='.join((requirement, version)) -cmd.append(requirement) - -import subprocess -if subprocess.call(cmd) != 0: - raise Exception( - "Failed to execute command:\n%s" % repr(cmd)[1:-1]) - -###################################################################### -# Import and run buildout - -ws.add_entry(tmpeggs) -ws.require(requirement) -import zc.buildout.buildout - -if not [a for a in args if '=' not in a]: - args.append('bootstrap') - -# if -c was provided, we push it back into args for buildout' main function -if options.config_file is not None: - args[0:0] = ['-c', options.config_file] - -zc.buildout.buildout.main(args) -shutil.rmtree(tmpeggs) diff --git a/buildout.cfg b/buildout.cfg deleted file mode 100644 index 3329e93..0000000 --- a/buildout.cfg +++ /dev/null @@ -1,45 +0,0 @@ -[buildout] -show-picked-versions = true -extends = pinned.cfg - -package = kabot - -develop = - kabot - mr-dev/discord - mr-dev/giphy - -parts += - kabot - doc - -extensions = mr.developer -sources-dir = mr-dev -auto-checkout = - discord - giphy - -[kabot] -recipe = zc.recipe.egg -eggs = - ${buildout:package} - cookiecutter - discord.py - PyNaCl - requests - giphy_client - python-gitlab - -interpreter = python - -[doc] -recipe = zc.recipe.egg -eggs = - ${buildout:package} - -[sources] -discord = git https://github.com/Rapptz/discord.py.git -giphy = git https://github.com/Giphy/giphy-python-client.git - -[logging] -logger_root_level = DEBUG diff --git a/kabot/.github/ISSUE_TEMPLATE.md b/kabot/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index beadd37..0000000 --- a/kabot/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,15 +0,0 @@ -* Kabot version: -* Python version: -* Operating System: - -### Description - -Describe what you were trying to get done. -Tell us what happened, what went wrong, and what you expected to happen. - -### What I Did - -``` -Paste the command(s) you ran and the output. -If there was a crash, please include the traceback here. -``` diff --git a/kabot/Makefile b/kabot/Makefile deleted file mode 100644 index f65d86a..0000000 --- a/kabot/Makefile +++ /dev/null @@ -1,88 +0,0 @@ -.PHONY: clean clean-test clean-pyc clean-build docs help -.DEFAULT_GOAL := help - -define BROWSER_PYSCRIPT -import os, webbrowser, sys - -try: - from urllib import pathname2url -except: - from urllib.request import pathname2url - -webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) -endef -export BROWSER_PYSCRIPT - -define PRINT_HELP_PYSCRIPT -import re, sys - -for line in sys.stdin: - match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) - if match: - target, help = match.groups() - print("%-20s %s" % (target, help)) -endef -export PRINT_HELP_PYSCRIPT - -BROWSER := python -c "$$BROWSER_PYSCRIPT" - -help: - @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) - -clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts - -clean-build: ## remove build artifacts - rm -fr build/ - rm -fr dist/ - rm -fr .eggs/ - find . -name '*.egg-info' -exec rm -fr {} + - find . -name '*.egg' -exec rm -f {} + - -clean-pyc: ## remove Python file artifacts - find . -name '*.pyc' -exec rm -f {} + - find . -name '*.pyo' -exec rm -f {} + - find . -name '*~' -exec rm -f {} + - find . -name '__pycache__' -exec rm -fr {} + - -clean-test: ## remove test and coverage artifacts - rm -fr .tox/ - rm -f .coverage - rm -fr htmlcov/ - rm -fr .pytest_cache - -lint: ## check style with flake8 - flake8 kabot tests - -test: ## run tests quickly with the default Python - python setup.py test - -test-all: ## run tests on every Python version with tox - tox - -coverage: ## check code coverage quickly with the default Python - coverage run --source kabot setup.py test - coverage report -m - coverage html - $(BROWSER) htmlcov/index.html - -docs: ## generate Sphinx HTML documentation, including API docs - rm -f docs/kabot.rst - rm -f docs/modules.rst - sphinx-apidoc -o docs/ kabot - $(MAKE) -C docs clean - $(MAKE) -C docs html - $(BROWSER) docs/_build/html/index.html - -servedocs: docs ## compile the docs watching for changes - watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D . - -release: dist ## package and upload a release - twine upload dist/* - -dist: clean ## builds source and wheel package - python setup.py sdist - python setup.py bdist_wheel - ls -l dist - -install: clean ## install the package to the active Python's site-packages - python setup.py install diff --git a/kabot/kabot/kabot.py b/kabot/kabot/kabot.py index f9509ff..b9d3b97 100644 --- a/kabot/kabot/kabot.py +++ b/kabot/kabot/kabot.py @@ -1,612 +1,40 @@ -# -*- coding: utf-8 -*- +# This example requires the 'message_content' privileged intent to function. -"""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 youtube_dl -import configparser -import argparse -import typing -import functools +import yt_dlp as youtube_dl -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__)) - -## création de l'objet logger -logger = logging.getLogger() -## definition du log level -logger.setLevel(logging.INFO) - -## format du log -formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s') - -## definition de l'affichage des logs dans la console -stream_handler = logging.StreamHandler() -stream_handler.setLevel(logging.INFO) -logger.addHandler(stream_handler) +from discord.ext import commands +from utils.audio import * +from utils.texte import * -ffmpeg_options = { - 'options': '-vn -loglevel debug', -} -#class Mybot(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_channel=None, - text_channel=None, - ): - self.gl_url = gl_url - self.audio_path = audio_path - self.gl_token = gl_token - self.gif_token = gif_token - self.voice_channel = voice_channel - self.text_channel = text_channel - self.bot = bot - self.sounds = [] - self.nickname = nickname - self.sounds_history = [] - #self.play_next.start() +intents = discord.Intents.all() +intents.message_content = True - async def setup_hook(self) -> None: - # create the background task and run it in the background - self.bg_task = self.loop.create_task(self.play_next()) - - #@tasks.loop(seconds=1.5) - async def play_next(self): - if self.sounds: - audio_file, ctx = self.sounds[0] - print(type(audio_file)) - source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(audio_file,**ffmpeg_options)) - if not ctx.voice_client.is_playing() and ctx.voice_client.is_connected(): - ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None) - self.sounds.pop(0) - self.sounds_history.reverse() - self.sounds_history.append((audio_file, ctx)) - self.sounds_history.reverse() - if len(self.sounds_history) > 5: - self.sounds_history = self.sounds_history[:5] - #Fin des fonctions necesaire pour Kabot. - - #Les commandes pour interagir avec Kabot. - @commands.command(help='Clear sound queue') - async def clear(self, ctx): - self.sounds = [] - - @commands.command(help='list des commits') - async def commits(self, ctx, number = 5): - 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("-_-") +bot = commands.Bot( + command_prefix=commands.when_mentioned_or("!"), + description='''A ROULEEEEETTES !! + HOULA... J'l'ai un peu trop gueulé ça, non ? + A roulettes.''', + intents=intents, +) - @commands.command(help='clear cache youtube dl') - async def cache_clear(self, ctx): - fichiers = os.listdir('/tmp') - for fichier in fichiers: - if fichier.startswith('discord'): - os.remove("/tmp/" + fichier) - - @commands.command() - async def leave(self, ctx): - if ctx.voice_client and ctx.voice_client.is_connected(): - await ctx.guild.voice_client.disconnect() - - @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() - async def join(self, ctx): - channel = [x for x in self.bot.get_all_channels() if x.name == self.voice_channel][0] - await channel.connect() - await asyncio.sleep(2) - - @commands.command(help="detail du dernier son joué") - async def last(self, ctx, number = 1): - number = int(number) - for sound in self.sounds_history[0:number]: - await ctx.channel.send("```"+str(sound[0])+"```") - - @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) - 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): - print('trying to repondre') - 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')) - #Fin des commandes pour interagir avec Kabot. - - #Les commandes pour faire mumuse avec Kabot. - @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) - 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) +@bot.event +async def on_ready(): + print(f'Logged in as {bot.user} (ID: {bot.user.id})') + print('------') - @commands.command(help='Faire des choix') - async def choice(self, ctx, *words): - choices = random.choice(words) - await ctx.channel.send(choices) +async def main(): + ## création de l'objet logger + logger = logging.getLogger() + ## definition du log level + logger.setLevel(logging.INFO) - @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.guild_only() - @commands.command() - async def joke(self, ctx, folder=None): - try: - user = ctx.message.author.name - if not folder or not ctx.message.content: - audio_file = random.choice([f"{f}" for f in Path(self.audio_path + '/').glob('**/*.mp3')]) - else: - folder = folder.lower() - audio_file = [f"{f}" for f in Path(self.audio_path + '/').glob('**/*.mp3') if folder in str(f).lower()] - if not audio_file: - ctx.channel.send("%s not found" % folder) - else: - audio_file = random.choice(audio_file) - self.sounds.append((audio_file, ctx)) - except: - e = exc_info()[0] - await ctx.channel.send("Exception when calling joke: %s\n" % e) - - - @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 - with ctx.channel.typing(): - await asyncio.sleep(len(result)/6) - await ctx.send(result) - - @commands.command(help="Toi tu fermes ta gueule! Tu la fermes définitivement") - async def mute(self, ctx, member: discord.Member=None, mute_time = 10): - if member.voice.mute: - with ctx.channel.typing(): - await asyncio.sleep(1) - await ctx.channel.send("Tu ne vas pas m'avoir si facilement") - return - if not member: - with ctx.channel.typing(): - await asyncio.sleep(1) - await ctx.channel.send("Qui veux-tu mute?") - return - if mute_time > 60: - with ctx.channel.typing(): - await asyncio.sleep(1) - await ctx.channel.send("Doucement sur le temps!") - return - member = ctx.message.mentions[0] - await member.edit(mute=True) - with ctx.channel.typing(): - await asyncio.sleep(1) - await ctx.send("Tu sors %s!" % member.mention) - await asyncio.sleep(mute_time) - await member.edit(mute=False) - with ctx.channel.typing(): - await asyncio.sleep(1) - await ctx.channel.send("Tu peux reparler %s!" % member.mention) - - @commands.command(help="Jouer un song a partir d'une video") - async def play(self, ctx, url): - ydl_opts = {'format': 'bestaudio/mp3', 'outtmpl': '/tmp/discord_%(title)s-%(id)s.%(ext)s', - 'postprocessors': [{ - 'key': 'FFmpegExtractAudio', - 'preferredcodec': 'mp3', - 'preferredquality': '192', - }], - } - with youtube_dl.YoutubeDL(ydl_opts) as ydl: - info_dict = ydl.extract_info(url, download=False) - out_file = ydl.prepare_filename(info_dict) - extension = out_file.split('.')[-1] - out_file = out_file.replace(extension, 'mp3') - if not os.path.isfile(out_file): - await asyncio.get_running_loop().run_in_executor(None, ydl.download,[url]) - self.sounds.append((out_file, ctx)) - - @commands.command() - async def repeat(self, ctx): - # if ctx.message.author.name == self.bot.user.name: - # return - user = ctx.message.author.name - source = self.sounds_history[0] - self.sounds.append(source) - - @commands.command(help="Appuie sur la detente PUSSY!") - async def roulette(self, ctx): - mute_time = 60 - member = ctx.message.author - barillet = [False, False, True, False, False] - bullet = random.choice(barillet) - await self.joke(ctx, "spinning_and_closed.mp3") - if bullet == True: - await self.joke(ctx, "omawa_shindeiru.mp3") - await asyncio.sleep(2) - await member.edit(mute=True) - with ctx.channel.typing(): - await asyncio.sleep(3) - await ctx.channel.send("Perdu, tu es mute pendant 60 secondes!") - else: - await self.joke(ctx, "hammer_and_dry.mp3") - with ctx.channel.typing(): - await asyncio.sleep(3) - await ctx.channel.send("Gagné, tu ne seras pas mute!") - return - await asyncio.sleep(mute_time) - await member.edit(mute=False) - with ctx.channel.typing(): - await asyncio.sleep(0.5) - await ctx.channel.send("Tu peux reparler %s!" % member.mention) - - @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_channel][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.name == word[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.name == word[1:]: - 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) - - @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: - with ctx.channel.typing(): - await asyncio.sleep(0.5) - await ctx.channel.send("je tribuche par terre et je sais pas comment") - else: - with ctx.channel.typing(): - await asyncio.sleep(len(slap_multiple) / 4) - await ctx.channel.send(random.choice(slap_multiple) % user) - - @commands.command() - async def welcome(self, ctx): - # if ctx.message.author.name == self.bot.user.name: - # return - user = ctx.message.author.name - print(user) - try: - audio_file = random.choice([f for f in os.listdir(self.audio_path + '/%s/' % user) if f.endswith('.mp3')]) - audio_file = self.audio_path + '/%s/' % user + audio_file - except: - audio_file = random.choice([f"{f}" for f in Path(self.audio_path + '/').glob('**/*.mp3')]) - self.sounds.append((audio_file, ctx)) - #Fin des commandes pour faire mumuse avec Kabot. - - #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()) - - @commands.command(help='Troll commands', hidden=True) - async def okre(self, ctx): - await self.joke(ctx, "tu_dois_tout_donner.mp3") - #Fin des commandes pour troll. - -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 - -#Le do[main]e de Kabot. -def main(): - intents = discord.Intents.all() - intents.members = True - intents.messages = True - logger.info("Initialisation de Kabot") parser = argparse.ArgumentParser() parser.add_argument( "-c", @@ -623,6 +51,7 @@ def main(): log_file = config['DEFAULT']['logs'] ## definition du fichier de log (chemin, level, etc ...) + formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s') file_handler = RotatingFileHandler(log_file, 'a', 1000000, 1) file_handler.setLevel(logging.INFO) file_handler.setFormatter(formatter) @@ -645,145 +74,25 @@ def main(): gl_url = config['gitlab']['url'] gl_token = config['gitlab']['token'] gif_token = config['giphy']['token'] - bot = commands.Bot( - command_prefix='!', - intents=intents, - audio_path="/home/mika/kabot-audio", - ) - bot.add_cog( - Mybot( - bot, - intents = intents, - gl_url=gl_url, - gl_token=gl_token, - gif_token=gif_token, - audio_path="/home/mika/kabot-audio", - nickname=nickname, - voice_channel=voice_channel, - text_channel=text_channel, + async with bot: + await bot.add_cog( + Audio( + bot, + voice_chan=voice_channel, + text_chan=text_channel, + audio_path='/home/mika/kabot_audio/' + ) ) - ) - - test = False - if "test" in argv[-1]: - test=True - - @aiocron.crontab('50 9-23/1 * * *') - async def kron(): - kron_choice = random.choice(["kaamelott", "slap", "kamoulox", "contrepeterie", "schizo", False, False, False, False, False, False]) - if kron_choice: - await asyncio.sleep(random.choice(range(3550))) - for channel in bot.get_all_channels(): - if channel.name == text_channel: - current_chan = channel - ctx = await bot.get_context(current_chan.last_message) - ctx.message.content = "" - print(ctx.message.content) - random_cmd = bot.get_command(kron_choice) - await random_cmd.invoke(ctx) - - @bot.event - async def on_message(message): - print(message.content) - if message.author == bot.user: - return - else: - print(message.content) - if 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(bot.user.id), str(message.author.id)) - if response.startswith('!'): - print('test') - command_name = response.split()[0].replace('!', '') - cmd = bot.get_command(command_name) - await cmd.invoke(message) - else: - 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 bot.process_commands(message) - - @bot.command(help='demerde toi') - async def join(interaction: discord.Interaction): - channel = [x for x in bot.get_all_channels() if x.name == voice_channel][0] - await channel.connect() - await asyncio.sleep(2) - - @bot.command() - async def welcome(interaction: discord.Interaction): - # if ctx.message.author.name == self.bot.user.name: - # return - user = interaction.message.author.name - print(user) - try: - audio_file = random.choice([f for f in os.listdir(audio_path + '/%s/' % user) if f.endswith('.mp3')]) - audio_file = audio_path + '/%s/' % user + audio_file - except: - audio_file = random.choice([f"{f}" for f in Path(audio_path + '/').glob('**/*.mp3')]) - bot.sounds.append((audio_file, interaction)) - - @bot.event - async def on_ready(): - print('yeah baby!') - if test: - await bot.close() - 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 !') - ctx = await bot.get_context(current_chan.last_message) - #join = bot.get_command('join') - #await join.invoke(ctx) - for channel in bot.get_all_channels(): - if channel.name == voice_channel: - for member in channel.members: - await member.edit(mute=False) - - @bot.event - async def on_voice_state_update(member, before, after): - if before.channel is None and after.channel: - for channel in bot.get_all_channels(): - if channel.name == text_channel: - current_chan = channel - ctx = await bot.get_context(current_chan.last_message) - ctx.message.author = member - #welcome = bot.get_command('welcome') - await asyncio.sleep(2) - #await welcome.invoke(ctx) - - @aiocron.crontab('*/5 * * * *') - async def pipelette(): - for channel in bot.get_all_channels(): - if channel.name == voice_channel and\ - len(channel.members) > 1 and\ - random.choice([True,True,True]): - for channel in bot.get_all_channels(): - if channel.name == text_channel: - current_chan = channel - await asyncio.sleep(random.choice(range(350))) - ctx = await bot.get_context(current_chan.last_message) - ctx.message.content = "" - joke = bot.get_command('joke') - await joke.invoke(ctx) - @bot.command(help='check if bot always online') - async def ping(ctx): - print("trying to repondre again") - await ctx.channel.send('pong') - bot.run(token) - + await bot.add_cog( + Texte( + bot, + gif_token=gif_token, + gl_token=gl_token, + gl_url=gl_url, + text_chan=text_channel, + ) + ) + await bot.start(token) if __name__ == "__main__": - main() - + asyncio.run(main()) diff --git a/kabot/kabot/utils/__init__.py b/kabot/kabot/utils/__init__.py new file mode 100644 index 0000000..ba38a01 --- /dev/null +++ b/kabot/kabot/utils/__init__.py @@ -0,0 +1 @@ +## diff --git a/kabot/kabot/utils/audio.py b/kabot/kabot/utils/audio.py new file mode 100644 index 0000000..f1fac67 --- /dev/null +++ b/kabot/kabot/utils/audio.py @@ -0,0 +1,304 @@ +# This example requires the 'message_content' privileged intent to function. + +import asyncio + +import discord +import yt_dlp as youtube_dl + +import random +import os +from discord.ext import commands, tasks +from pathlib import Path + +# Suppress noise about console usage from errors +youtube_dl.utils.bug_reports_message = lambda: '' + + +ytdl_format_options = { + 'format': 'bestaudio/mp3', + 'outtmpl': '/tmp/discord_%(title)s-%(id)s.%(ext)s', + 'postprocessors': [{ + 'key': 'FFmpegExtractAudio', + 'preferredcodec': 'mp3', + 'preferredquality': '192', + }] +} + +ffmpeg_options = { + 'options': '-vn', +} + +ytdl = youtube_dl.YoutubeDL(ytdl_format_options) + + +class YTDLSource(discord.PCMVolumeTransformer): + def __init__(self, source, *, data, volume=0.5): + super().__init__(source, volume) + + self.data = data + + self.title = data.get('title') + self.url = data.get('url') + + @classmethod + async def from_url(cls, url, *, loop=None, stream=False): + loop = loop or asyncio.get_event_loop() + data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream)) + + if 'entries' in data: + # take first item from a playlist + data = data['entries'][0] + + filename = data['url'] if stream else ytdl.prepare_filename(data) + extension = filename.split('.')[-1] + filename = filename.replace(extension, 'mp3') + return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data) + + @classmethod + async def from_file(cls, audio_file, ctx, *, loop=None, stream=False): + source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(audio_file,**ffmpeg_options)) + ctx.voice_client.play(source, after=lambda e: print('Player error: %s' % e) if e else None) + + +class Audio(commands.Cog, name="Commandes Audio"): + def __init__( + self, + bot, + audio_path=None, + voice_chan=None, + text_chan=None): + self.bot = bot + self.sounds = [] + self.voice_chan = voice_chan + self.text_chan = text_chan + self.audio_path = audio_path + self.sounds_history = [] + + @commands.Cog.listener() + async def on_voice_state_update(self, member, before, after): + if before.channel is None and after.channel: + 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.author = member + #welcome = bot.get_command('welcome') + await asyncio.sleep(2) + await self.welcome(ctx, member.display_name) + + @commands.Cog.listener() + async def on_ready(self): + self.play_next.start() + self.pipelette.start() + if self.voice_chan: + await self.join(self.voice_chan) + #await self.welcome(None, 'kabot') + + @commands.command(help="Toi tu fermes ta gueule! Tu la fermes définitivement") + async def mute(self, ctx, member: discord.Member=None, mute_time = 10): + if member.voice.mute: + async with ctx.channel.typing(): + await asyncio.sleep(1) + await ctx.channel.send("Tu ne vas pas m'avoir si facilement") + return + if not member: + async with ctx.channel.typing(): + await asyncio.sleep(1) + await ctx.channel.send("Qui veux-tu mute?") + return + if mute_time > 60: + async with ctx.channel.typing(): + await asyncio.sleep(1) + await ctx.channel.send("Doucement sur le temps!") + return + member = ctx.message.mentions[0] + await member.edit(mute=True) + async with ctx.channel.typing(): + await asyncio.sleep(1) + await ctx.send("Tu sors %s!" % member.mention) + await asyncio.sleep(mute_time) + await member.edit(mute=False) + async with ctx.channel.typing(): + await asyncio.sleep(1) + await ctx.channel.send("Tu peux reparler %s!" % member.mention) + + @commands.command(help="Appuie sur la detente PUSSY!") + async def roulette(self, ctx): + mute_time = 60 + member = ctx.message.author + if not member.voice: + async with ctx.typing(): + await ctx.channel.send("You're not in voice channel") + return + barillet = [False, False, True, False, False] + bullet = random.choice(barillet) + await self.joke(ctx, "spinning_and_closed.mp3") + if bullet == True: + await self.joke(ctx, "omawa_shindeiru.mp3") + await asyncio.sleep(2) + await member.edit(mute=True) + async with ctx.typing(): + await asyncio.sleep(3) + await ctx.channel.send("Perdu, tu es mute pendant 60 secondes!") + else: + await self.joke(ctx, "hammer_and_dry.mp3") + async with ctx.typing(): + await asyncio.sleep(3) + await ctx.channel.send("Gagné, tu ne seras pas mute!") + return + await asyncio.sleep(mute_time) + await member.edit(mute=False) + async with ctx.typing(): + await asyncio.sleep(0.5) + await ctx.channel.send("Tu peux reparler %s!" % member.mention) + + @tasks.loop(seconds=300) + async def pipelette(self): + for channel in self.bot.get_all_channels(): + if channel.name == self.voice_chan and\ + len(channel.members) > 1 and\ + random.choice([True,True,True]): + for chan in self.bot.get_all_channels(): + if chan.name == self.text_chan: + current_chan = chan + await asyncio.sleep(random.choice(range(305))) + async for msg in current_chan.history(limit=1): + last_message = msg + ctx = await self.bot.get_context(last_message) + ctx.message.content = "" + await self.joke(ctx) + + @tasks.loop(seconds=1) + async def play_next(self): + connected_voice = [chan for chan in self.bot.voice_clients if chan.is_connected()] + if connected_voice: + if not [chan for chan in connected_voice if chan.is_playing()]: + if self.sounds: + audio_type, audio_file, ctx = self.sounds[0] + if 'url' in audio_type: + player = await YTDLSource.from_url(audio_file, loop=self.bot.loop) + ctx.voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None) + elif 'file' in audio_type: + player = await YTDLSource.from_file(audio_file, ctx) + last_audio = self.sounds.pop(0) + self.sounds_history.reverse() + self.sounds_history.append(last_audio) + self.sounds_history.reverse() + if len(self.sounds_history) > 5: + self.sounds_history = self.sounds_history[:5] + + @commands.command(help='Troll commands', hidden=True) + async def okre(self, ctx): + await self.joke(ctx, "tu_dois_tout_donner.mp3") + + @commands.command(help='Clear sound queue') + async def clear(self, ctx): + self.sounds = [] + + @commands.command() + async def welcome(self, ctx, user=None): + if not user: + user = ctx.message.author.name + try: + audio_file = random.choice([f for f in os.listdir(self.audio_path + '%s/' % user) if f.endswith('.mp3')]) + audio_file = self.audio_path + '/%s/' % user + audio_file + except: + audio_file = random.choice([f for f in Path(self.audio_path + '/').glob('**/*.mp3')]) + self.sounds.append(('file', audio_file, ctx)) + + @commands.command() + async def repeat(self, ctx): + # if ctx.message.author.name == self.bot.user.name: + # return + user = ctx.message.author.name + source = self.sounds_history[0] + self.sounds.append(source) + + @commands.command(help="detail du dernier son joué") + async def last(self, ctx, number = 1): + number = int(number) + for sound in self.sounds_history[0:number]: + await ctx.channel.send("```"+str(sound[1])+"```") + + @commands.command() + async def join(self, chan_name: discord.VoiceChannel): + """Joins a voice channel""" + + #if ctx.voice_client is not None: + # return await ctx.voice_client.move_to(channel) + channel = [x for x in self.bot.get_all_channels() if x.name == chan_name][0] + return await channel.connect() + + await channel.connect() + + @commands.command() + async def play(self, ctx, *, url): + """Plays from a url (almost anything youtube_dl supports)""" + self.sounds.append(('url',url,ctx)) + + @commands.command() + async def stream(self, ctx, *, url): + """Streams from a url (same as yt, but doesn't predownload)""" + + async with ctx.typing(): + player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True) + ctx.voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None) + + await ctx.send(f'Now playing: {player.title}') + + @commands.command() + async def stop(self, ctx): + await ctx.voice_client.stop() + + @commands.command() + async def volume(self, ctx, volume: int): + """Changes the player's volume""" + + if ctx.voice_client is None: + return await ctx.send("Not connected to a voice channel.") + + ctx.voice_client.source.volume = volume / 100 + await ctx.send(f"Changed volume to {volume}%") + + @commands.command() + async def leave(self, ctx): + """Stops and disconnects the bot from voice""" + + await ctx.voice_client.disconnect() + + @commands.command() + async def joke(self, ctx, folder=None): + try: + user = ctx.message.author.name + if not folder or not ctx.message.content: + audio_file = random.choice([f"{f}" for f in Path(self.audio_path + '/').glob('**/*.mp3')]) + elif folder: + folder = folder.lower() + audio_files = [f for f in Path(self.audio_path + '/').glob('**/*.mp3') if folder in str(f).lower()] + if not audio_files: + await ctx.channel.send("%s not found" % folder) + return + else: + audio_file = random.choice(audio_files) + self.sounds.append(('file', audio_file, ctx)) + except: + e = exc_info()[0] + await ctx.channel.send("Exception when calling joke: %s\n" % e) + + @play.before_invoke + @joke.before_invoke + @repeat.before_invoke + @stream.before_invoke + async def ensure_voice(self, ctx): + if ctx.voice_client is None: + if ctx.author.voice: + await ctx.author.voice.channel.connect() + else: + await ctx.send("You are not connected to a voice channel.") + raise commands.CommandError("Author not connected to a voice channel.") + elif ctx.voice_client.is_playing(): + pass + + diff --git a/kabot/kabot/ressources/avatar_bot/.gitkeep b/kabot/kabot/utils/ressources/.gitkeep similarity index 100% rename from kabot/kabot/ressources/avatar_bot/.gitkeep rename to kabot/kabot/utils/ressources/.gitkeep diff --git a/kabot/kabot/utils/ressources/avatar_bot/.gitkeep b/kabot/kabot/utils/ressources/avatar_bot/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/kabot/kabot/ressources/avatar_bot/404.jpg b/kabot/kabot/utils/ressources/avatar_bot/404.jpg similarity index 100% rename from kabot/kabot/ressources/avatar_bot/404.jpg rename to kabot/kabot/utils/ressources/avatar_bot/404.jpg diff --git a/kabot/kabot/ressources/avatar_bot/Bender.jpg b/kabot/kabot/utils/ressources/avatar_bot/Bender.jpg similarity index 100% rename from kabot/kabot/ressources/avatar_bot/Bender.jpg rename to kabot/kabot/utils/ressources/avatar_bot/Bender.jpg diff --git a/kabot/kabot/ressources/avatar_bot/Gaspard_et_Balthazar.jpg b/kabot/kabot/utils/ressources/avatar_bot/Gaspard_et_Balthazar.jpg similarity index 100% rename from kabot/kabot/ressources/avatar_bot/Gaspard_et_Balthazar.jpg rename to kabot/kabot/utils/ressources/avatar_bot/Gaspard_et_Balthazar.jpg diff --git a/kabot/kabot/ressources/avatar_bot/Gunther.jpg b/kabot/kabot/utils/ressources/avatar_bot/Gunther.jpg similarity index 100% rename from kabot/kabot/ressources/avatar_bot/Gunther.jpg rename to kabot/kabot/utils/ressources/avatar_bot/Gunther.jpg diff --git a/kabot/kabot/ressources/avatar_bot/Kabot.jpg b/kabot/kabot/utils/ressources/avatar_bot/Kabot.jpg similarity index 100% rename from kabot/kabot/ressources/avatar_bot/Kabot.jpg rename to kabot/kabot/utils/ressources/avatar_bot/Kabot.jpg diff --git a/kabot/kabot/ressources/avatar_bot/MissSaugnacEtCambran2022.jpg b/kabot/kabot/utils/ressources/avatar_bot/MissSaugnacEtCambran2022.jpg similarity index 100% rename from kabot/kabot/ressources/avatar_bot/MissSaugnacEtCambran2022.jpg rename to kabot/kabot/utils/ressources/avatar_bot/MissSaugnacEtCambran2022.jpg diff --git a/kabot/kabot/ressources/avatar_bot/Zoidberg.jpg b/kabot/kabot/utils/ressources/avatar_bot/Zoidberg.jpg similarity index 100% rename from kabot/kabot/ressources/avatar_bot/Zoidberg.jpg rename to kabot/kabot/utils/ressources/avatar_bot/Zoidberg.jpg diff --git a/kabot/kabot/ressources/base_kml.xml b/kabot/kabot/utils/ressources/base_kml.xml similarity index 100% rename from kabot/kabot/ressources/base_kml.xml rename to kabot/kabot/utils/ressources/base_kml.xml diff --git a/kabot/kabot/ressources/contrepeteries.txt b/kabot/kabot/utils/ressources/contrepeteries.txt similarity index 100% rename from kabot/kabot/ressources/contrepeteries.txt rename to kabot/kabot/utils/ressources/contrepeteries.txt diff --git a/kabot/kabot/utils/texte.py b/kabot/kabot/utils/texte.py new file mode 100644 index 0000000..999a4d1 --- /dev/null +++ b/kabot/kabot/utils/texte.py @@ -0,0 +1,453 @@ +# -*- 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): + self.kron.start() + + @commands.Cog.listener() + async def on_message(self, message): + if message.author == self.bot.user or message.content.startswith('!'): + 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, 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 + diff --git a/kabot/requirements_dev.txt b/kabot/requirements_dev.txt deleted file mode 100644 index c54c8ce..0000000 --- a/kabot/requirements_dev.txt +++ /dev/null @@ -1,10 +0,0 @@ -pip==19.2.3 -bump2version==0.5.11 -wheel==0.33.6 -watchdog==0.9.0 -flake8==3.7.8 -tox==3.14.0 -coverage==4.5.4 -Sphinx==1.8.5 -twine==1.14.0 - diff --git a/kabot/setup.py b/kabot/setup.py index 4d99e68..0a6880f 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -18,7 +18,7 @@ requirements = [ 'aiocron', 'python-gitlab', 'giphy_client', - 'youtube_dl', + 'yt-dl', ] setup_requirements = [ ] @@ -28,7 +28,7 @@ test_requirements = [ ] setup( author="Michaël Ricart", author_email='michael.ricart@0w.tf', - python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*', + python_requires='>=3.11', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', diff --git a/kabot/tox.ini b/kabot/tox.ini deleted file mode 100644 index e9b5d39..0000000 --- a/kabot/tox.ini +++ /dev/null @@ -1,20 +0,0 @@ -[tox] -envlist = py27, py35, py36, py37 flake8 - -[travis] -python = - 3.7: py37 - 3.6: py36 - 3.5: py35 - 2.7: py27 - -[testenv:flake8] -basepython = python -deps = flake8 -commands = flake8 kabot - -[testenv] -setenv = - PYTHONPATH = {toxinidir} - -commands = python setup.py test diff --git a/pinned.cfg b/pinned.cfg deleted file mode 100644 index cbcc074..0000000 --- a/pinned.cfg +++ /dev/null @@ -1,36 +0,0 @@ -[versions] -Click = 7.0 -Jinja2 = 2.10.1 -MarkupSafe = 1.1.1 -async-timeout = 3.0.1 -attrs = 19.1.0 -binaryornot = 0.4.4 -certifi = 2019.9.11 -chardet = 3.0.4 -cookiecutter = 1.6.0 -future = 0.17.1 -idna = 2.8 -jinja2-time = 0.2.0 -mr.developer = 2.0.0 -multidict = 4.5.2 -poyo = 0.5.0 -requests = 2.22.0 -urllib3 = 1.25.6 -websockets = 6.0 -whichcraft = 0.6.1 -yarl = 1.3.0 -zc.buildout = 2.13.2 -zc.recipe.egg = 2.0.7 - -# Required by: -# jinja2-time==0.2.0 -arrow = 0.15.2 - -# Required by: -# arrow==0.15.2 -python-dateutil = 2.8.0 - -# Required by: -# mr.developer==2.0.0 -six = 1.12.0 - From d77d390efe4976cbbc1b12db2c43d9df37b2c539 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Tue, 26 Dec 2023 13:25:05 +0100 Subject: [PATCH 07/35] typo --- kabot/setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kabot/setup.py b/kabot/setup.py index 0a6880f..6623ba7 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -18,7 +18,7 @@ requirements = [ 'aiocron', 'python-gitlab', 'giphy_client', - 'yt-dl', + 'yt-dlp', ] setup_requirements = [ ] From d2291738bbf2031e41c4d1ac03385cd9401ace56 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Tue, 26 Dec 2023 13:28:46 +0100 Subject: [PATCH 08/35] fix import && update version --- kabot/kabot/kabot.py | 4 ++-- kabot/setup.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/kabot/kabot/kabot.py b/kabot/kabot/kabot.py index b9d3b97..bc1c9e8 100644 --- a/kabot/kabot/kabot.py +++ b/kabot/kabot/kabot.py @@ -6,8 +6,8 @@ import discord import yt_dlp as youtube_dl from discord.ext import commands -from utils.audio import * -from utils.texte import * +from kabot.utils.audio import * +from kabot.utils.texte import * diff --git a/kabot/setup.py b/kabot/setup.py index 6623ba7..255afee 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -58,6 +58,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.1.0', + version='0.2.0', zip_safe=False, ) From 55d4045a2e3fa3fc03b2813c24ccde0eb8ee1112 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Tue, 26 Dec 2023 13:42:00 +0100 Subject: [PATCH 09/35] fix entrypoint --- kabot/kabot/kabot.py | 5 ++++- kabot/setup.py | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/kabot/kabot/kabot.py b/kabot/kabot/kabot.py index bc1c9e8..3b2a859 100644 --- a/kabot/kabot/kabot.py +++ b/kabot/kabot/kabot.py @@ -94,5 +94,8 @@ async def main(): ) await bot.start(token) -if __name__ == "__main__": +def run(): asyncio.run(main()) + +if __name__ == "__main__": + run() diff --git a/kabot/setup.py b/kabot/setup.py index 255afee..7d65754 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -44,7 +44,7 @@ setup( description="kabot for discord", entry_points={ 'console_scripts': [ - 'kabot=kabot.kabot:main', + 'kabot=kabot.kabot:run', ], }, install_requires=requirements, From 30e89ba49ce2e3af904854ef8305122f3ee7c2f7 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Tue, 26 Dec 2023 13:42:52 +0100 Subject: [PATCH 10/35] update version --- kabot/setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kabot/setup.py b/kabot/setup.py index 7d65754..a3724cf 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -58,6 +58,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.2.0', + version='0.2.1', zip_safe=False, ) From ccde0ff81d98de753aff8f84ba983e0c376bb9b9 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Tue, 26 Dec 2023 15:32:21 +0100 Subject: [PATCH 11/35] deploy dockerfile --- Dockerfile | 11 +++++++++++ config.ini.sample | 2 +- entrypoint.sh | 3 +++ kabot/MANIFEST.in | 1 + kabot/kabot/ressources/.gitkeep | 0 kabot/setup.py | 3 +++ 6 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 Dockerfile create mode 100755 entrypoint.sh delete mode 100644 kabot/kabot/ressources/.gitkeep diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..efe041a --- /dev/null +++ b/Dockerfile @@ -0,0 +1,11 @@ +FROM python:3.11 + +WORKDIR /usr/src/kabot +ENV CONFIG_FILE=/data/config.ini +COPY kabot ./ +COPY config.ini.sample /data/config.ini +COPY entrypoint.sh / + +RUN pip install --no-cache-dir /usr/src/kabot/ + +CMD [ "/entrypoint.sh" ] diff --git a/config.ini.sample b/config.ini.sample index c979083..9e5e06b 100644 --- a/config.ini.sample +++ b/config.ini.sample @@ -1,6 +1,6 @@ [DEFAULT] -logs = /var/log/kabot/kabot.log +logs = /var/log/kabot.log audio_path = /tmp/ voice_channel = channel_name text_channel = channel_name diff --git a/entrypoint.sh b/entrypoint.sh new file mode 100755 index 0000000..656edfe --- /dev/null +++ b/entrypoint.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +kabot -c $CONFIG_FILE diff --git a/kabot/MANIFEST.in b/kabot/MANIFEST.in index 965b2dd..7b4adff 100644 --- a/kabot/MANIFEST.in +++ b/kabot/MANIFEST.in @@ -3,6 +3,7 @@ include CONTRIBUTING.rst include HISTORY.rst include LICENSE include README.rst +include kabot/utils/ressources/* recursive-include tests * recursive-exclude * __pycache__ diff --git a/kabot/kabot/ressources/.gitkeep b/kabot/kabot/ressources/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/kabot/setup.py b/kabot/setup.py index a3724cf..01c0849 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -19,6 +19,8 @@ requirements = [ 'python-gitlab', 'giphy_client', 'yt-dlp', + 'lxml', + 'BeautifulSoup4', ] setup_requirements = [ ] @@ -51,6 +53,7 @@ setup( license="BSD license", long_description=readme + '\n\n' + history, include_package_data=True, + package_data={'ressources': ['kabot/utils/ressources/*']}, keywords='kabot', name='kabot', packages=find_packages(include=['kabot', 'kabot.*']), From 82c5c6501c50bf3acc4c6189bbf8900150700506 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Wed, 27 Dec 2023 08:37:20 +0100 Subject: [PATCH 12/35] fix kron function --- kabot/kabot/utils/texte.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kabot/kabot/utils/texte.py b/kabot/kabot/utils/texte.py index 999a4d1..303a31d 100644 --- a/kabot/kabot/utils/texte.py +++ b/kabot/kabot/utils/texte.py @@ -322,7 +322,7 @@ class Texte(commands.Cog): @tasks.loop(seconds=3600) async def kron(self): - kron_choice = random.choice([self.kaamelott, self.slap, self.kamoulox, self.contrepeterie, schizo, None, None, None, None, None, None]) + 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(): From a046a4d55f4e40408857610010b2df46640a40ba Mon Sep 17 00:00:00 2001 From: Milka64 Date: Wed, 27 Dec 2023 08:38:28 +0100 Subject: [PATCH 13/35] update version --- kabot/setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kabot/setup.py b/kabot/setup.py index 01c0849..ebef0c8 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -61,6 +61,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.2.1', + version='0.2.2', zip_safe=False, ) From ff98d6b4534da2ae88825292b0b9adc9e70709e6 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Wed, 27 Dec 2023 16:54:31 +0100 Subject: [PATCH 14/35] rattrapage --- Dockerfile | 3 ++- kabot/kabot/kabot.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index efe041a..b7537c9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -5,7 +5,8 @@ ENV CONFIG_FILE=/data/config.ini COPY kabot ./ COPY config.ini.sample /data/config.ini COPY entrypoint.sh / - +RUN apt update && apt install -y ffmpeg +RUN apt clean RUN pip install --no-cache-dir /usr/src/kabot/ CMD [ "/entrypoint.sh" ] diff --git a/kabot/kabot/kabot.py b/kabot/kabot/kabot.py index 3b2a859..f92c679 100644 --- a/kabot/kabot/kabot.py +++ b/kabot/kabot/kabot.py @@ -80,7 +80,7 @@ async def main(): bot, voice_chan=voice_channel, text_chan=text_channel, - audio_path='/home/mika/kabot_audio/' + audio_path=audio_path, ) ) await bot.add_cog( From e8fef9801e52b2779014d9baf73ca0c5da26fb9e Mon Sep 17 00:00:00 2001 From: Milka64 Date: Wed, 27 Dec 2023 17:07:15 +0100 Subject: [PATCH 15/35] ci-cd --- .gitlab-ci.yml | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 .gitlab-ci.yml diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..bec004f --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,21 @@ +stages: + - login + - build + - push + - deploy + +deploy: + stage: deploy + script : sudo docker-compose --env-file /data/docker/compose-files/others.env -f /data/docker/compose-files/others.yml up -d + +build: + stage: build + script: sudo docker build -t hub.0w.tf/milka64/kabot:latest . + +push: + stage: push + script: sudo docker push hub.0w.tf/milka64/kabot:latest + +login: + stage: login + script: sudo docker login -u milka64 -p $GL_TOKEN From 5dd913d1cae3e6282372dcd4a60f409f248f2982 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Wed, 27 Dec 2023 17:10:36 +0100 Subject: [PATCH 16/35] update variable --- .gitlab-ci.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index bec004f..b79b928 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -4,6 +4,9 @@ stages: - push - deploy +variables: + GL_TOKEN: $GL_TOKEN + deploy: stage: deploy script : sudo docker-compose --env-file /data/docker/compose-files/others.env -f /data/docker/compose-files/others.yml up -d From 8e654da976ef228e7df69a80ada121caee966899 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Wed, 27 Dec 2023 17:12:00 +0100 Subject: [PATCH 17/35] update variable --- .gitlab-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index b79b928..691a9c4 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -21,4 +21,4 @@ push: login: stage: login - script: sudo docker login -u milka64 -p $GL_TOKEN + script: sudo docker login -u milka64 -p $GL_TOKEN hub.0w.tf From c3e590fd2c7a81bd6f39bea7568d9e6192db5c57 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Thu, 28 Dec 2023 11:32:02 +0100 Subject: [PATCH 18/35] fix #11 --- .gitlab-ci.yml | 9 +++++++-- kabot/kabot/utils/audio.py | 5 +++-- kabot/setup.py | 2 +- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 691a9c4..db2e650 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -6,6 +6,7 @@ stages: variables: GL_TOKEN: $GL_TOKEN + VERSION: '0.2.3' deploy: stage: deploy @@ -13,11 +14,15 @@ deploy: build: stage: build - script: sudo docker build -t hub.0w.tf/milka64/kabot:latest . + script: + - sudo docker build -t hub.0w.tf/milka64/kabot:$VERSION . + - sudo docker build -t hub.0w.tf/milka64/kabot:latest . push: stage: push - script: sudo docker push hub.0w.tf/milka64/kabot:latest + script: + - sudo docker push hub.0w.tf/milka64/kabot:$VERSION + - sudo docker push hub.0w.tf/milka64/kabot:latest login: stage: login diff --git a/kabot/kabot/utils/audio.py b/kabot/kabot/utils/audio.py index f1fac67..495fc45 100644 --- a/kabot/kabot/utils/audio.py +++ b/kabot/kabot/utils/audio.py @@ -210,8 +210,7 @@ class Audio(commands.Cog, name="Commandes Audio"): @commands.command() async def repeat(self, ctx): - # if ctx.message.author.name == self.bot.user.name: - # return + """Rejouer le dernier son joué""" user = ctx.message.author.name source = self.sounds_history[0] self.sounds.append(source) @@ -250,6 +249,7 @@ class Audio(commands.Cog, name="Commandes Audio"): @commands.command() async def stop(self, ctx): + """Stoppe la lecture en cours""" await ctx.voice_client.stop() @commands.command() @@ -270,6 +270,7 @@ class Audio(commands.Cog, name="Commandes Audio"): @commands.command() async def joke(self, ctx, folder=None): + """Joue un son (aléatoire par défaut)""" try: user = ctx.message.author.name if not folder or not ctx.message.content: diff --git a/kabot/setup.py b/kabot/setup.py index ebef0c8..873ff53 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -61,6 +61,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.2.2', + version='0.2.3', zip_safe=False, ) From 012feae29c116ace2a60b0124fc8bdea394bc549 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Thu, 28 Dec 2023 17:10:52 +0100 Subject: [PATCH 19/35] WIP #51 --- .gitlab-ci.yml | 2 +- kabot/kabot/utils/audio.py | 12 ++++++++++++ kabot/setup.py | 2 +- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index db2e650..8d8ee73 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -6,7 +6,7 @@ stages: variables: GL_TOKEN: $GL_TOKEN - VERSION: '0.2.3' + VERSION: '0.2.4' deploy: stage: deploy diff --git a/kabot/kabot/utils/audio.py b/kabot/kabot/utils/audio.py index 495fc45..1384a4d 100644 --- a/kabot/kabot/utils/audio.py +++ b/kabot/kabot/utils/audio.py @@ -199,6 +199,7 @@ class Audio(commands.Cog, name="Commandes Audio"): @commands.command() async def welcome(self, ctx, user=None): + """Joue le son d'accueil de l'utilisateur""" if not user: user = ctx.message.author.name try: @@ -268,6 +269,17 @@ class Audio(commands.Cog, name="Commandes Audio"): await ctx.voice_client.disconnect() + @commands.command() + async def find(self, ctx, query): + """Cherche un son dans la bibliothèque""" + if query: + query = query.lower() + audio_files = [f for f in Path(self.audio_path + '/').glob('**/*.mp3') if query in str(f).lower()] + if not audio_files: + await ctx.channel.send("%s not found" % query) + else: + await ctx.channel.send("\n".join(audio_files)) + @commands.command() async def joke(self, ctx, folder=None): """Joue un son (aléatoire par défaut)""" diff --git a/kabot/setup.py b/kabot/setup.py index 873ff53..243ee57 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -61,6 +61,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.2.3', + version='0.2.4', zip_safe=False, ) From a6a7eb07bc4ff9d76aab78436de5131d61f4b8b4 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Fri, 29 Dec 2023 10:24:03 +0100 Subject: [PATCH 20/35] WIP #51 --- .gitlab-ci.yml | 2 +- kabot/kabot/utils/audio.py | 14 +++++++------- kabot/setup.py | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 8d8ee73..f34345e 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -6,7 +6,7 @@ stages: variables: GL_TOKEN: $GL_TOKEN - VERSION: '0.2.4' + VERSION: '0.2.5' deploy: stage: deploy diff --git a/kabot/kabot/utils/audio.py b/kabot/kabot/utils/audio.py index 1384a4d..fee3bf1 100644 --- a/kabot/kabot/utils/audio.py +++ b/kabot/kabot/utils/audio.py @@ -272,13 +272,13 @@ class Audio(commands.Cog, name="Commandes Audio"): @commands.command() async def find(self, ctx, query): """Cherche un son dans la bibliothèque""" - if query: - query = query.lower() - audio_files = [f for f in Path(self.audio_path + '/').glob('**/*.mp3') if query in str(f).lower()] - if not audio_files: - await ctx.channel.send("%s not found" % query) - else: - await ctx.channel.send("\n".join(audio_files)) + query = query.lower() + audio_files = [f for f in Path(self.audio_path + '/').glob('**/*.mp3') if query in str(f).lower()] + if not audio_files: + await ctx.channel.send("%s not found" % query) + else: + for file in audio_files: + await ctx.channel.send("```"+str(file)+"```") @commands.command() async def joke(self, ctx, folder=None): diff --git a/kabot/setup.py b/kabot/setup.py index 243ee57..649d6cf 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -61,6 +61,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.2.4', + version='0.2.5', zip_safe=False, ) From 2d893dbda20516366475a9082838e11f79339c8c Mon Sep 17 00:00:00 2001 From: Milka64 Date: Fri, 29 Dec 2023 10:34:41 +0100 Subject: [PATCH 21/35] =?UTF-8?q?Ajout=20d'une=20limite=20=C3=A0=20la=20co?= =?UTF-8?q?mmande=20find=20#51?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitlab-ci.yml | 2 +- kabot/kabot/utils/audio.py | 4 ++-- kabot/setup.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index f34345e..39806f5 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -6,7 +6,7 @@ stages: variables: GL_TOKEN: $GL_TOKEN - VERSION: '0.2.5' + VERSION: '0.2.6' deploy: stage: deploy diff --git a/kabot/kabot/utils/audio.py b/kabot/kabot/utils/audio.py index fee3bf1..3ac1442 100644 --- a/kabot/kabot/utils/audio.py +++ b/kabot/kabot/utils/audio.py @@ -271,13 +271,13 @@ class Audio(commands.Cog, name="Commandes Audio"): @commands.command() async def find(self, ctx, query): - """Cherche un son dans la bibliothèque""" + """Cherche un son dans la bibliothèque (5 resultat max)""" query = query.lower() audio_files = [f for f in Path(self.audio_path + '/').glob('**/*.mp3') if query in str(f).lower()] if not audio_files: await ctx.channel.send("%s not found" % query) else: - for file in audio_files: + for file in audio_files[:6]: await ctx.channel.send("```"+str(file)+"```") @commands.command() diff --git a/kabot/setup.py b/kabot/setup.py index 649d6cf..f868440 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -61,6 +61,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.2.5', + version='0.2.6', zip_safe=False, ) From d913af437810541d4ff329f2c10f5eb4d36848bf Mon Sep 17 00:00:00 2001 From: Milka64 Date: Fri, 29 Dec 2023 11:54:19 +0100 Subject: [PATCH 22/35] WIP #32 --- .gitlab-ci.yml | 2 +- kabot/kabot/utils/texte.py | 18 ++++++++++++++++++ kabot/setup.py | 2 +- 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 39806f5..100f19f 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -6,7 +6,7 @@ stages: variables: GL_TOKEN: $GL_TOKEN - VERSION: '0.2.6' + VERSION: '0.2.7' deploy: stage: deploy diff --git a/kabot/kabot/utils/texte.py b/kabot/kabot/utils/texte.py index 303a31d..716c184 100644 --- a/kabot/kabot/utils/texte.py +++ b/kabot/kabot/utils/texte.py @@ -53,11 +53,29 @@ class Texte(commands.Cog): @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 \ diff --git a/kabot/setup.py b/kabot/setup.py index f868440..d4447e1 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -61,6 +61,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.2.6', + version='0.2.7', zip_safe=False, ) From f2b663861605d94920710ebcacd316842057417c Mon Sep 17 00:00:00 2001 From: Milka64 Date: Fri, 29 Dec 2023 14:00:02 +0100 Subject: [PATCH 23/35] WIP #32 --- .gitlab-ci.yml | 2 +- kabot/kabot/utils/texte.py | 2 +- kabot/setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 100f19f..283f129 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -6,7 +6,7 @@ stages: variables: GL_TOKEN: $GL_TOKEN - VERSION: '0.2.7' + VERSION: '0.2.8' deploy: stage: deploy diff --git a/kabot/kabot/utils/texte.py b/kabot/kabot/utils/texte.py index 716c184..73bdb42 100644 --- a/kabot/kabot/utils/texte.py +++ b/kabot/kabot/utils/texte.py @@ -302,7 +302,7 @@ class Texte(commands.Cog): for member in members: if member.nick.lower() == wordi.lower()[1:]: sentence = sentence.replace(word, member.mention) - ctx.message = sentence + ctx.message.content = sentence await cmd.invoke(ctx) else: for word in sentence.split(): diff --git a/kabot/setup.py b/kabot/setup.py index d4447e1..dabada6 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -61,6 +61,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.2.7', + version='0.2.8', zip_safe=False, ) From daa3c7aa0d6590ea3bedec9ee1a523734cbda16e Mon Sep 17 00:00:00 2001 From: Milka64 Date: Fri, 29 Dec 2023 14:20:47 +0100 Subject: [PATCH 24/35] WIP #32 --- .gitlab-ci.yml | 2 +- kabot/kabot/utils/texte.py | 28 +++++++--------------------- kabot/setup.py | 2 +- 3 files changed, 9 insertions(+), 23 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 283f129..675136c 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -6,7 +6,7 @@ stages: variables: GL_TOKEN: $GL_TOKEN - VERSION: '0.2.8' + VERSION: '0.2.9' deploy: stage: deploy diff --git a/kabot/kabot/utils/texte.py b/kabot/kabot/utils/texte.py index 73bdb42..51e140c 100644 --- a/kabot/kabot/utils/texte.py +++ b/kabot/kabot/utils/texte.py @@ -291,27 +291,13 @@ class Texte(commands.Cog): 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.content = 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) + 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): diff --git a/kabot/setup.py b/kabot/setup.py index dabada6..e584bee 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -61,6 +61,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.2.8', + version='0.2.9', zip_safe=False, ) From d33eb077a7f685fcc203875d77b5a5dca11ce2fb Mon Sep 17 00:00:00 2001 From: Milka64 Date: Fri, 29 Dec 2023 14:48:17 +0100 Subject: [PATCH 25/35] WIP #32 --- .gitlab-ci.yml | 2 +- kabot/kabot/utils/texte.py | 13 +------------ kabot/setup.py | 2 +- 3 files changed, 3 insertions(+), 14 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 675136c..5a0450e 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -6,7 +6,7 @@ stages: variables: GL_TOKEN: $GL_TOKEN - VERSION: '0.2.9' + VERSION: '0.2.10' deploy: stage: deploy diff --git a/kabot/kabot/utils/texte.py b/kabot/kabot/utils/texte.py index 51e140c..481d91b 100644 --- a/kabot/kabot/utils/texte.py +++ b/kabot/kabot/utils/texte.py @@ -64,18 +64,7 @@ class Texte(commands.Cog): @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) + if message.author == self.bot.user and not message.content.startswith('!'): return else: if self.bot.user in message.mentions \ diff --git a/kabot/setup.py b/kabot/setup.py index e584bee..99e4757 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -61,6 +61,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.2.9', + version='0.2.10', zip_safe=False, ) From 26a30c9af874a35c6b244770ec36a5ec19693062 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Fri, 29 Dec 2023 15:00:02 +0100 Subject: [PATCH 26/35] WIP #32 --- .gitlab-ci.yml | 2 +- kabot/kabot/utils/texte.py | 2 +- kabot/setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 5a0450e..743904f 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -6,7 +6,7 @@ stages: variables: GL_TOKEN: $GL_TOKEN - VERSION: '0.2.10' + VERSION: '0.2.11' deploy: stage: deploy diff --git a/kabot/kabot/utils/texte.py b/kabot/kabot/utils/texte.py index 481d91b..2afc52b 100644 --- a/kabot/kabot/utils/texte.py +++ b/kabot/kabot/utils/texte.py @@ -83,7 +83,7 @@ class Texte(commands.Cog): else: await asyncio.sleep(len(response) / 6) await message.channel.send(response) - await self.bot.process_commands(message) + await self.bot.process_commands(message.content) @commands.command(help='list des commits') async def commits(self, ctx, number = 5): diff --git a/kabot/setup.py b/kabot/setup.py index 99e4757..45f714e 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -61,6 +61,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.2.10', + version='0.2.11', zip_safe=False, ) From 2d8518e1697d92a23b3366018ddd637b4021efc3 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Fri, 29 Dec 2023 15:10:40 +0100 Subject: [PATCH 27/35] WIP #32 --- .gitlab-ci.yml | 2 +- kabot/kabot/utils/texte.py | 2 +- kabot/setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 743904f..6684257 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -6,7 +6,7 @@ stages: variables: GL_TOKEN: $GL_TOKEN - VERSION: '0.2.11' + VERSION: '0.2.12' deploy: stage: deploy diff --git a/kabot/kabot/utils/texte.py b/kabot/kabot/utils/texte.py index 2afc52b..a67bd36 100644 --- a/kabot/kabot/utils/texte.py +++ b/kabot/kabot/utils/texte.py @@ -83,7 +83,7 @@ class Texte(commands.Cog): else: await asyncio.sleep(len(response) / 6) await message.channel.send(response) - await self.bot.process_commands(message.content) + #await self.bot.process_commands(message) @commands.command(help='list des commits') async def commits(self, ctx, number = 5): diff --git a/kabot/setup.py b/kabot/setup.py index 45f714e..ad217f1 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -61,6 +61,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.2.11', + version='0.2.12', zip_safe=False, ) From 2fadbe74c04cd99b4f19bfe1897fb2886c8943fc Mon Sep 17 00:00:00 2001 From: Milka64 Date: Fri, 29 Dec 2023 15:21:57 +0100 Subject: [PATCH 28/35] WIP #32 --- .gitlab-ci.yml | 2 +- kabot/kabot/utils/texte.py | 2 +- kabot/setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 6684257..bb226a4 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -6,7 +6,7 @@ stages: variables: GL_TOKEN: $GL_TOKEN - VERSION: '0.2.12' + VERSION: '0.2.13' deploy: stage: deploy diff --git a/kabot/kabot/utils/texte.py b/kabot/kabot/utils/texte.py index a67bd36..e1a3da3 100644 --- a/kabot/kabot/utils/texte.py +++ b/kabot/kabot/utils/texte.py @@ -53,7 +53,7 @@ class Texte(commands.Cog): @commands.Cog.listener() async def on_ready(self): - for channel in bot.get_all_channels(): + for channel in self.bot.get_all_channels(): if channel.name == text_channel: current_chan = channel if nickname: diff --git a/kabot/setup.py b/kabot/setup.py index ad217f1..142ebf6 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -61,6 +61,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.2.12', + version='0.2.13', zip_safe=False, ) From 9a4e9b373530eff8d820b23aa5dbd71a8fd455a8 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Fri, 29 Dec 2023 15:32:40 +0100 Subject: [PATCH 29/35] Fix welcome text message --- .gitlab-ci.yml | 2 +- kabot/kabot/utils/texte.py | 6 +++--- kabot/setup.py | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index bb226a4..a499b35 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -6,7 +6,7 @@ stages: variables: GL_TOKEN: $GL_TOKEN - VERSION: '0.2.13' + VERSION: '0.2.14' deploy: stage: deploy diff --git a/kabot/kabot/utils/texte.py b/kabot/kabot/utils/texte.py index e1a3da3..a548351 100644 --- a/kabot/kabot/utils/texte.py +++ b/kabot/kabot/utils/texte.py @@ -54,10 +54,10 @@ class Texte(commands.Cog): @commands.Cog.listener() async def on_ready(self): for channel in self.bot.get_all_channels(): - if channel.name == text_channel: + if channel.name == self.text_channel: current_chan = channel - if nickname: - await bot.user.edit(nick=nickname) + if self.nickname: + await self.bot.user.edit(nick=self.nickname) await current_chan.send('Le troll est dans la place !') self.kron.start() diff --git a/kabot/setup.py b/kabot/setup.py index 142ebf6..95f19cd 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -61,6 +61,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.2.13', + version='0.2.14', zip_safe=False, ) From 3cdec52d813fd0c01d3bc1bcadfb10bed0fce318 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Fri, 29 Dec 2023 15:39:10 +0100 Subject: [PATCH 30/35] Fix welcome text message --- .gitlab-ci.yml | 2 +- kabot/kabot/utils/texte.py | 2 +- kabot/setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index a499b35..ca00519 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -6,7 +6,7 @@ stages: variables: GL_TOKEN: $GL_TOKEN - VERSION: '0.2.14' + VERSION: '0.2.15' deploy: stage: deploy diff --git a/kabot/kabot/utils/texte.py b/kabot/kabot/utils/texte.py index a548351..2192fb3 100644 --- a/kabot/kabot/utils/texte.py +++ b/kabot/kabot/utils/texte.py @@ -54,7 +54,7 @@ class Texte(commands.Cog): @commands.Cog.listener() async def on_ready(self): for channel in self.bot.get_all_channels(): - if channel.name == self.text_channel: + if channel.name == self.text_chan: current_chan = channel if self.nickname: await self.bot.user.edit(nick=self.nickname) diff --git a/kabot/setup.py b/kabot/setup.py index 95f19cd..2093231 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -61,6 +61,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.2.14', + version='0.2.15', zip_safe=False, ) From 6f2460eaef05057c358f3068e8c3cafdcfe8b03f Mon Sep 17 00:00:00 2001 From: Milka64 Date: Fri, 29 Dec 2023 15:50:46 +0100 Subject: [PATCH 31/35] WIP #32 --- .gitlab-ci.yml | 2 +- kabot/kabot/utils/texte.py | 5 ++++- kabot/setup.py | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index ca00519..4d461e2 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -6,7 +6,7 @@ stages: variables: GL_TOKEN: $GL_TOKEN - VERSION: '0.2.15' + VERSION: '0.2.16' deploy: stage: deploy diff --git a/kabot/kabot/utils/texte.py b/kabot/kabot/utils/texte.py index 2192fb3..61c71aa 100644 --- a/kabot/kabot/utils/texte.py +++ b/kabot/kabot/utils/texte.py @@ -64,7 +64,10 @@ class Texte(commands.Cog): @commands.Cog.listener() async def on_message(self, message): - if message.author == self.bot.user and not message.content.startswith('!'): + if message.author == self.bot.user and message.content.startswith('!'): + if message.content.startswith('!'): + ctx = await self.bot.get_context(message) + await self.bot.invoke(ctx) return else: if self.bot.user in message.mentions \ diff --git a/kabot/setup.py b/kabot/setup.py index 2093231..c85932e 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -61,6 +61,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.2.15', + version='0.2.16', zip_safe=False, ) From b7d3546ceadb1f5b2e6283ffd3fe111057254c57 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Fri, 29 Dec 2023 17:10:09 +0100 Subject: [PATCH 32/35] fix some traceback in logs --- kabot/kabot/kabot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kabot/kabot/kabot.py b/kabot/kabot/kabot.py index f92c679..57668f4 100644 --- a/kabot/kabot/kabot.py +++ b/kabot/kabot/kabot.py @@ -15,7 +15,7 @@ intents = discord.Intents.all() intents.message_content = True bot = commands.Bot( - command_prefix=commands.when_mentioned_or("!"), + command_prefix=commands.command_prefix("!"), description='''A ROULEEEEETTES !! HOULA... J'l'ai un peu trop gueulé ça, non ? A roulettes.''', From 8cca3c1990cce76e56cb43fa2f660db5bdf19402 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Fri, 29 Dec 2023 17:18:12 +0100 Subject: [PATCH 33/35] fix boulette --- kabot/kabot/kabot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kabot/kabot/kabot.py b/kabot/kabot/kabot.py index 57668f4..f92c679 100644 --- a/kabot/kabot/kabot.py +++ b/kabot/kabot/kabot.py @@ -15,7 +15,7 @@ intents = discord.Intents.all() intents.message_content = True bot = commands.Bot( - command_prefix=commands.command_prefix("!"), + command_prefix=commands.when_mentioned_or("!"), description='''A ROULEEEEETTES !! HOULA... J'l'ai un peu trop gueulé ça, non ? A roulettes.''', From 6504c286da5c9c32a4e7de8a0419c5ba13f4b68b Mon Sep 17 00:00:00 2001 From: Milka64 Date: Tue, 2 Jan 2024 15:52:14 +0100 Subject: [PATCH 34/35] add more None un kron --- .gitlab-ci.yml | 2 +- kabot/kabot/utils/texte.py | 2 +- kabot/setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 4d461e2..68dc0ea 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -6,7 +6,7 @@ stages: variables: GL_TOKEN: $GL_TOKEN - VERSION: '0.2.16' + VERSION: '0.2.17' deploy: stage: deploy diff --git a/kabot/kabot/utils/texte.py b/kabot/kabot/utils/texte.py index 61c71aa..189fc1c 100644 --- a/kabot/kabot/utils/texte.py +++ b/kabot/kabot/utils/texte.py @@ -318,7 +318,7 @@ class Texte(commands.Cog): @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]) + kron_choice = random.choice([self.kaamelott, self.slap, self.kamoulox, self.contrepeterie, self.schizo, None, None, None, None, None, None, None,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(): diff --git a/kabot/setup.py b/kabot/setup.py index c85932e..4f88226 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -61,6 +61,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.2.16', + version='0.2.17', zip_safe=False, ) From 6b9e153de1f07dd9da4b227a3d566d234f77df39 Mon Sep 17 00:00:00 2001 From: Milka64 Date: Tue, 2 Jan 2024 16:45:19 +0100 Subject: [PATCH 35/35] try to fix command prefix --- .gitlab-ci.yml | 2 +- kabot/kabot/kabot.py | 2 +- kabot/setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 68dc0ea..af6b124 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -6,7 +6,7 @@ stages: variables: GL_TOKEN: $GL_TOKEN - VERSION: '0.2.17' + VERSION: '0.2.18' deploy: stage: deploy diff --git a/kabot/kabot/kabot.py b/kabot/kabot/kabot.py index f92c679..ffd083b 100644 --- a/kabot/kabot/kabot.py +++ b/kabot/kabot/kabot.py @@ -15,7 +15,7 @@ intents = discord.Intents.all() intents.message_content = True bot = commands.Bot( - command_prefix=commands.when_mentioned_or("!"), + command_prefix="!", description='''A ROULEEEEETTES !! HOULA... J'l'ai un peu trop gueulé ça, non ? A roulettes.''', diff --git a/kabot/setup.py b/kabot/setup.py index 4f88226..20c8caf 100644 --- a/kabot/setup.py +++ b/kabot/setup.py @@ -61,6 +61,6 @@ setup( test_suite='tests', tests_require=test_requirements, url='https://github.com/None/kabot', - version='0.2.17', + version='0.2.18', zip_safe=False, )