Fully converted to slash commands

This commit is contained in:
NikolajDanger
2021-03-31 00:38:51 +02:00
parent a8a7e5eabd
commit b345720468
50 changed files with 1102 additions and 1111 deletions

View File

@ -1,28 +1,29 @@
import discord, traceback
from discord.ext import commands
class EventCog(commands.cog):
def __init__(bot):
class EventCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
# Sets the game and logs when the bot logs in
@client.event
async def on_ready():
logThis("Logged in as "+client.user.name+", "+str(client.user.id))
game = discord.Game("Some weeb shit")
await client.change_presence(activity=game)
@commands.Cog.listener()
async def on_ready(self):
self.bot.log("Logged in as "+self.bot.user.name+", "+str(self.bot.user.id))
game = discord.Game("Use /help for commands")
await self.bot.change_presence(activity=game)
# Logs when user sends a command
@client.event
async def on_slash_command(ctx):
logThis(f"{ctx.author.display_name} ran {ctx.name}")
@commands.Cog.listener()
async def on_slash_command(self, ctx):
self.bot.log(f"{ctx.author.display_name} ran /{ctx.name}")
# Logs if a command experiences an error
@client.event
async def on_slash_command_error(ctx, error):
@commands.Cog.listener()
async def on_slash_command_error(self, ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send("That's not a command (error code 001)")
elif isinstance(error,commands.errors.MissingRequiredArgument):
logThis(f"{error}",str(ctx.channel_id))
self.bot.log(f"{error}",str(ctx.channel_id))
await ctx.send("Missing command parameters (error code 002). Try using `!help [command]` to find out how to use the command.")
else:
exception = traceback.format_exception(type(error), error, error.__traceback__)
@ -32,5 +33,8 @@ class EventCog(commands.cog):
exception = exception[:index]
exceptionString = "".join(exception)
logThis([f"exception in {ctx.name} command", f"{exceptionString}"],str(ctx.channel_id), 40)
await ctx.send("Something went wrong (error code 000)")
self.bot.log([f"exception in /{ctx.name}", f"{exceptionString}"],str(ctx.channel_id), 40)
await ctx.send("Something went wrong (error code 000)")
def setup(bot):
bot.add_cog(EventCog(bot))

View File

@ -3,20 +3,11 @@ from discord.ext import commands
from discord_slash import cog_ext
from discord_slash import SlashCommandOptionType as scot
from funcs import logThis
from utils import Options
from utils import getParams
with open("resources/slashParameters.json", "r") as f:
params = json.load(f)
options = Options()
if options.testing:
for p in params:
params[p]["guild_ids"] = options.guildIds
params = getParams()
class GamesCog(commands.Cog):
def __init__(self,bot):
"""Runs game stuff."""
self.bot = bot
@ -39,7 +30,7 @@ class GamesCog(commands.Cog):
commands = parameters.split(" ")
amount = int(commands[-1])
username = " ".join(commands[:-1])
if self.bot.funcs.getID(username) == None:
if self.bot.databaseFuncs.getID(username) == None:
async for member in ctx.guild.fetch_members(limit=None):
if member.display_name.lower() == username.lower():
username = member.display_name
@ -52,7 +43,7 @@ class GamesCog(commands.Cog):
@cog_ext.cog_slash(**params["invest"])
async def invest(self, ctx, parameters = "check"):
await ctx.defer()
response = self.bot.invest.parseInvest(parameters,"#"+str(ctx.author.id))
response = self.bot.games.invest.parseInvest(parameters,"#"+str(ctx.author.id))
if response.startswith("**"):
responses = response.split("\n")
em = discord.Embed(title=responses[0],description="\n".join(responses[1:]),colour=0x00FF00)
@ -65,7 +56,7 @@ class GamesCog(commands.Cog):
async def trivia(self, ctx, answer = ""):
await ctx.defer()
if answer == "":
question, options, correctAnswer = self.bot.trivia.triviaStart(str(ctx.channel_id))
question, options, correctAnswer = self.bot.games.trivia.triviaStart(str(ctx.channel_id))
if options != "":
results = "**"+question+"**\n"
for x, option in enumerate(options):
@ -75,95 +66,135 @@ class GamesCog(commands.Cog):
await asyncio.sleep(60)
self.bot.trivia.triviaCountPoints(str(ctx.channel_id))
self.bot.games.trivia.triviaCountPoints(str(ctx.channel_id))
self.bot.funcs.deleteGame("trivia questions",str(ctx.channel_id))
self.bot.databaseFuncs.deleteGame("trivia questions",str(ctx.channel_id))
logThis("Time's up for the trivia question",str(ctx.channel_id))
self.bot.log("Time's up for the trivia question",str(ctx.channel_id))
await ctx.send("Time's up The answer was \""+chr(correctAnswer)+") "+options[correctAnswer-97]+"\". Anyone who answered that has gotten 1 GwendoBuck")
else:
await ctx.send(question, hidden=True)
elif answer in ["a","b","c","d"]:
response = self.bot.trivia.triviaAnswer("#"+str(ctx.author.id),str(ctx.channel_id),answer)
response = self.bot.games.trivia.triviaAnswer("#"+str(ctx.author.id),str(ctx.channel_id),answer)
if response.startswith("Locked in "):
await ctx.send(f"{ctx.author.display_name} answered {answer}")
else:
await ctx.send(response)
else:
logThis("I didn't understand that (error code 1101)",str(ctx.channel_id))
self.bot.log("I didn't understand that (error code 1101)",str(ctx.channel_id))
await ctx.send("I didn't understand that (error code 1101)")
# Runs a game of blackjack
@cog_ext.cog_slash(**params["blackjack"])
async def blackjack(self, ctx, parameters = ""):
await ctx.defer()
await self.bot.blackjack.parseBlackjack(parameters, ctx)
class BlackjackCog(commands.Cog):
def __init__(self,bot):
"""Runs game stuff."""
self.bot = bot
# Starts a game of blackjack
@cog_ext.cog_subcommand(**params["blackjackStart"])
async def blackjackStart(self, ctx):
await ctx.defer()
await self.bot.games.blackjack.parseBlackjack("", ctx)
@cog_ext.cog_subcommand(**params["blackjackBet"])
async def blackjackBet(self, ctx, bet):
await ctx.defer()
await self.bot.games.blackjack.parseBlackjack(f"bet {bet}", ctx)
@cog_ext.cog_subcommand(**params["blackjackStand"])
async def blackjackStand(self, ctx, hand = ""):
await ctx.defer()
await self.bot.games.blackjack.parseBlackjack(f"stand {hand}", ctx)
@cog_ext.cog_subcommand(**params["blackjackHit"])
async def blackjackHit(self, ctx, hand = ""):
await ctx.defer()
await self.bot.games.blackjack.parseBlackjack(f"hit {hand}", ctx)
class ConnectFourCog(commands.Cog):
def __init__(self,bot):
"""Runs game stuff."""
self.bot = bot
# Start a game of connect four against a user
@cog_ext.cog_subcommand(**params["connectFourStartUser"])
async def connectFourStartUser(self, ctx, user):
await ctx.defer()
await self.bot.gameLoops.connectFour(ctx, "start "+user.display_name)
await self.bot.games.gameLoops.connectFour(ctx, "start "+user.display_name)
# Start a game of connect four against gwendolyn
@cog_ext.cog_subcommand(**params["connectFourStartGwendolyn"])
async def connectFourStartGwendolyn(self, ctx, difficulty = 3):
await ctx.defer()
await self.bot.gameLoops.connectFour(ctx, "start "+str(difficulty))
await self.bot.games.gameLoops.connectFour(ctx, "start "+str(difficulty))
# Stop the current game of connect four
@cog_ext.cog_subcommand(**params["connectFourStop"])
async def connectFourStop(self, ctx):
await self.bot.gameLoops.connectFour(ctx, "stop")
await self.bot.games.gameLoops.connectFour(ctx, "stop")
# Place a piece in the current game of connect four
@cog_ext.cog_subcommand(**params["connectFourPlace"])
async def connectFourPlace(self, ctx, column):
await self.bot.gameLoops.connectFour(ctx, "place "+str(column))
await self.bot.games.gameLoops.connectFour(ctx, "place "+str(column))
class HangmanCog(commands.Cog):
def __init__(self,bot):
"""Runs game stuff."""
self.bot = bot
# Starts a game of Hangman
@cog_ext.cog_subcommand(**params["hangmanStart"])
async def hangmanStart(self, ctx):
await ctx.defer()
await self.bot.gameLoops.runHangman(ctx.channel,"#"+str(ctx.author.id),"start", ctx)
await self.bot.games.gameLoops.runHangman(ctx.channel,"#"+str(ctx.author.id),"start", ctx)
# Stops a game of Hangman
@cog_ext.cog_subcommand(**params["hangmanStop"])
async def hangmanStop(self, ctx):
await self.bot.gameLoops.runHangman(ctx.channel,"#"+str(ctx.author.id),"stop", ctx)
await self.bot.games.gameLoops.runHangman(ctx.channel,"#"+str(ctx.author.id),"stop", ctx)
class HexCog(commands.Cog):
def __init__(self,bot):
"""Runs game stuff."""
self.bot = bot
# Start a game of Hex against another user
@cog_ext.cog_subcommand(**params["hexStartUser"])
async def hexStartUser(self, ctx, user):
await ctx.defer()
await self.bot.gameLoops.runHex(ctx, "start "+user.display_name, "#"+str(ctx.author.id))
await self.bot.games.gameLoops.runHex(ctx, "start "+user.display_name, "#"+str(ctx.author.id))
# Start a game of Hex against Gwendolyn
@cog_ext.cog_subcommand(**params["hexStartGwendolyn"])
async def hexStartGwendolyn(self, ctx, difficulty = 2):
await ctx.defer()
await self.bot.gameLoops.runHex(ctx, "start "+str(difficulty), "#"+str(ctx.author.id))
await self.bot.games.gameLoops.runHex(ctx, "start "+str(difficulty), "#"+str(ctx.author.id))
# Undo your last hex move
@cog_ext.cog_subcommand(**params["hexUndo"])
async def hexUndo(self, ctx):
await self.bot.gameLoops.runHex(ctx, "undo", "#"+str(ctx.author.id))
await self.bot.games.gameLoops.runHex(ctx, "undo", "#"+str(ctx.author.id))
# Perform a hex swap
@cog_ext.cog_subcommand(**params["hexSwap"])
async def hexSwap(self, ctx):
await self.bot.gameLoops.runHex(ctx, "swap", "#"+str(ctx.author.id))
await self.bot.games.gameLoops.runHex(ctx, "swap", "#"+str(ctx.author.id))
# Surrender the hex game
@cog_ext.cog_subcommand(**params["hexSurrender"])
async def hexSurrender(self, ctx):
await self.bot.gameLoops.runHex(ctx, "surrender", "#"+str(ctx.author.id))
await self.bot.games.gameLoops.runHex(ctx, "surrender", "#"+str(ctx.author.id))
# Place a piece in the hex game
@cog_ext.cog_subcommand(**params["hexPlace"])
async def hexPlace(self, ctx, coordinates):
await self.bot.gameLoops.runHex(ctx, "place "+coordinates, "#"+str(ctx.author.id))
await self.bot.games.gameLoops.runHex(ctx, "place "+coordinates, "#"+str(ctx.author.id))
def setup(bot):
bot.add_cog(GamesCog(bot))
bot.add_cog(GamesCog(bot))
bot.add_cog(BlackjackCog(bot))
bot.add_cog(ConnectFourCog(bot))
bot.add_cog(HangmanCog(bot))
bot.add_cog(HexCog(bot))

View File

@ -3,28 +3,19 @@ from discord.ext import commands
from discord_slash import cog_ext
from discord_slash import SlashCommandOptionType as scot
from funcs import spellFunc, monsterFunc, cap
from utils import Options
from utils import getParams, cap
with open("resources/slashParameters.json", "r") as f:
params = json.load(f)
options = Options()
if options.testing:
for p in params:
params[p]["guild_ids"] = options.guildIds
params = getParams()
class LookupCog(commands.Cog):
def __init__(self,client):
def __init__(self, bot):
"""Runs lookup commands."""
self.client = client
self.bot = bot
# Looks up a spell
@cog_ext.cog_slash(**params["spell"])
async def spell(self, ctx, query):
spell = spellFunc(cap(query))
spell = self.bot.lookupFuncs.spellFunc(cap(query))
if len(spell) > 2000:
await ctx.send(spell[:2000])
await ctx.send(spell[2000:])
@ -34,7 +25,7 @@ class LookupCog(commands.Cog):
# Looks up a monster
@cog_ext.cog_slash(**params["monster"])
async def monster(self, ctx, query):
title, text1, text2, text3, text4, text5 = monsterFunc(cap(query))
title, text1, text2, text3, text4, text5 = self.bot.lookupFuncs.monsterFunc(cap(query))
em1 = discord.Embed(title = title, description = text1, colour=0xDEADBF)
# Sends the received information. Separates into separate messages if
@ -77,5 +68,5 @@ class LookupCog(commands.Cog):
em5_2 = discord.Embed(title = "", description = text5[2048:], colour=0xDEADBF)
await ctx.send(embed = em5_2)
def setup(client):
client.add_cog(LookupCog(client))
def setup(bot):
bot.add_cog(LookupCog(bot))

View File

@ -2,7 +2,6 @@ import discord, codecs, string, json
from discord.ext import commands
from discord_slash import cog_ext
from funcs import logThis, helloFunc, roll_dice, imageFunc, movieFunc, cap, findWikiPage
from utils import Options
with open("resources/slashParameters.json", "r") as f:
@ -15,31 +14,31 @@ if options.testing:
params[p]["guild_ids"] = options.guildIds
class MiscCog(commands.Cog):
def __init__(self,client):
def __init__(self, bot):
"""Runs misc commands."""
self.client = client
self.client.remove_command("help")
self.generator = client.generator
self.bedreNetflix = client.bedreNetflix
self.nerdShit = client.nerdShit
self.bot = bot
self.bot.remove_command("help")
self.generators = bot.other.generators
self.bedreNetflix = bot.other.bedreNetflix
self.nerdShit = bot.other.nerdShit
# Sends the bot's latency
@cog_ext.cog_slash(**params["ping"])
async def ping(self, ctx):
await ctx.send(f"Pong!\nLatency is {round(self.client.latency * 1000)}ms")
await ctx.send(f"Pong!\nLatency is {round(self.bot.latency * 1000)}ms")
# Restarts the bot
@cog_ext.cog_slash(**params["stop"])
async def stop(self, ctx):
if "#"+str(ctx.author.id) in self.client.options.admins:
if "#"+str(ctx.author.id) in self.bot.options.admins:
await ctx.send("Pulling git repo and restarting...")
self.client.funcs.stopServer()
self.bot.databaseFuncs.stopServer()
logThis("Logging out.")
await self.client.logout()
self.bot.log("Logging out.")
await self.bot.logout()
else:
logThis(f"{ctx.author.display_name} tried to stop me! (error code 201)",str(ctx.channel_id))
self.bot.log(f"{ctx.author.display_name} tried to stop me! (error code 201)",str(ctx.channel_id))
await ctx.send(f"I don't think I will, {ctx.author.display_name} (error code 201)")
# Gets help for specific command
@ -51,13 +50,13 @@ class MiscCog(commands.Cog):
em = discord.Embed(title = "Help", description = text,colour = 0x59f442)
await ctx.send(embed = em)
else:
logThis(f"Looking for help-{command}.txt",str(ctx.channel_id))
self.bot.log(f"Looking for help-{command}.txt",str(ctx.channel_id))
with codecs.open(f"resources/help/help-{command}.txt",encoding="utf-8") as f:
text = f.read()
em = discord.Embed(title = command.capitalize(), description = text,colour = 0x59f442)
await ctx.send(embed = em)
# Let's you thank the bot
# Lets you thank the bot
@cog_ext.cog_slash(**params["thank"])
async def thank(self, ctx):
await ctx.send("You're welcome :blush:")
@ -65,61 +64,42 @@ class MiscCog(commands.Cog):
# Sends a friendly message
@cog_ext.cog_slash(**params["hello"])
async def hello(self, ctx):
await ctx.send(helloFunc(ctx.author.display_name))
await ctx.send(self.bot.other.helloFunc(ctx.author.display_name))
# Rolls dice
@cog_ext.cog_slash(**params["roll"])
async def roll(self, ctx, dice = "1d20"):
await ctx.send(roll_dice(ctx.author.display_name,dice))
await ctx.send(self.bot.other.rollDice(ctx.author.display_name, dice))
# Sends a random image
@cog_ext.cog_slash(**params["image"])
async def image(self, ctx):
randomImage = imageFunc()
await ctx.send(randomImage)
await ctx.defer()
await ctx.send(self.bot.other.imageFunc())
# Finds a random movie
@cog_ext.cog_slash(**params["movie"])
async def movie(self,ctx):
await ctx.defer()
title, plot, cover, cast = movieFunc()
if title == "error":
await ctx.send("An error occurred. Try again (error code "+plot+")")
else:
try:
embed = discord.Embed(title=title, description=plot, color=0x24ec19)
embed.set_thumbnail(url=cover)
embed.add_field(name="Cast", value=cast,inline = True)
await ctx.send(embed = embed)
except:
logThis("Error embedding (error code 805)")
await self.bot.other.movieFunc(ctx)
# Generates a random name
@cog_ext.cog_slash(**params["name"])
async def name(self, ctx):
await ctx.send(self.generator.nameGen())
await ctx.send(self.generators.nameGen())
# Generates a random tavern name
@cog_ext.cog_slash(**params["tavern"])
async def tavern(self, ctx):
await ctx.send(self.generator.tavernGen())
# Sets the game Gwendolyn's playing
@cog_ext.cog_slash(**params["game"])
async def game(self, ctx, gameText):
gamePlaying = cap(gameText)
game = discord.Game(gamePlaying)
await self.client.change_presence(activity=game)
await ctx.send(f"Setting game to \"{gamePlaying}\"")
await ctx.send(self.generators.tavernGen())
# Finds a page on the Senkulpa wiki
@cog_ext.cog_slash(**params["wiki"])
async def wiki(self, ctx, wikiPage):
await ctx.defer()
command = string.capwords(wikiPage)
title, content, thumbnail = findWikiPage(command)
title, content, thumbnail = self.bot.otherfindWikiPage(command)
if title != "":
logThis("Sending the embedded message",str(ctx.channel_id))
self.bot.log("Sending the embedded message",str(ctx.channel_id))
content += "\n[Læs mere](https://senkulpa.fandom.com/da/wiki/"+title.replace(" ","_")+")"
embed = discord.Embed(title = title, description = content, colour=0xDEADBF)
if thumbnail != "":
@ -152,5 +132,5 @@ class MiscCog(commands.Cog):
async def wolf(self, ctx, query):
await self.nerdShit.wolfSearch(ctx, query)
def setup(client):
client.add_cog(MiscCog(client))
def setup(bot):
bot.add_cog(MiscCog(bot))

View File

@ -1,28 +1,28 @@
from discord.ext import commands
from funcs import logThis, emojiToCommand
from utils import emojiToCommand
class ReactionCog(commands.Cog):
def __init__(self, client):
def __init__(self, bot):
"""Listens for reactions."""
self.client = client
self.bot = bot
@commands.Cog.listener()
async def on_reaction_add(self, reaction,user):
async def on_reaction_add(self, reaction, user):
if user.bot == False:
message = reaction.message
channel = message.channel
logThis(user.display_name+" reacted to a message",str(channel.id))
self.bot.log(f"{user.display_name} reacted to a message",str(channel.id), level = 10)
try:
connectFourTheirTurn, piece = self.client.funcs.connectFourReactionTest(channel,message,"#"+str(user.id))
connectFourTheirTurn, piece = self.bot.databaseFuncs.connectFourReactionTest(channel,message,"#"+str(user.id))
except:
connectFourTheirTurn = False
bedreNetflixMessage, addMovie, imdbIds = self.client.funcs.bedreNetflixReactionTest(channel,message)
bedreNetflixMessage, addMovie, imdbIds = self.bot.databaseFuncs.bedreNetflixReactionTest(channel, message)
if connectFourTheirTurn:
place = emojiToCommand(reaction.emoji)
await self.client.gameLoops.connectFour(message,"place "+str(piece)+" "+str(place),user.id, str(message.channel.id))
await self.bot.games.gameLoops.connectFour(message,"place "+str(piece)+" "+str(place),user.id, str(message.channel.id))
elif bedreNetflixMessage and addMovie:
moviePick = emojiToCommand(reaction.emoji)
await message.delete()
@ -30,7 +30,7 @@ class ReactionCog(commands.Cog):
imdbID = None
else:
imdbID = imdbIds[moviePick-1]
await self.client.bedreNetflix.addMovie(channel,imdbID)
await self.bot.other.bedreNetflix.addMovie(channel,imdbID)
elif bedreNetflixMessage and not addMovie:
showPick = emojiToCommand(reaction.emoji)
await message.delete()
@ -38,9 +38,9 @@ class ReactionCog(commands.Cog):
imdbName = None
else:
imdbName = imdbIds[showPick-1]
await self.client.bedreNetflix.addShow(channel,imdbName)
elif self.client.funcs.hangmanReactionTest(channel,message) and ord(reaction.emoji) in range(127462,127488):
await self.bot.other.bedreNetflix.addShow(channel,imdbName)
elif self.bot.databaseFuncs.hangmanReactionTest(channel,message) and ord(reaction.emoji) in range(127462,127488):
guess = chr(ord(reaction.emoji)-127397)
await self.client.gameLoops.runHangman(channel,"#"+str(user.id),command="guess "+guess)
def setup(client):
client.add_cog(ReactionCog(client))
await self.bot.games.gameLoops.runHangman(channel,"#"+str(user.id),command="guess "+guess)
def setup(bot):
bot.add_cog(ReactionCog(bot))

View File

@ -2,8 +2,7 @@ import discord, string, json
from discord.ext import commands
from discord_slash import cog_ext
from funcs import cap
from utils import Options
from utils import Options, cap
with open("resources/slashParameters.json", "r") as f:
params = json.load(f)
@ -14,17 +13,17 @@ if options.testing:
for p in params:
params[p]["guild_ids"] = options.guildIds
class SwCog(commands.Cog):
class starWarsCog(commands.Cog):
def __init__(self,client):
def __init__(self, bot):
"""Runs star wars commands."""
self.client = client
self.bot = bot
# Rolls star wars dice
@cog_ext.cog_slash(**params["starWarsRoll"])
async def starWarsRoll(self, ctx, dice = ""):
command = cap(dice)
newMessage = self.client.swroll.parseRoll("#"+str(ctx.author.id),command)
newMessage = self.bot.starWars.roll.parseRoll("#"+str(ctx.author.id),command)
messageList = newMessage.split("\n")
await ctx.send(messageList[0])
if len(messageList) > 1:
@ -34,7 +33,7 @@ class SwCog(commands.Cog):
# Controls destiny points
@cog_ext.cog_slash(**params["starWarsDestiny"])
async def starWarsDestiny(self, ctx, parameters = ""):
newMessage = self.client.swdestiny.parseDestiny("#"+str(ctx.author.id),parameters)
newMessage = self.bot.starWars.destiny.parseDestiny("#"+str(ctx.author.id),parameters)
messageList = newMessage.split("\n")
await ctx.send(messageList[0])
if len(messageList) > 1:
@ -44,7 +43,7 @@ class SwCog(commands.Cog):
# Rolls for critical injuries
@cog_ext.cog_slash(**params["starWarsCrit"])
async def starWarsCrit(self, ctx, severity : int = 0):
newMessage = self.client.swroll.critRoll(int(severity))
newMessage = self.bot.starWars.roll.critRoll(int(severity))
messageList = newMessage.split("\n")
await ctx.send(messageList[0])
@ -53,16 +52,16 @@ class SwCog(commands.Cog):
await ctx.channel.send(messageItem)
# Accesses and changes character sheet data with the parseChar function
# from funcs/swfuncs/swchar.py
# from funcs/starWarsFuncs/starWarsCharacter.py
@cog_ext.cog_slash(**params["starWarsCharacter"])
async def starWarsCharacter(self, ctx, parameters = ""):
command = string.capwords(parameters.replace("+","+ ").replace("-","- ").replace(",",", "))
title, desc = self.client.swchar.parseChar("#"+str(ctx.author.id),command)
title, desc = self.bot.starWars.character.parseChar("#"+str(ctx.author.id),command)
if title != "":
em1 = discord.Embed(title = title, description = desc, colour=0xDEADBF)
await ctx.send(embed = em1)
else:
await ctx.send(desc)
def setup(client):
client.add_cog(SwCog(client))
def setup(bot):
bot.add_cog(starWarsCog(bot))