Renaming modules, removing useless and changing logic of bot initialization

This commit is contained in:
Rafael Vargas
2022-01-06 18:25:17 -04:00
parent 9c327b8dbf
commit 74d91c15f8
22 changed files with 33 additions and 209 deletions

View File

@@ -0,0 +1,71 @@
import discord
from discord import Client
from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument
from discord.ext import commands
from config import config
class Control(commands.Cog):
"""Control the flow of the Bot"""
def __init__(self, bot: Client):
self.__bot = bot
self.__comandos = {
'MUSIC': ['resume', 'pause', 'loop', 'stop', 'skip', 'play', 'queue', 'clear', 'np', 'shuffle', 'move', 'remove', 'reset'],
'WARFRAME': ['warframe'],
'RANDOM': ['escolha', 'cara', 'random'],
'HELP': ['help'],
'OTHERS': ['frase', 'drop']
}
@commands.Cog.listener()
async def on_ready(self):
print(config.STARTUP_MESSAGE)
await self.__bot.change_presence(status=discord.Status.online, activity=discord.Game(name=f"Vulkan | {config.BOT_PREFIX}help"))
print(config.STARTUP_COMPLETE_MESSAGE)
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, MissingRequiredArgument):
await ctx.channel.send(f'Falta argumentos. Digite {config.BOT_PREFIX}help para ver todos os comandos\n\nOu tente {config.BOT_PREFIX}command help para mais informações')
elif isinstance(error, CommandNotFound):
await ctx.channel.send(f'O comando não existe')
else:
await ctx.channel.send(f'Teve um erro aí bicho')
raise error
@commands.command(name="help", alisases=['ajuda'], help=config.HELP_HELP)
async def help_msg(self, ctx):
helptxt = ''
help_music = '-- MUSIC\n'
help_random = '-- RANDOM\n'
help_warframe = '-- WARFRAME\n'
help_help = '-- HELP\n'
help_others = '-- OTHERS\n'
for command in self.__bot.commands:
if command.name in self.__comandos['MUSIC']:
help_music += f'**{command}** - {command.help}\n'
elif command.name in self.__comandos['HELP']:
help_help += f'**{command}** - {command.help}\n'
elif command.name in self.__comandos['OTHERS']:
help_others += f'**{command}** - {command.help}\n'
elif command.name in self.__comandos['WARFRAME']:
help_warframe += f'**{command}** - {command.help}\n'
else:
help_random += f'**{command}** - {command.help}\n'
helptxt = f'{help_music}\n{help_warframe}\n{help_random}\n{help_others}\n{help_help}'
embedhelp = discord.Embed(
colour=config.COLOURS['grey'],
title=f'Comandos do {self.__bot.user.name}',
description=helptxt
)
embedhelp.set_thumbnail(url=self.__bot.user.avatar_url)
await ctx.send(embed=embedhelp)
def setup(bot):
bot.add_cog(Control(bot))

175
vulkan/commands/Music.py Normal file
View File

@@ -0,0 +1,175 @@
import discord
from discord.ext import commands
from config import config
from vulkan.music.Player import Player
from vulkan.music.utils import *
class Music(commands.Cog):
def __init__(self, bot):
self.__guilds = {}
self.__bot: discord.Client = bot
@commands.command(name="play", help=config.HELP_PLAY, aliases=['p', 'tocar'])
async def play(self, ctx, *args):
user_input = " ".join(args)
player = self.__get_player(ctx)
if player == None:
player = Player(self.__bot, ctx.guild)
self.__guilds[ctx.guild] = player
if is_connected(ctx) == None:
result = await player.connect(ctx)
if result['success'] == False:
await self.__send_embed(ctx, description=result['reason'], colour_name='red')
return
await player.play(ctx, user_input)
@commands.command(name="queue", help=config.HELP_QUEUE, aliases=['q', 'fila'])
async def queue(self, ctx):
player = self.__get_player(ctx)
if player == None:
return
embed = await player.queue()
await ctx.send(embed=embed)
@commands.command(name="skip", help=config.HELP_SKIP, aliases=['pular'])
async def skip(self, ctx):
player = self.__get_player(ctx)
if player == None:
return
else:
await player.skip()
@commands.command(name='stop', help=config.HELP_STOP, aliases=['parar'])
async def stop(self, ctx):
player = self.__get_player(ctx)
if player == None:
return
else:
await player.stop()
@commands.command(name='pause', help=config.HELP_PAUSE, aliases=['pausar'])
async def pause(self, ctx):
player = self.__get_player(ctx)
if player == None:
print('No player')
return
else:
success = await player.pause()
if success:
await self.__send_embed(ctx, description='Song paused', colour_name='blue')
@commands.command(name='resume', help=config.HELP_RESUME, aliases=['soltar'])
async def resume(self, ctx):
player = self.__get_player(ctx)
if player == None:
return
else:
success = await player.resume()
if success:
await self.__send_embed(ctx, description='Song Playing', colour_name='blue')
@commands.command(name='loop', help=config.HELP_LOOP, aliases=['repeat'])
async def loop(self, ctx, args: str):
player = self.__get_player(ctx)
if player == None:
return
else:
result = await player.loop(args)
await self.__send_embed(ctx, description=result, colour_name='blue')
@commands.command(name='clear', help=config.HELP_CLEAR, aliases=['limpar'])
async def clear(self, ctx):
player = self.__get_player(ctx)
if player == None:
return
else:
await player.clear()
@commands.command(name='np', help=config.HELP_NP, aliases=['playing', 'now'])
async def now_playing(self, ctx):
player = self.__get_player(ctx)
if player == None:
return
else:
embed = await player.now_playing()
await self.__clean_messages(ctx)
await ctx.send(embed=embed)
@commands.command(name='shuffle', help=config.HELP_SHUFFLE, aliases=['aleatorio'])
async def shuffle(self, ctx):
player = self.__get_player(ctx)
if player == None:
return
else:
result = await player.shuffle()
await self.__send_embed(ctx, description=result, colour_name='blue')
@commands.command(name='move', help=config.HELP_MOVE, aliases=['mover'])
async def move(self, ctx, pos1, pos2='1'):
player = self.__get_player(ctx)
if player == None:
return
else:
result = await player.move(pos1, pos2)
await self.__send_embed(ctx, description=result, colour_name='blue')
@commands.command(name='remove', help=config.HELP_REMOVE, aliases=['remover'])
async def remove(self, ctx, position):
"""Remove a song from the queue in the position"""
player = self.__get_player(ctx)
if player == None:
return
else:
result = await player.remove(position)
await self.__send_embed(ctx, description=result, colour_name='blue')
@commands.command(name='reset', help=config.HELP_RESET, aliases=['resetar'])
async def reset(self, ctx):
player = self.__get_player(ctx)
if player != None:
await player.stop()
self.__guilds[ctx.guild] = Player(self.__bot, ctx.guild)
async def __send_embed(self, ctx, title='', description='', colour_name='grey'):
try:
colour = config.COLOURS[colour_name]
except Exception as e:
colour = config.COLOURS['grey']
embedvc = discord.Embed(
title=title,
description=description,
colour=colour
)
await ctx.send(embed=embedvc)
async def __clean_messages(self, ctx):
"""Clear Bot messages if send recently"""
last_messages = await ctx.channel.history(limit=5).flatten()
for message in last_messages:
try:
if message.author == self.__bot.user:
if len(message.embeds) > 0:
embed = message.embeds[0]
if embed.title == 'Song Playing Now' or embed.title == 'Song Looping Now':
await message.delete()
except:
continue
def __get_player(self, ctx):
try:
return self.__guilds[ctx.guild]
except:
return None
def setup(bot):
bot.add_cog(Music(bot))

View File

@@ -0,0 +1,59 @@
from discord.client import Client
import requests
import json
from config import config
from discord.ext import commands
from random import random as rand
class Phrases(commands.Cog):
"""Deal with the generation of motivational phrases"""
def __init__(self, bot: Client):
self.__bot = bot
@commands.command(name='frase', help=config.HELP_FRASE)
async def phrase(self, ctx):
"""Send some phrase to the requester"""
secret = await self.__calculate_rgn()
if secret != None:
await ctx.send(secret)
else:
phrase = await self.__get_phrase()
await ctx.send(phrase)
async def __calculate_rgn(self):
"""Calculate the chance from the phrase function return a secret custom message"""
x = rand()
if x < 0.15:
return config.SECRET_MESSAGE
else:
return None
async def __get_phrase(self):
"""Get the phrase from the server"""
tries = 0
while True:
tries += 1
if tries > config.MAX_API_PHRASES_TRIES:
return 'O banco de dados dos cara tá off, bando de vagabundo, tenta depois aí bicho'
try:
response = requests.get(config.PHRASES_API)
data = json.loads(response.content)
phrase = data['quoteText']
author = data['quoteAuthor']
if phrase == '' or author == '':
continue
text = f'{phrase} \nBy: {author}'
return text
except Exception as e:
continue
def setup(bot):
bot.add_cog(Phrases(bot))

80
vulkan/commands/Random.py Normal file
View File

@@ -0,0 +1,80 @@
from random import randint, random
import discord
from discord.ext import commands
from config import config
class Random(commands.Cog):
"""Deal with returning random things"""
def __init__(self, bot):
self.__bot = bot
@commands.command(name='random', help=config.HELP_RANDOM)
async def random(self, ctx, arg: str):
try:
arg = int(arg)
except Exception as e:
embed = discord.Embed(
description='Manda um número aí ow animal',
colour=config.COLOURS['red']
)
await ctx.send(embed=embed)
return
if arg < 1:
a = arg
b = 1
else:
a = 1
b = arg
x = randint(a, b)
embed = discord.Embed(
title=f'Número Aleatório entre {a, b}',
description=x,
colour=config.COLOURS['green']
)
await ctx.send(embed=embed)
@commands.command(name='cara', help=config.HELP_CARA)
async def cara(self, ctx):
x = random()
if x < 0.5:
result = 'cara'
else:
result = 'coroa'
embed = discord.Embed(
title='Cara Cora',
description=f'Resultado: {result}',
colour=config.COLOURS['green']
)
await ctx.send(embed=embed)
@commands.command(name='escolha', help=config.HELP_ESCOLHA)
async def escolher(self, ctx, *args: str):
try:
user_input = " ".join(args)
itens = user_input.split(sep=',')
index = randint(0, len(itens)-1)
embed = discord.Embed(
title='Escolha de algo',
description=itens[index],
colour=config.COLOURS['green']
)
await ctx.send(embed=embed)
except Exception as e:
embed = discord.Embed(
title='Escolha de algo',
description='Erro: Envie várias coisas separadas por vírgula',
colour=config.COLOURS['green']
)
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(Random(bot))

118
vulkan/commands/Warframe.py Normal file
View File

@@ -0,0 +1,118 @@
import requests
import json
import discord
from discord.ext import commands
from config import config
from discord import Embed
class Warframe(commands.Cog):
"""Deal with the generation of warframe data"""
def __init__(self, bot: discord.Client):
self.__bot = bot
self.__open_functions = ['cetus', 'cambion', 'fissures']
@commands.command(name='warframe', help=config.HELP_WARFRAME)
async def warframe(self, ctx, arg) -> Embed:
if arg in self.__open_functions:
function = getattr(Warframe, f'_Warframe__{arg}')
embed = await function(self)
await ctx.send(embed=embed)
else:
info = f'Warframe commands: {self.__open_functions}'
embed = Embed(
title='Invalid Command',
description=info,
colour=config.COLOURS['blue']
)
await ctx.send(embed=embed)
async def __cetus(self) -> Embed:
description = await self.__get_cetus()
embed = discord.Embed(
title='Warframe Cetus Timing',
description=description,
colour=config.COLOURS['blue']
)
return embed
async def __get_cetus(self) -> str:
"""Return the information of the Warframe API"""
tries = 0
while True:
tries += 1
if tries > config.MAX_API_CETUS_TRIES:
return 'Os DE baiano não tão com o banco de dados ligado'
try:
response = requests.get(config.CETUS_API)
data = json.loads(response.content)
short = data['shortString']
return short
except Exception as e:
continue
async def __cambion(self) -> Embed:
description = await self.__get_cambion()
embed = discord.Embed(
title='Warframe Cambion Timing',
description=description,
colour=config.COLOURS['blue']
)
return embed
async def __get_cambion(self) -> str:
"""Return the information of the Warframe API"""
tries = 0
while True:
tries += 1
if tries > config.MAX_API_CAMBION_TRIES:
return 'Os DE baiano não tão com o banco de dados ligado'
try:
response = requests.get(config.CAMBION_API)
data = json.loads(response.content)
info = f'**Active:** {data["active"]}\n**Time Left:** {data["timeLeft"]}'
return info
except:
continue
async def __fissures(self) -> Embed:
description = await self.__get_fissures()
embed = discord.Embed(
title='Warframe Fissures Status',
description=description,
colour=config.COLOURS['blue']
)
return embed
async def __get_fissures(self) -> str:
"""Return the information of the Warframe API"""
tries = 0
while True:
tries += 1
if tries > config.MAX_API_FISSURES_TRIES:
return 'Os DE baiano não tão com o banco de dados ligado'
try:
response = requests.get(config.FISSURES_API)
data = json.loads(response.content)
info = ''
for pos, fissure in enumerate(data, start=1):
info += f'`{pos}` - **Mission:** {fissure["missionType"]} | **Type:** {fissure["tier"]} | **Timing:** {fissure["eta"]} | **Storm:** {fissure["isStorm"]}\n'
return info
except Exception as e:
continue
def setup(bot):
bot.add_cog(Warframe(bot))