insert2-cogs/gameutils.py
2024-08-17 10:41:35 -04:00

183 lines
7.2 KiB
Python

import nextcord
from nextcord.ext import commands, application_checks
from nextcord import TextInputStyle
import random
import aiosqlite as sqlite3
import aiohttp
import traceback
import sys
from urllib.parse import urlparse
import os
class TurnModal(nextcord.ui.Modal):
def __init__(self,message,turnping,fristrun):
self.message = message
self.turnping = turnping
self.fristrun = fristrun
super().__init__(
f"{self.fristrun.name}/{self.fristrun.display_name}" if self.fristrun else f"set turn message/context"
)
self.text = nextcord.ui.TextInput(
label="text",
placeholder="text",
style=TextInputStyle.paragraph,
max_length=1700,
required=False,
)
self.add_item(self.text)
async def callback(self, interaction: nextcord.Interaction) -> None:
if not self.fristrun:
if not interaction.permissions.manage_roles:
await interaction.response.send_message("You don't have permission!", ephemeral=True)
return
await interaction.response.edit_message(content=self.message)
await interaction.followup.send(f"<{self.turnping}> it is now your turn!\n{self.text.value}")
else:
sentmsg = await interaction.response.send_message(self.message, view=GameView(), allowed_mentions=nextcord.AllowedMentions.none())
try:
sentmsg = await sentmsg.fetch()
await sentmsg.pin()
except:
pass
await interaction.followup.send(f"<@{self.fristrun.id}> it is now your turn!\n{self.text.value}")
async def on_error(self, error: nextcord.DiscordException, interaction: nextcord.Interaction):
error = traceback.format_exc()
print(error, file=sys.stderr)
message = f"```py\n{error[-1800:]}\n```\n Contact the bot owner if the error persists"
try:
await interaction.send(message, ephemeral=True)
except:
try:
await interaction.followup.send(message, ephemeral=True)
except:
await interaction.response.send_message(message, ephemeral=True)
class GameView(nextcord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@nextcord.ui.button(
label="Next Turn", style=nextcord.ButtonStyle.green, custom_id="gameutils:nextturn"
)
async def nextturn(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
if not interaction.permissions.manage_roles:
await interaction.response.send_message("You don't have permission!", ephemeral=True)
return
ogmsg = interaction.message.content.split("\n")
turnmessage = ogmsg[0]
ogmsg.pop(0)
message = f"{turnmessage}\n"
found = False
turnover = False
for i in range(len(ogmsg)):
if ogmsg[i].startswith("~"):
message = f"{message}{ogmsg[i]}\n"
continue
if not found:
newmsg = "~~" + ogmsg[i] + "~~"
message = message + newmsg + "\n"
found = True
try:
turnping = ogmsg[i+1].split("<")[1].split(">")[0]
except IndexError:
message = message + "The round is over"
turnover = True
continue
else:
message = message + ogmsg[i] + "\n"
if turnover:
await interaction.response.edit_message(content=message,view=None)
try:
await interaction.message.unpin()
except:
pass
await interaction.followup.send(f"The round has concluded")
else:
await interaction.response.send_modal(TurnModal(message,turnping,False))
return
async def on_error(self, error: nextcord.DiscordException, item: nextcord.ui.Item, interaction: nextcord.Interaction):
error = traceback.format_exc()
print(error, file=sys.stderr)
message = f"```py\n{error[-1800:]}\n```\n Contact the bot owner if the error persists"
try:
await interaction.send(message, ephemeral=True)
except:
try:
await interaction.followup.send(message, ephemeral=True)
except:
await interaction.response.send_message(message, ephemeral=True)
class gameutils(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
#errors if first loaded but is needed after
try:
self.bot.add_view(GameView())
except:
pass
@commands.Cog.listener('on_ready')
async def gameready(self):
self.bot.add_view(GameView())
@nextcord.slash_command(
name="turngen",
description="Roll the next turn for a certian role",
guild_ids=[1247883904178978927,699285282276507708,1059858639088779275],
default_member_permissions=nextcord.Permissions(manage_roles=True),
)
@nextcord.ext.application_checks.has_permissions(manage_roles=True)
async def turngen(self, interaction: nextcord.Interaction, role: nextcord.Role, turnmessage: str, disadvantagerole: nextcord.Role = nextcord.SlashOption(required=False)):
message = f"{turnmessage}\n"
users = role.members
if disadvantagerole:
disusers = disadvantagerole.members
users = list(set(users) - set(disusers))
random.shuffle(users)
for i in range(len(users)):
message = message + f"{str(i+1)}\. <@{users[i].id}>\n"
if disadvantagerole:
random.shuffle(disusers)
for i in range(len(disusers)):
message = message + f"{str(i+1+len(users))}\. <@{disusers[i].id}> **disadventage**\n"
await interaction.response.send_modal(TurnModal(message,None,users[0]))
#await interaction.followup.send(f"<@{users[0].id}> it is now your turn!")
@nextcord.slash_command(
name="dice",
description="Roll a number of dice",
#guild_ids=[1247883904178978927,699285282276507708],
integration_types=[
nextcord.IntegrationType.guild_install,
nextcord.IntegrationType.user_install,
],
contexts=[
nextcord.InteractionContextType.guild,
nextcord.InteractionContextType.bot_dm,
nextcord.InteractionContextType.private_channel,
],
force_global=True,
)
async def diceroll(self, interaction: nextcord.Interaction, number: int, sides: int, hidden: str = nextcord.SlashOption(choices=["Yes", "No"])):
message = f"May the odds ever be in your favor...\n"
fullnum = 0
for d in range(number):
num = random.randint(1, sides)
fullnum = fullnum + num
message = message + f":game_die: {str(d+1)}. {str(num)}\n"
message = message + f"sum: {fullnum}"
if hidden == "Yes":
await interaction.response.send_message(message, ephemeral=True)
else:
await interaction.response.send_message(message, ephemeral=False)
def setup(bot: commands.Bot):
bot.add_cog(gameutils(bot))