Skip to content

Commit

Permalink
Cleanup and fix some code, start improving kasino betting experience
Browse files Browse the repository at this point in the history
  • Loading branch information
jackra1n committed Dec 10, 2023
1 parent 1f6516d commit 4c15ed9
Show file tree
Hide file tree
Showing 4 changed files with 115 additions and 128 deletions.
172 changes: 101 additions & 71 deletions bot/cogs/karma.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from core import values
from core.bot import Substiify
from discord import app_commands
from discord import ButtonStyle, Interaction, ui
from discord.ext import commands

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -73,7 +74,7 @@ async def list_votes(self, ctx: commands.Context):
@app_commands.describe(
channel="The channel to enable votes in"
)
async def start(self, ctx: commands.Context, channel: discord.TextChannel = None):
async def start(self, ctx: commands.Context, channel: discord.abc.GuildChannel = None):
"""
Enables votes in the current or specified channel. Requires Manage Channels permission.
After enabling votes, the bot will add the upvote and downvote reactions to every message in the channel.
Expand All @@ -90,7 +91,7 @@ async def start(self, ctx: commands.Context, channel: discord.TextChannel = None
if not votes_enabled:
stmt = '''INSERT INTO discord_channel (discord_channel_id, channel_name, discord_server_id, parent_discord_channel_id, upvote)
VALUES ($1, $2, $3, $4, $5) ON CONFLICT (discord_channel_id) DO UPDATE SET upvote = $5'''
await self.bot.db.execute(stmt, channel.id, channel.name, channel.guild.id, channel.category_id, True)
await self.bot.db.execute(stmt, channel.id, channel.name, channel.guild.id, None, True)
else:
embed = discord.Embed(
description=f'Votes are **already active** in {ctx.channel.mention}!',
Expand All @@ -117,7 +118,7 @@ async def stop(self, ctx: commands.Context, channel: discord.TextChannel = None)
channel = channel or ctx.channel
stmt = '''INSERT INTO discord_channel (discord_channel_id, channel_name, discord_server_id, parent_discord_channel_id, upvote)
VALUES ($1, $2, $3, $4, $5) ON CONFLICT (discord_channel_id) DO UPDATE SET upvote = $5'''
await self.bot.db.execute(stmt, channel.id, channel.name, channel.guild.id, channel.category_id, False)
await self.bot.db.execute(stmt, channel.id, channel.name, channel.guild.id, None, False)

if channel.id in self.vote_channels:
self.vote_channels.remove(channel.id)
Expand Down Expand Up @@ -570,74 +571,6 @@ async def kasino_lock(self, ctx: commands.Context, kasino_id: int):
await self.update_kasino_msg(ctx, kasino_id)
await ctx.message.delete()

@kasino.command(name='bet', usage="bet <kasino_id> <amount> <option>")
@app_commands.describe(
kasino_id="The ID of the kasino you want to bet on. The ID should be visible in the kasino message.",
amount="The amount of karma you want to bet. `all` to bet all your karma.",
option="The option you want to bet on. 1 or 2."
)
async def kasino_bet(self, ctx: commands.Context, kasino_id: int, amount: str, option: int):
output_embed = discord.Embed(color=discord.Colour.from_rgb(209, 25, 25))

if option not in [1, 2]:
output_embed.title=f'Wrong usage. Correct usage is `{ctx.prefix}kasino bet <kasino_id> <amount> <1 or 2>`'
return await ctx.author.send(embed=output_embed, delete_after=30)

if amount != 'all':
try:
amount = int(amount)
except ValueError:
output_embed.title=f'Wrong usage. Correct usage is `{ctx.prefix}kasino bet <kasino_id> <amount> <1 or 2>`'
return await ctx.author.send(embed=output_embed, delete_after=30)
if amount < 1:
output_embed.title='You tried to bet < 1 karma! Silly you!'
return await ctx.author.send(embed=output_embed, delete_after=30)

kasino = await self.bot.db.fetchrow('SELECT * FROM kasino WHERE id = $1', kasino_id)

if kasino is None:
output_embed.title=f'Kasino with ID {kasino_id} is not open.'
return await ctx.author.send(embed=output_embed, delete_after=30)

if kasino['locked']:
output_embed.title=f'kasino with ID {kasino_id} is locked.'
return await ctx.author.send(embed=output_embed, delete_after=30)

bettor_karma = await self._get_user_karma(ctx.author.id, ctx.guild.id)
if bettor_karma is None:
return await ctx.send('You do not have any karma.')

amount = bettor_karma if amount == "all" else amount

if bettor_karma < amount:
output_embed.title=f'You don\'t have that much karma. Your karma: {bettor_karma}'
return await ctx.author.send(embed=output_embed, delete_after=30)

total_bet = amount
output = 'added'

stmt_bet = 'SELECT * FROM kasino_bet WHERE kasino_id = $1 AND discord_user_id = $2;'
user_bet = await self.bot.db.fetchrow(stmt_bet, kasino_id, ctx.author.id)
if user_bet is not None:
if user_bet['option'] != option:
output_embed.title = f'You can\'t change your choice on the bet with id {kasino_id}. No chickening out!'
return await ctx.author.send(embed=output_embed)
total_bet = user_bet['amount'] + amount
output = 'increased'
stmt_bet = '''INSERT INTO kasino_bet (kasino_id, discord_user_id, amount, option) VALUES ($1, $2, $3, $4)
ON CONFLICT (kasino_id, discord_user_id) DO UPDATE SET amount = kasino_bet.amount + $3;
UPDATE user_karma SET karma = user_karma.karma - $3 WHERE discord_user_id = $2 AND discord_server_id = $5;'''
await self.bot.db.execute(stmt_bet, kasino_id, ctx.author.id, amount, option, ctx.guild.id)

output_embed.title = f'**Successfully {output} bet on option {option}, on kasino with ID {kasino_id} for {amount} karma! Total bet is now: {total_bet} Karma**'
output_embed.color = discord.Colour.from_rgb(52, 79, 235)
output_embed.description = f'Remaining karma: {bettor_karma - amount}'

await self.update_kasino_msg(ctx, kasino_id)
await ctx.author.send(embed=output_embed)
await ctx.send(f"Bet added from {ctx.author}!", delete_after=30)
await ctx.message.delete()

@kasino.command(name='list', aliases=['l'], usage="list")
async def kasino_list(self, ctx: commands.Context):
embed = discord.Embed(title='Open kasinos')
Expand Down Expand Up @@ -940,6 +873,103 @@ async def update_kasino_msg(self, ctx: commands.Context, kasino_id: int) -> None

await kasino_msg.edit(embed=to_embed)

class KasinoView(ui.View):
def __init__(self, ctx: commands.Context, kasino: Record):
super().__init__(timeout=None)
self.ctx = ctx
self.kasino = kasino


class KasinoBetButton(ui.Button):
def __init__(self, ctx: commands.Context, kasino: Record):
gamba_emoji = discord.PartialEmoji.from_str('karmabet:817354842699857920')
super().__init__(label='Bet', emoji=gamba_emoji, style=discord.ButtonStyle.green)
self.ctx = ctx
self.kasino = kasino

async def callback(self, interaction: discord.Interaction):
await interaction.response.send_modal(KasinoBetModal(self.ctx, self.kasino))


class KasinoBetModal(discord.ui.Modal):
def __init__(self, ctx: commands.Context, kasino: Record):
super().__init__(title=kasino['question'])
self.ctx = ctx
self.kasino = kasino
self.bet_option_select = discord.ui.Select(
placeholder='Select option',
options=[
discord.SelectOption(label=kasino['option_1'], value='1'),
discord.SelectOption(label=kasino['option_2'], value='2')
]
)
self.bet_amount_input = discord.ui.TextInput(
label='Bet amount',
style=discord.TextStyle.short,
placeholder='100',
required=True
)
self.add_item(self.bet_option_select)
self.add_item(self.bet_amount_input)


async def on_submit(self, interaction: discord.Interaction) -> None:
amount = self.bet_amount_input.value
if amount != 'all':
try:
amount = int(amount)
except ValueError:
return await interaction.response.send_message('Invalid amount', ephemeral=True)
if amount < 1:
return await interaction.response.send_message('You tried to bet < 1 karma! Silly you!', ephemeral=True)

kasino = await self.bot.db.fetchrow('SELECT * FROM kasino WHERE id = $1', kasino_id)

if kasino is None:
output_embed.title=f'Kasino with ID {kasino_id} is not open.'
return await ctx.author.send(embed=output_embed, delete_after=30)

if kasino['locked']:
output_embed.title=f'kasino with ID {kasino_id} is locked.'
return await ctx.author.send(embed=output_embed, delete_after=30)

bettor_karma = await self._get_user_karma(ctx.author.id, ctx.guild.id)
if bettor_karma is None:
return await ctx.send('You do not have any karma.')

amount = bettor_karma if amount == "all" else amount

if bettor_karma < amount:
output_embed.title=f'You don\'t have that much karma. Your karma: {bettor_karma}'
return await ctx.author.send(embed=output_embed, delete_after=30)

total_bet = amount
output = 'added'

stmt_bet = 'SELECT * FROM kasino_bet WHERE kasino_id = $1 AND discord_user_id = $2;'
user_bet = await self.bot.db.fetchrow(stmt_bet, kasino_id, ctx.author.id)
if user_bet is not None:
if user_bet['option'] != option:
output_embed.title = f'You can\'t change your choice on the bet with id {kasino_id}. No chickening out!'
return await ctx.author.send(embed=output_embed)
total_bet = user_bet['amount'] + amount
output = 'increased'
stmt_bet = '''INSERT INTO kasino_bet (kasino_id, discord_user_id, amount, option) VALUES ($1, $2, $3, $4)
ON CONFLICT (kasino_id, discord_user_id) DO UPDATE SET amount = kasino_bet.amount + $3;
UPDATE user_karma SET karma = user_karma.karma - $3 WHERE discord_user_id = $2 AND discord_server_id = $5;'''
await self.bot.db.execute(stmt_bet, kasino_id, ctx.author.id, amount, option, ctx.guild.id)

output_embed.title = f'**Successfully {output} bet on option {option}, on kasino with ID {kasino_id} for {amount} karma! Total bet is now: {total_bet} Karma**'
output_embed.color = discord.Colour.from_rgb(52, 79, 235)
output_embed.description = f'Remaining karma: {bettor_karma - amount}'

await self.update_kasino_msg(ctx, kasino_id)
await ctx.author.send(embed=output_embed)
await ctx.send(f"Bet added from {ctx.author}!", delete_after=30)
await ctx.message.delete()




async def setup(bot):
query = await bot.db.fetch('SELECT * FROM discord_channel WHERE upvote = True')
Expand Down
51 changes: 0 additions & 51 deletions bot/cogs/owner.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,57 +346,6 @@ async def db_generate_test_data(self, ctx: commands.Context):
random_karma = random.randint(500, 3000)
await self.bot.db.execute(stmt_insert_user_karma, user.id, ctx.guild.id, random_karma)

async def check_if_server_exists_and_insert(bot: Substiify, server_id: int) -> bool:
server = await bot.db.fetchrow("SELECT * FROM discord_server WHERE discord_server_id = $1", server_id)
if server is None:
try:
bot_server = bot.get_guild(server_id) or await bot.fetch_guild(server_id)
except Exception as e:
print(f"Error fetching server: {e}")
return False
if bot_server is None:
print(f"Server with id {server_id} does not exist in the database. Skipping...")
return False
bot.db.execute(
"INSERT INTO discord_server (discord_server_id, server_name) VALUES ($1, $2) ON CONFLICT (discord_server_id) DO NOTHING",
server_id, bot_server.name
)
return True

async def check_if_channel_exists_and_insert(bot: Substiify, channel_id: int) -> bool:
channel = await bot.db.fetchrow("SELECT * FROM discord_channel WHERE discord_channel_id = $1", channel_id)
if channel is None:
try:
bot_channel = bot.get_channel(channel_id) or await bot.fetch_channel(channel_id)
except Exception as e:
print(f"Error fetching channel: {e}")
return False
if bot_channel is None:
print(f"Channel with id {channel_id} does not exist in the database. Skipping...")
return False
bot.db.execute(
"INSERT INTO discord_channel (discord_channel_id, channel_name, discord_server_id) VALUES ($1, $2, $3) ON CONFLICT (discord_channel_id) DO NOTHING",
channel_id, bot_channel.name, bot_channel.guild.id
)
return True

async def check_if_user_exists_and_insert(bot: Substiify, user_id: int) -> bool:
user = await bot.db.fetchrow("SELECT * FROM discord_user WHERE discord_user_id = $1", user_id)
if user is None:
try:
bot_user = bot.get_user(user_id) or await bot.fetch_user(user_id)
except Exception as e:
print(f"Error fetching user: {e}")
return False
if bot_user is None:
print(f"User with id {user_id} does not exist in the database. Skipping...")
return False
bot.db.execute(
"INSERT INTO discord_user (discord_user_id, username, avatar) VALUES ($1, $2, $3) ON CONFLICT (discord_user_id) DO NOTHING",
user_id, bot_user.name, bot_user.display_avatar.url
)
return True


def create_command_usage_embed(results):
commands_used = ""
Expand Down
16 changes: 11 additions & 5 deletions bot/core/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,12 @@ async def on_guild_remove(self, guild: discord.Guild):
@commands.Cog.listener()
async def on_guild_channel_create(self, channel: discord.abc.GuildChannel):
await self._insert_server(channel.guild)
stmt = 'INSERT INTO discord_channel (discord_channel_id, channel_name, discord_server_id, parent_discord_channel_id) VALUES ($1, $2, $3, $4)'
await self.bot.db.execute(stmt, channel.id, channel.name, channel.guild.id, channel.category_id)

await self._insert_channel(channel)

@commands.Cog.listener()
async def on_guild_channel_update(self, before: discord.abc.GuildChannel, after: discord.abc.GuildChannel):
stmt = 'UPDATE discord_channel SET channel_name = $1, parent_discord_channel_id = $2 WHERE discord_channel_id = $3'
await self.bot.db.execute(stmt, after.name, after.category_id, after.id)
stmt = 'UPDATE discord_channel SET channel_name = $1 WHERE discord_channel_id = $2'
await self.bot.db.execute(stmt, after.name, after.id)

async def _insert_server(self, guild: discord.Guild):
stmt = '''
Expand All @@ -58,6 +57,13 @@ async def _insert_server(self, guild: discord.Guild):
'''
await self.bot.db.execute(stmt, guild.id, guild.name)

async def _insert_channel(self, channel: discord.abc.GuildChannel):
stmt = '''
INSERT INTO discord_channel (discord_channel_id, channel_name, discord_server_id) VALUES ($1, $2, $3)
ON CONFLICT (discord_channel_id) DO UPDATE SET channel_name = $2
'''
await self.bot.db.execute(stmt, channel.id, channel.name, channel.guild.id)


async def setup(bot: Substiify):
await bot.add_cog(Events(bot))
4 changes: 3 additions & 1 deletion bot/utils/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,10 @@ async def _insert_foundation(self, user: discord.Member, server: discord.Guild,
avatar_url = user.display_avatar.url if user.display_avatar else None
await self.execute(USER_INSERT_QUERY, user.id, user.name, avatar_url)
await self.execute(SERVER_INSERT_QUERY, server.id, server.name)
if pchannel := channel.parent if hasattr(channel, 'parent') else None:

if pchannel := channel.parent if isinstance(channel, discord.Thread) else None:
await self.execute(CHANNEL_INSERT_QUERY, pchannel.id, pchannel.name, pchannel.guild.id, None)

p_chan_id = pchannel.id if pchannel else None
await self.execute(CHANNEL_INSERT_QUERY, channel.id, channel.name, channel.guild.id, p_chan_id)

Expand Down

0 comments on commit 4c15ed9

Please sign in to comment.