Archived
1
0
Fork 0

Garou, Reactionner et Music

Ajoute d'une réaction automatique
Progression sur le Garou
Ajout d'un system de Music (beta)
This commit is contained in:
Ethanell 2018-01-01 19:19:28 +01:00
parent a526d9705a
commit 5e0a36b5fb
5 changed files with 396 additions and 82 deletions

207
Garou.py
View file

@ -2,104 +2,154 @@ import discord
import random
from discord.ext import commands
#Variables de base
game = 0
djoueurs = 0
joueurs = str("0")
gm = str()
joueurs = list()
#Vrai variables
minijoueurs = 5 #Le nombre minimum de joueurs qu'il faut pour lancer une partie
roles = ["", ""] #Les roles donner
def is_joueurs(target):
global joueurs
for i in range(len(joueurs)):
if target == joueurs[i]:
return True
return False
class Garou:
def __init__(self, bot):
self.bot = bot
self.games = {} # contiendra toutes les partie en cours
#Définition du groupe de commande lg
@commands.group(pass_context=True)
async def lg(self, ctx):
if ctx.invoked_subcommand is None:
# do something that should only happen if no subcommands are called
await self.bot.say("Jeux garou : start, joueurs, stop")
def create_game(self, channel_id): # créer une game : ajout d'option possible
game = {
'channel' : channel_id,
'player' : [],
'message' : None
}
return game
def get_game(self,channel_id):
for game in self.games:
if channel_id == game['channel']:
return game
return None
def embed(self):
info = discord.Embed()
info.title = 'Garou : Choose the player'
info.colour = random.randint(0, 0xFFFFFF)
info.add_field(name='Description', value="Voici une description ndu jeu")
info.add_field(name='Info', value="Choose the player by react on this message !")
info.set_footer(text="Loup Garou by jbdo99 & flifloo")
return info
#Commande de démarrage du Garou
@commands.command(pass_context=True, name="lg")
#Commande pour démarre le jeux
@lg.command(pass_context=True)
async def start(self, ctx):
"""Commence la partie"""
if self.get_game(ctx.message.channel) == None: # on verifie si il n y pas de partie en cours dans ce salon
self.games[ctx.message.channel] = self.create_game(ctx.message.channel) # on créer le jeu
game = self.games[ctx.message.channel]
game['message'] = await self.bot.send_message(ctx.message.channel,embed=self.embed()) # on affiche le message et on le met dans le game
for emoji in ["💚"]:
await self.bot.add_reaction(message=game["message"],emoji=emoji) #on fait apparaitre le/les reac du bot
nopi = True #boucle infin (a ccorriger, j vais mettre une time out)
while nopi:
waiter = await self.bot.wait_for_reaction(message=game["message"],timeout=40.0) #on attend les reac (le timeout est mis a 40, j vais modif ca + tard)
if not waiter == None: # si c est pas none
if (waiter[0].emoji == "💚" and waiter[1] != self.bot.user): # si la rec est la bonne et que c est pas le bot (car discord prend du temp a mettre les reac et le bot croie que sa propre reac est une nouvelle)
await self.bot.say("Un joueur en plus !") #ici on mettre l ajout d un utilisateur
else:
await self.bot.say("A game already started")
"""
global game,gm
if game == 1:
print("Commande lg start lancer par: "+str(ctx.message.author)+" refuser, partie deja lancer")
await self.bot.say("Désoler mais une partie est deja en cours !")
elif game == 0:
game=1
gm=ctx.message.author
print("Commande lg start lancer par "+str(ctx.message.author))
#await self.bot.say("Lancement de la partie !")
await self.bot.say("Veuiller specifier les participants avec la commande: ```lg joueurs```.")
#Commande pour definir les participant du Garou
@commands.command(pass_context=True)
async def gjoueurs(self, ctx, *, CMDjoueurs):
global djoueurs
global joueurs
@lg.command(pass_context=True)
async def joueurs(self, ctx):
global djoueurs,joueurs,gm
if game == 0:
print("Commande gjoueurs lancer par: "+str(ctx.message.author)+" refuser, aucune partie lancer !")
print("Commande lg joueurs lancer par: "+str(ctx.message.author)+" refuser, aucune partie lancer !")
await self.bot.say("Désoler mais aucune partie n'est lancer.")
elif game == 1:
if djoueurs == 1:
print("Commande gjoueurs lancer par: "+str(ctx.message.author)+" refuser, partie deja lacer !")
if djoueurs >= 1:
print("Commande lg joueurs lancer par: "+str(ctx.message.author)+" refuser, partie deja lacer !")
await self.bot.say("Désoler mais une partie est deja en cours !")
elif djoueurs == 0:
djoueurs = 1
joueurs = CMDjoueurs
print("Commande gjoueurs lancer par: "+str(ctx.message.author)+" argument: "+str(CMDjoueurs))
await self.bot.say("Les jouer de cette partie sont: "+str(joueurs))
if gm == ctx.message.author:
djoueurs = 1
joueurs.insert(0, ctx.message.author.id)
print("Commande lg joueurs lancer par: "+str(ctx.message.author))
await self.bot.say("Rejoiner la partie avec la commande: ```lg join```.")
else:
print("Commande lg joueurs lancer par: "+str(ctx.message.author)+", refuser car non GM")
await self.bot.say("Désoler mais vous n'étes pas le GM !")
#Commande pour rejoindre la partie
@lg.command(pass_context=True)
async def join(self, ctx):
global djoueurs,joueurs
if game == 0:
print("Commande lg join lancer par: "+str(ctx.message.author)+" refuser, aucune partie lancer !")
await self.bot.say("Désoler mais aucune partie n'est lancer.")
elif game == 1:
if djoueurs == 0:
print("Commande lg join lancer par: "+str(ctx.message.author)+" refuser, definition des joueurs non lancer !")
await self.bot.say("Désoler mais aucunne demande de joueurs est lancer !.")
elif djoueurs == 2:
print("Commande lg join lancer par: "+str(ctx.message.author)+" refuser, joueurs deja defini !")
await self.bot.say("Désoler mais les joueurs sont deja defini.")
elif djoueurs == 1:
if gm == ctx.message.author:
print("Commande lg join lancer par: "+str(ctx.message.author)+" refuser, c'est le GM !")
await self.bot.say("Désoler mais vous êtes le GM, vous avez deja rejoint par defaut.")
else:
joueurs.append(ctx.message.author.id)
print("Commande lg join lancer par: "+str(ctx.message.author))
await self.bot.say("Vous avez rejoin la partie !")
#Commande pour stoper la definition de joueurs
@lg.command(pass_context=True)
async def play(self, ctx):
global joueurs,gm,djoueurs,minijoueurs
if game == 0:
print("Commande lg play lancer par: "+str(ctx.message.author)+" refuser, aucune partie lancer !")
await self.bot.say("Désoler mais aucune partie n'est lancer.")
elif game == 1:
if djoueurs == 0:
print("Commande lg play lancer par: "+str(ctx.message.author)+" refuser, definition des joueurs non lancer !")
await self.bot.say("Désoler mais aucunne demande de joueurs est lancer !.")
elif djoueurs == 2:
print("Commande lg play lancer par: "+str(ctx.message.author)+" refuser, joueurs deja defini !")
await self.bot.say("Désoler mais les joueurs sont deja defini.")
elif djoueurs == 1:
if gm == ctx.message.author:
if len(joueurs) < minijoueurs:
print("Commande lg play lancer par: "+str(ctx.message.author)+", refuser car minimum de joueurs pas atteint")
await self.bot.say("Désoler mais il n'y a que "+str(len(joueurs))+" joueur(s) dans la partie")
else:
djoueurs=2
print("Commande lg play lancer par: "+str(ctx.message.author))
await self.bot.say("Definitions de joueurs terminer !")
await self.bot.say("Il y a "+str(len(joueurs))+" joueurs dans la partie.")
await self.bot.say("Definitions du role de chacun des joueurs en cours...")
else:
print("Commande lg play lancer par: "+str(ctx.message.author)+" refuser, pas le GM !")
await self.bot.say("Désoler mais vous n'êtes pas le GM !")
#Commande de test
@commands.command(pass_content=True)
async def gtest(self, ctx):
sender = ctx.message.author
if is_joueurs(sender) == True:
await self.bot.say("Vous ete bien un joueurs !")
@lg.command(pass_context=True)
async def test(self, ctx):
global gm,joueurs
await self.bot.say("Liste de joueurs: "+str(joueurs))
if gm == ctx.message.author:
await self.bot.say("vous etes le GM !")
elif is_joueurs(ctx.message.author.id) == True:
await self.bot.say("vous etes un joueurs !")
elif gm == ctx.message.author:
await self.bot.say("Vous ete le GM !")
else:
await self.bot.say("Vous n'ete pas un joueurs !")
#Commande pour annuler le Garou
@commands.command(pass_context=True)
async def gstop(self, ctx):
global game,djoueurs
@lg.command(pass_context=True)
async def stop(self, ctx):
global game,djoueurs,gm
if game == 0:
print("Commande gstop lancer par: "+str(ctx.message.author)+" refuser, aucune partie lancer !")
print("Commande lg stop lancer par: "+str(ctx.message.author)+" refuser, aucune partie lancer !")
await self.bot.say("Désoler mais aucune partie n'est lancer.")
elif game == 1:
@ -107,14 +157,15 @@ class Garou:
#reset de toutes les variables
game = 0
djoueurs = 0
gm = 0
print("Partie de garou annuler !")
gm = str()
joueurs = list()
print("Commande lg stop lancer par: "+str(ctx.message.author))
await self.bot.say("La partie de garou est annuler !")
else:
print("Commande gstop mancer par: "+str(ctx.message.author)+" refuser car ce n'est pas le gm !")
await self.bot.say("Désoler mais vous n'avez pas le droit de faire ça, vous n'étes pas le gm !")
"""
print("Commande lg stop lancer par: "+str(ctx.message.author)+" refuser car ce n'est pas le GM !")
await self.bot.say("Désoler mais vous n'avez pas le droit de faire ça, vous n'étes pas le GM !")
def setup(bot):
bot.add_cog(Garou(bot))

233
Music.py Normal file
View file

@ -0,0 +1,233 @@
import asyncio
import discord
from discord.ext import commands
from ctypes.util import find_library
import youtube_dl
if not discord.opus.is_loaded():
# the 'opus' library here is opus.dll on windows
# or libopus.so on linux in the current directory
# you should replace this with the location the
# opus library is located in and with the proper filename.
# note that on windows this DLL is automatically provided for you
discord.opus.load_opus(find_library("opus"))
def __init__(self, bot):
self.bot = bot
class VoiceEntry:
def __init__(self, message, player):
self.requester = message.author
self.channel = message.channel
self.player = player
def __str__(self):
fmt = ' {0.title} uploaded by {0.uploader} and requested by {1.display_name}'
duration = self.player.duration
if duration:
fmt = fmt + ' [length: {0[0]}m {0[1]}s]'.format(divmod(duration, 60))
return fmt.format(self.player, self.requester)
class VoiceState:
def __init__(self, bot):
self.current = None
self.voice = None
self.bot = bot
self.play_next_song = asyncio.Event()
self.songs = asyncio.Queue()
self.skip_votes = set() # a set of user_ids that voted
self.audio_player = self.bot.loop.create_task(self.audio_player_task())
def is_playing(self):
if self.voice is None or self.current is None:
return False
player = self.current.player
return not player.is_done()
@property
def player(self):
return self.current.player
def skip(self):
self.skip_votes.clear()
if self.is_playing():
self.player.stop()
def toggle_next(self):
self.bot.loop.call_soon_threadsafe(self.play_next_song.set)
async def audio_player_task(self):
while True:
self.play_next_song.clear()
self.current = await self.songs.get()
await self.bot.send_message(self.current.channel, ' Joue maintenant ' + str(self.current))
self.current.player.start()
await self.play_next_song.wait()
class Music:
"""Commandes de musique.
"""
def __init__(self, bot):
self.bot = bot
self.voice_states = {}
def get_voice_state(self, server):
state = self.voice_states.get(server.id)
if state is None:
state = VoiceState(self.bot)
self.voice_states[server.id] = state
return state
async def create_voice_client(self, channel):
voice = await self.bot.join_voice_channel(channel)
state = self.get_voice_state(channel.server)
state.voice = voice
def __unload(self):
for state in self.voice_states.values():
try:
state.audio_player.cancel()
if state.voice:
self.bot.loop.create_task(state.voice.disconnect())
except:
pass
@commands.command(pass_context=True, no_pm=True)
async def join(self, ctx, *, channel : discord.Channel):
"""Rejoins le channel vocal. Ne fonctionne que si l'utilisateur est deja dans un channel.
Ne semble pas fonctionner pour le moment."""
try:
await self.create_voice_client(channel)
except discord.ClientException:
await self.bot.say('Already in a voice channel...')
except discord.InvalidArgument:
await self.bot.say('This is not a voice channel...')
else:
await self.bot.say('Ready to play audio in **' + channel.name)
@commands.command(pass_context=True, no_pm=True)
async def summon(self, ctx):
"""Invoque le bot dans le channel vocal.
Ne fonctionne que si l'utilisateur est déja dans un channel."""
summoned_channel = ctx.message.author.voice_channel
if summoned_channel is None:
await self.bot.say('Are you sure your in a channel?')
return False
state = self.get_voice_state(ctx.message.server)
if state.voice is None:
state.voice = await self.bot.join_voice_channel(summoned_channel)
else:
await state.voice.move_to(summoned_channel)
return True
@commands.command(pass_context=True, no_pm=True)
async def play(self, ctx, *, song : str):
"""Joue une musique.
S'il y a une musique qui joue deja, alors elle est mise dans
la queue jusqu'a la derniere musique de la queue.
Le bot recherche automatiquement sur youtube.
La liste des sites supportés est trouvée ici:
https://rg3.github.io/youtube-dl/supportedsites.html
"""
state = self.get_voice_state(ctx.message.server)
opts = {
'default_search': 'auto',
'quiet': True,
}
if state.voice is None:
success = await ctx.invoke(self.summon)
await self.bot.say("Chargement de la musique...")
if not success:
return
try:
player = await state.voice.create_ytdl_player(song, ytdl_options=opts, after=state.toggle_next)
except Exception as e:
fmt = 'Une erreur est arrivé lors du traitement de la requete: ```py\n{}: {}\n```'
await self.bot.send_message(ctx.message.channel, fmt.format(type(e).__name__, e))
else:
player.volume = 0.6
entry = VoiceEntry(ctx.message, player)
await self.bot.say('La musique ' + str(entry)+" a été mise en queue")
await state.songs.put(entry)
@commands.command(pass_context=True, no_pm=True)
async def volume(self, ctx, value : int):
"""Définie le volume du bot."""
state = self.get_voice_state(ctx.message.server)
if state.is_playing():
player = state.player
player.volume = value / 100
await self.bot.say('Volume mit à {:.0%}'.format(player.volume))
@commands.command(pass_context=True, no_pm=True)
async def resume(self, ctx):
"""Relance la misique jouée."""
state = self.get_voice_state(ctx.message.server)
if state.is_playing():
player = state.player
player.resume()
@commands.command(pass_context=True, no_pm=True)
async def stop(self, ctx):
"""Arrete la musique jouée et quitte le channel.
Cela vide aussi la queue.
"""
server = ctx.message.server
state = self.get_voice_state(server)
if state.is_playing():
player = state.player
player.stop()
try:
state.audio_player.cancel()
del self.voice_states[server.id]
await state.voice.disconnect()
await self.bot.say("Queue vidée et channel quitté. ")
except:
pass
@commands.command(pass_context=True, no_pm=True)
async def skip(self, ctx):
"""Vote pour passer la chanson en cours.
Il faut trois votes pour passer la chanson.
"""
state = self.get_voice_state(ctx.message.server)
if not state.is_playing():
await self.bot.say("Aucune chanson n'est jouée actuellement...")
return
voter = ctx.message.author
if voter == state.current.requester:
await self.bot.say('Une requete pour passer la chanson a été faite.')
state.skip()
elif voter.id not in state.skip_votes:
state.skip_votes.add(voter.id)
total_votes = len(state.skip_votes)
if total_votes >= 3:
await self.bot.say('Vote pour passer effectué,chanson passée...')
state.skip()
else:
await self.bot.say('Vote pour passer effectué, actuellement à [{}/3]'.format(total_votes))
else:
await self.bot.say('Vous avez deja voté pour passer cette chanson.')
@commands.command(pass_context=True, no_pm=True)
async def playing(self, ctx):
"""Montre des informations sur la chanson jouée."""
state = self.get_voice_state(ctx.message.server)
if state.current is None:
await self.bot.say("Rien n'est joué.")
else:
skip_count = len(state.skip_votes)
await self.bot.say('Joue actuellement {} [skips: {}/3]'.format(state.current, skip_count))
def setup(bot):
bot.add_cog(Music(bot))
print('Music is loaded')

View file

@ -13,6 +13,15 @@ sel = ["sel", "salty", "putain"]
troll_symbole = ":troll:232080409083641856"
troll = ["troll", "trol", "trololo"]
dog_symbole = "🐶"
dog = ["waf", "chien", "dog"]
perfect_symbole = "👌"
perfect = ["parfait", "perfect", "ok"]
plus_symbole = ":plus:283940426053058561"
plus = ["+1"]
class Reactionner:
def __init__(self, bot):
self.bot = bot
@ -22,21 +31,36 @@ class Reactionner:
if licorne[i] in message.content.lower():
print("licorne detecter !")
await self.bot.add_reaction(message,licorne_symbole)
for i in range(len(caca)):
if caca[i] in message.content.lower():
print("caca detecter !")
await self.bot.add_reaction(message,caca_symbole )
for i in range(len(sel)):
if sel[i] in message.content.lower():
print("sel detecter !")
await self.bot.add_reaction(message,sel_symbole)
for i in range(len(troll)):
if troll[i] in message.content.lower():
print("troll detecter !")
await self.bot.add_reaction(message,troll_symbole)
for i in range(len(dog)):
if dog[i] in message.content.lower():
print("Chien detecter !")
await self.bot.add_reaction(message,dog_symbole)
for i in range(len(perfect)):
if perfect[i] in message.content.lower():
print("Perfection detecter !")
await self.bot.add_reaction(message,perfect_symbole)
for i in range(len(plus)):
if plus[i] in message.content.lower():
print("Plus detecter !")
await self.bot.add_reaction(message,plus_symbole)
def setup(bot):
bot.add_cog(Reactionner(bot))
bot.add_cog(Reactionner(bot))

6
bot.py
View file

@ -19,6 +19,9 @@ def is_owner(id):
#Démarrage
@bot.event
async def on_ready():
print("Définition du statu de base")
await bot.change_presence(game=discord.Game(name='a se faire toucher le code'))
print("Démarrage de DefaultCMD")
bot.load_extension("DefaultCMD")
@ -34,6 +37,9 @@ async def on_ready():
print("Démarrage de Garou")
bot.load_extension("Garou")
print("Démarrage de Music")
bot.load_extension("Music")
print("FTW's Bot operationelle")
@bot.command(pass_context = True)

BIN
ffmpeg.exe Normal file

Binary file not shown.