Untitled
Tech
plain_text
a month ago
30 kB
6
Indexable
Never
import sqlite3 import discord import random import asyncio from random import choice from discord import app_commands from discord.ext import commands, tasks #from discord.app_commands import cooldown, BucketType import json import time import re import os from discord.ext.commands import CooldownMapping, BucketType from discord.ui import View # Importing View class from discord.ui from datetime import datetime, timedelta # Your cog code here... #active_bankrobs = set() def load_bankrobs(): if not os.path.exists('bankrobs.json'): with open('bankrobs.json', 'w') as f: json.dump({}, f) with open('bankrobs.json', 'r') as f: return json.load(f) def save_bankrobs(self, data): with open('bankrobs.json', 'w') as f: json.dump(data, f, indent=4) def is_in_bankrob(self, user_id): bankrobs = load_bankrobs() return str(user_id) in bankrobs def add_to_bankrob(self, user_id): bankrobs = load_bankrobs() bankrobs[str(user_id)] = True save_bankrobs(bankrobs) import sqlite3 import discord import random import asyncio from random import choice from discord import app_commands from discord.ext import commands, tasks #from discord.app_commands import cooldown, BucketType import json import time import re import os from discord.ext.commands import CooldownMapping, BucketType from discord.ui import View # Importing View class from discord.ui from datetime import datetime, timedelta # Your cog code here... #active_bankrobs = set() # Utility functions def load_bankrobs(): if not os.path.exists('bankrobs.json'): with open('bankrobs.json', 'w') as f: json.dump({}, f) with open('bankrobs.json', 'r') as f: return json.load(f) def save_bankrobs(data): with open('bankrobs.json', 'w') as f: json.dump(data, f, indent=4) def is_in_bankrob(user_id): bankrobs = load_bankrobs() return str(user_id) in bankrobs def add_to_bankrob(user_id): bankrobs = load_bankrobs() bankrobs[str(user_id)] = True save_bankrobs(bankrobs) def remove_from_bankrob(user_id): bankrobs = load_bankrobs() if str(user_id) in bankrobs: del bankrobs[str(user_id)] save_bankrobs(bankrobs) class BankRobView(discord.ui.View): def __init__(self, ctx, target, cog): super().__init__(timeout=60) self.ctx = ctx self.target = target self.cog = cog self.participants = [] self.message = None self.moneyemoji = "<a:MoneyGIFNexus:1274650931992072205>" self.stopped = False async def interaction_check(self, interaction): if interaction.user == self.target: embed = discord.Embed(description="You can't join a Bankrob against yourself!", color=discord.Color.gold()) await interaction.response.send_message(embed=embed, ephemeral=True) return False if is_in_bankrob(interaction.user.id): if interaction.user == self.ctx.author: return True embed = discord.Embed(description="You are already in a bankrob and cannot join another one.", color=discord.Color.blurple()) await interaction.response.send_message(embed=embed, ephemeral=True) return False return True @discord.ui.button(label="JOIN BANKROB", style=discord.ButtonStyle.green, custom_id="join_bankrob") async def join_button(self, interaction: discord.Interaction, button: discord.ui.Button): if interaction.user not in self.participants: self.participants.append(interaction.user) add_to_bankrob(interaction.user.id) embed = discord.Embed(description="You have successfully joined the Bankrob.", color=discord.Color.blue()) await interaction.response.send_message(embed=embed, ephemeral=True) else: embed = discord.Embed(description="You have already joined the Bankrob.", color=discord.Color.blue()) await interaction.response.send_message(embed=embed, ephemeral=True) def format_money(self, amount): return "{:,}".format(amount) async def on_timeout(self): for child in self.children: if isinstance(child, discord.ui.Button): child.disabled = True await self.message.edit(view=self) min_participants = 5 if len(self.participants) < min_participants: embed = discord.Embed(description=f"Bankrob failed. Not enough participants.", color=discord.Color.brand_red()) await self.ctx.send(embed=embed) for user in self.participants: remove_from_bankrob(user.id) remove_from_bankrob(self.ctx.author.id) return target_balance = self.cog.get_bank_balance(self.target.id) split_amount = target_balance // len(self.participants) for user in self.participants: self.cog.update_balance(user.id, split_amount, 'wallet') self.cog.update_balance(self.target.id, -target_balance, 'bank') results = [f"`{user.display_name}` ran away with `{self.moneyemoji} {self.format_money(split_amount)}`" for user in self.participants] description = f"Good job everyone! We racked a total of `{self.moneyemoji} {self.format_money(target_balance)}` from `{self.target.display_name}`.\n\n" + "\n".join(results) endembed = discord.Embed(title="Bank Rob Complete!", description=description, color=discord.Color.green()) await self.ctx.send(embed=endembed) for user in self.participants: dm_embed = discord.Embed( title="Heist Successful!", description=f"You ran away with **{self.moneyemoji} {self.format_money(split_amount)}** robbing `{self.target.display_name}`\n \nin (*{self.ctx.guild.name}*).", color=discord.Color(0x39FF14) ) await user.send(embed=dm_embed) if self.participants: dm_embed = discord.Embed( title="You've been robbed!", description=f"{len(self.participants)} people have stolen **{self.moneyemoji} {self.format_money(target_balance)}**. The bankrob was led by `{self.ctx.author.display_name}`\n \nin *({self.ctx.guild.name})*", color=discord.Color.red()) await self.target.send(embed=dm_embed) for user in self.participants: remove_from_bankrob(user.id) remove_from_bankrob(self.ctx.author.id) self.stop() fines = [] for user in self.participants: wallet_balance = self.cog.get_wallet_balance(user.id) fine_percentage = random.uniform(0.05, 0.15) # Random percentage between 5% and 15% fine_amount = int(wallet_balance * fine_percentage) fine_amount = max(fine_amount, 10000) # Minimum fine of 10,000 fine_amount = min(fine_amount, wallet_balance) # Can't fine more than they have self.cog.update_balance(user.id, -fine_amount, 'wallet') fines.append((user, fine_amount)) fine_descriptions = [f"`{user.display_name}` was fined `{self.moneyemoji} {self.format_money(amount)}`" for user, amount in fines] description = f"The bankrob was stopped by {self.target.mention} using a mobile! All participants have been fined:\n\n" + "\n".join(fine_descriptions) embed = discord.Embed(title="Bankrob Stopped!", description=description, color=discord.Color.red()) await self.ctx.send(embed=embed) for user in self.participants: remove_from_bankrob(user.id) remove_from_bankrob(self.ctx.author.id) self.stop() class Bankrob(commands.Cog): def __init__(self, client): self.client = client self.rob_cooldowns = {} self.rob_attempts = {} self.ongoing_bankrobs = {} self.db_path = os.path.join('Cogs', 'economy.db') self.conn = sqlite3.connect(self.db_path) self.cursor = self.conn.cursor() self.moneyemoji = "<a:MoneyGIFNexus:1274650931992072205>" #self.active_bankrobs = set() # Initialize the rob_attempts dictionary here #Function to retrieve a user's wallet balance from mainbank.json def get_wallet_balance(self, user_id): self.cursor.execute("SELECT wallet FROM users WHERE user_id = ?", (user_id,)) result = self.cursor.fetchone() return result[0] if result else 0 def get_bank_balance(self, user_id): self.cursor.execute("SELECT bank FROM users WHERE user_id = ?", (user_id,)) result = self.cursor.fetchone() return result[0] if result else 0 async def open_account(self, member): self.cursor.execute("SELECT * FROM users WHERE user_id = ?", (member.id,)) if not self.cursor.fetchone(): self.cursor.execute("INSERT INTO users (user_id, wallet, bank) VALUES (?, 0, 0)", (member.id,)) self.conn.commit() return True return False def update_balance(self, user_id, change, account_type='wallet'): self.cursor.execute(f"UPDATE users SET {account_type} = {account_type} + ? WHERE user_id = ?", (change, user_id)) self.conn.commit() def format_money(self, amount): return "{:,}".format(amount) # Helper function to parse the amount with k, m, b multipliers def parse_amount(self, amount_str): multipliers = {'k': 1000, 'm': 1000000, 'b': 1000000000} match = re.match(r"(\d+)([kmb])?$", amount_str) if match: number, multiplier = match.groups() number = int(number) if multiplier: number *= multipliers[multiplier.lower()] return number return 0 # Helper function to update balance def update_balance(self, user_id, change, account_type='wallet'): self.cursor.execute(f"UPDATE users SET {account_type} = {account_type} + ? WHERE user_id = ?", (change, user_id)) self.conn.commit() #def cog_check(self, ctx): # If the user is in active_bankrobs, block the command #return ctx.author.id not in self.active_bankrobs @commands.hybrid_command(name="bankrob", description="Start a bankrob on any user.") @app_commands.describe(target="The user on whom you want to start a bankrob") async def bankrob(self, ctx, target: discord.Member): if target.bot: embed = discord.Embed(description="You can't start a bankrob on bots. They're too smart for you!", color=discord.Color.red()) await ctx.send(embed=embed) return if is_in_bankrob(ctx.author.id): embed = discord.Embed(description="You are already in a bankrob. Therefore you can't use any other command until the Bankrob ends.", color=discord.Color.teal()) await ctx.send(embed=embed) return if ctx.author == target: embed = discord.Embed(description="You can't run a bankrob on yourself. Idiot!", color=discord.Color.blurple()) await ctx.send(embed=embed) return bank_balance = self.get_bank_balance(target.id) if bank_balance == 0: await ctx.send(f"`{target.display_name}` has no money in their bank.") return start_dm_embed = discord.Embed( title="Bankrob Alert!", description=f"A bankrob is being started on you by `{ctx.author.display_name}`! in **{ctx.guild.name}**\n \n[Click Here]({ctx.message.jump_url})", color=discord.Color.red()) try: await target.send(embed=start_dm_embed) except discord.Forbidden: await ctx.send(f"Unable to send a DM to {target.mention}. They may have DMs disabled.") return view = BankRobView(ctx, target, self) self.ongoing_bankrobs[target.id] = view embed = discord.Embed( title="Bankrob Started", description=f"`{ctx.author.display_name}` is starting a bankrob on `{target.display_name}`. Click the button below to join the bankrob.", color=discord.Color.green()) embed.set_thumbnail(url=ctx.author.display_avatar.url) message = await ctx.send(embed=embed, view=view) view.message = message add_to_bankrob(ctx.author.id) @commands.hybrid_command(name="rob", description="Rob any user") @app_commands.describe(member="The user whom you want to rob.") async def rob(self, ctx, member: discord.Member): if member.bot: embed = discord.Embed(description="You can't rob bots. They're too smart for you!", color=discord.Color.red()) await ctx.send(embed=embed) return if is_in_bankrob(ctx.author.id): embed = discord.Embed(description="You are already in a bankrob. Therefore you can't use any other command until the Bankrob ends.", color=discord.Color.teal()) await ctx.send(embed=embed) return False if member == ctx.author: embed = discord.Embed(description="You can't run a bankrob on yourself. Idiot!", color=discord.Color.blurple()) await ctx.send(embed=embed) return await self.open_account(ctx.author) await self.open_account(member) user_id = ctx.author.id if user_id in self.rob_cooldowns and self.rob_cooldowns[user_id] > datetime.now(): cooldown_time = (self.rob_cooldowns[user_id] - datetime.now()).total_seconds() await ctx.send(f"{ctx.author.mention}, you are on a cooldown. Try again in `{int(cooldown_time)}` seconds.") return author_balance = self.get_wallet_balance(ctx.author.id) if author_balance < 10000: await ctx.send(f"{ctx.author.mention}, you need at least {self.moneyemoji} 10,000 in your wallet to attempt a robbery!") return victim_balance = self.get_wallet_balance(member.id) if victim_balance < 10000: await ctx.send("It's not worth it, they don't have enough money!") return if self.rob_attempts.get(user_id, 0) == 0: penalty = random.randint(1000, 5000) self.update_balance(ctx.author.id, -penalty) await ctx.send(f"Haha, you were caught and paid `{member.display_name}` {self.moneyemoji} {penalty:,}!") self.rob_cooldowns[user_id] = datetime.now() + timedelta(seconds=10) self.rob_attempts[user_id] = 1 tembed = discord.Embed( title="Rob Attempt!", description=f"{ctx.author.mention} tried robbing you in (*{ctx.guild.name}*) but failed.\n \n[Click Here]({ctx.message.jump_url})", colour=discord.Colour.red()) await member.send(embed=tembed) else: if random.randint(1, 3) != 1: earnings = random.randint(10000, min(30000000, victim_balance)) self.update_balance(ctx.author.id, earnings) self.update_balance(member.id, -earnings) await ctx.send(f"{ctx.author.mention} successfully stole **{self.moneyemoji} {earnings:,}** from `{member.display_name}`.") memembed = discord.Embed( title="Money Stolen!", description=f'{ctx.author.mention} has stolen **{self.moneyemoji} {earnings:,}** from you in (*{ctx.guild.name}*)!', color=discord.Color.red()) await member.send(embed=memembed) self.rob_cooldowns[user_id] = datetime.now() + timedelta(minutes=5) self.rob_attempts[user_id] = 0 else: penalty = random.randint(1000, 5000) self.update_balance(ctx.author.id, -penalty) self.update_balance(ctx.member.id, penalty) await ctx.send(f"Haha, you were caught and paid `{member.display_name}` {self.moneyemoji} {penalty:,}!") self.rob_cooldowns[user_id] = datetime.now() + timedelta(seconds=10) nembed = discord.Embed( title="Rob Attempt!", description=f"{ctx.author.mention} tried robbing you in (*{ctx.guild.name}*) but failed.", colour=discord.Colour.red()) await member.send(embed=nembed) async def setup(client): await client.add_cog(Bankrob(client)) async def stop_bankrob(self, ctx, view): await view.stop_bankrob(ctx) del self.ongoing_bankrobs[ctx.author.id] class BankRobView(discord.ui.View): def __init__(self, ctx, target, cog): super().__init__(timeout=60) self.ctx = ctx self.target = target self.cog = cog self.participants = [] self.message = None self.moneyemoji = "<a:MoneyGIFNexus:1274650931992072205>" self.stopped = False self.ongoing_bankrobs = {} def remove_from_bankrob(user_id): bankrobs = load_bankrobs() if str(user_id) in bankrobs: del bankrobs[str(user_id)] save_bankrobs(bankrobs) async def interaction_check(self, interaction): if interaction.user == self.target: embed = discord.Embed(description="You can't join a Bankrob against yourself!", color=discord.Color.gold()) await interaction.response.send_message(embed=embed, ephemeral=True) return False if is_in_bankrob(interaction.user.id): if interaction.user == self.ctx.author: return True embed = discord.Embed(description="You are already in a bankrob and cannot join another one.", color=discord.Color.blurple()) await interaction.response.send_message(embed=embed, ephemeral=True) return False return True @discord.ui.button(label="JOIN BANKROB", style=discord.ButtonStyle.green, custom_id="join_bankrob") async def join_button(self, interaction: discord.Interaction, button: discord.ui.Button): if interaction.user not in self.participants: self.participants.append(interaction.user) add_to_bankrob(interaction.user.id) embed = discord.Embed(description="You have successfully joined the Bankrob.", color=discord.Color.blue()) await interaction.response.send_message(embed=embed, ephemeral=True) else: embed = discord.Embed(description="You have already joined the Bankrob.", color=discord.Color.blue()) await interaction.response.send_message(embed=embed, ephemeral=True) def format_money(self, amount): return "{:,}".format(amount) async def on_timeout(self): if self.stopped: return for child in self.children: if isinstance(child, discord.ui.Button): child.disabled = True await self.message.edit(view=self) min_participants = 5 if len(self.participants) < min_participants: embed = discord.Embed(description=f"Bankrob failed. Not enough participants.", color=discord.Color.brand_red()) await self.ctx.send(embed=embed) for user in self.participants: self.remove_from_bankrob(user.id) self.remove_from_bankrob(self.ctx.author.id) return target_balance = self.cog.get_bank_balance(self.target.id) split_amount = target_balance // len(self.participants) for user in self.participants: self.cog.update_balance(user.id, split_amount, 'wallet') self.cog.update_balance(self.target.id, -target_balance, 'bank') results = [f"`{user.display_name}` ran away with `{self.moneyemoji} {self.format_money(split_amount)}`" for user in self.participants] description = f"Good job everyone! We racked a total of `{self.moneyemoji} {self.format_money(target_balance)}` from `{self.target.display_name}`.\n\n" + "\n".join(results) endembed = discord.Embed(title="Bank Rob Complete!", description=description, color=discord.Color.green()) await self.ctx.send(embed=endembed) for user in self.participants: dm_embed = discord.Embed( title="Heist Successful!", description=f"You ran away with **{self.moneyemoji} {self.format_money(split_amount)}** robbing `{self.target.display_name}`\n \nin (*{self.ctx.guild.name}*).", color=discord.Color(0x39FF14) ) await user.send(embed=dm_embed) if self.participants: dm_embed = discord.Embed( title="You've been robbed!", description=f"{len(self.participants)} people have stolen **{self.moneyemoji} {self.format_money(target_balance)}**. The bankrob was led by `{self.ctx.author.display_name}`\n \nin *({self.ctx.guild.name})*", color=discord.Color.red()) await self.target.send(embed=dm_embed) for user in self.participants: self.remove_from_bankrob() self.remove_from_bankrob(self.ctx.author.id) self.stop() class Bankrob(commands.Cog): def __init__(self, client): self.client = client self.rob_cooldowns = {} self.rob_attempts = {} self.ongoing_bankrobs = {} self.db_path = os.path.join('Cogs', 'economy.db') self.conn = sqlite3.connect(self.db_path) self.cursor = self.conn.cursor() self.moneyemoji = "<a:MoneyGIFNexus:1274650931992072205>" #self.active_bankrobs = set() # Initialize the rob_attempts dictionary here #Function to retrieve a user's wallet balance from mainbank.json def get_wallet_balance(self, user_id): self.cursor.execute("SELECT wallet FROM users WHERE user_id = ?", (user_id,)) result = self.cursor.fetchone() return result[0] if result else 0 def get_bank_balance(self, user_id): self.cursor.execute("SELECT bank FROM users WHERE user_id = ?", (user_id,)) result = self.cursor.fetchone() return result[0] if result else 0 async def open_account(self, member): self.cursor.execute("SELECT * FROM users WHERE user_id = ?", (member.id,)) if not self.cursor.fetchone(): self.cursor.execute("INSERT INTO users (user_id, wallet, bank) VALUES (?, 0, 0)", (member.id,)) self.conn.commit() return True return False def update_balance(self, user_id, change, account_type='wallet'): self.cursor.execute(f"UPDATE users SET {account_type} = {account_type} + ? WHERE user_id = ?", (change, user_id)) self.conn.commit() def format_money(self, amount): return "{:,}".format(amount) # Helper function to parse the amount with k, m, b multipliers def parse_amount(self, amount_str): multipliers = {'k': 1000, 'm': 1000000, 'b': 1000000000} match = re.match(r"(\d+)([kmb])?$", amount_str) if match: number, multiplier = match.groups() number = int(number) if multiplier: number *= multipliers[multiplier.lower()] return number return 0 # Helper function to update balance def update_balance(self, user_id, change, account_type='wallet'): self.cursor.execute(f"UPDATE users SET {account_type} = {account_type} + ? WHERE user_id = ?", (change, user_id)) self.conn.commit() #def cog_check(self, ctx): # If the user is in active_bankrobs, block the command #return ctx.author.id not in self.active_bankrobs @commands.hybrid_command(name="bankrob", description="Start a bankrob on any user.") @app_commands.describe(target="The user on whom you want to start a bankrob") async def bankrob(self, ctx, target: discord.Member): if target.bot: embed = discord.Embed(description="You can't start a bankrob on bots. They're too smart for you!", color=discord.Color.red()) await ctx.send(embed=embed) return if is_in_bankrob(ctx.author.id): embed = discord.Embed(description="You are already in a bankrob. Therefore you can't use any other command until the Bankrob ends.", color=discord.Color.teal()) await ctx.send(embed=embed) return if ctx.author == target: embed = discord.Embed(description="You can't run a bankrob on yourself. Idiot!", color=discord.Color.blurple()) await ctx.send(embed=embed) return bank_balance = self.get_bank_balance(target.id) if bank_balance == 0: await ctx.send(f"`{target.display_name}` has no money in their bank.") return start_dm_embed = discord.Embed( title="Bankrob Alert!", description=f"A bankrob is being started on you by `{ctx.author.display_name}`! in **{ctx.guild.name}**\n \n[Click Here]({ctx.message.jump_url})", color=discord.Color.red()) try: await target.send(embed=start_dm_embed) except discord.Forbidden: await ctx.send(f"Unable to send a DM to {target.mention}. They may have DMs disabled.") return view = BankRobView(ctx, target, self) self.ongoing_bankrobs[target.id] = view embed = discord.Embed( title="Bankrob Started", description=f"`{ctx.author.display_name}` is starting a bankrob on `{target.display_name}`. Click the button below to join the bankrob.", color=discord.Color.green()) embed.set_thumbnail(url=ctx.author.display_avatar.url) message = await ctx.send(embed=embed, view=view) view.message = message add_to_bankrob(ctx.author.id) @commands.hybrid_command(name="rob", description="Rob any user") @app_commands.describe(member="The user whom you want to rob.") async def rob(self, ctx, member: discord.Member): if member.bot: embed = discord.Embed(description="You can't rob bots. They're too smart for you!", color=discord.Color.red()) await ctx.send(embed=embed) return if is_in_bankrob(ctx.author.id): embed = discord.Embed(description="You are already in a bankrob. Therefore you can't use any other command until the Bankrob ends.", color=discord.Color.teal()) await ctx.send(embed=embed) return False if member == ctx.author: embed = discord.Embed(description="You can't run a bankrob on yourself. Idiot!", color=discord.Color.blurple()) await ctx.send(embed=embed) return await self.open_account(ctx.author) await self.open_account(member) user_id = ctx.author.id if user_id in self.rob_cooldowns and self.rob_cooldowns[user_id] > datetime.now(): cooldown_time = (self.rob_cooldowns[user_id] - datetime.now()).total_seconds() await ctx.send(f"{ctx.author.mention}, you are on a cooldown. Try again in `{int(cooldown_time)}` seconds.") return author_balance = self.get_wallet_balance(ctx.author.id) if author_balance < 10000: await ctx.send(f"{ctx.author.mention}, you need at least {self.moneyemoji} 10,000 in your wallet to attempt a robbery!") return victim_balance = self.get_wallet_balance(member.id) if victim_balance < 10000: await ctx.send("It's not worth it, they don't have enough money!") return if self.rob_attempts.get(user_id, 0) == 0: penalty = random.randint(1000, 5000) self.update_balance(ctx.author.id, -penalty) await ctx.send(f"Haha, you were caught and paid `{member.display_name}` {self.moneyemoji} {penalty:,}!") self.rob_cooldowns[user_id] = datetime.now() + timedelta(seconds=10) self.rob_attempts[user_id] = 1 tembed = discord.Embed( title="Rob Attempt!", description=f"{ctx.author.mention} tried robbing you in (*{ctx.guild.name}*) but failed.\n \n[Click Here]({ctx.message.jump_url})", colour=discord.Colour.red()) await member.send(embed=tembed) else: if random.randint(1, 3) != 1: earnings = random.randint(10000, min(30000000, victim_balance)) self.update_balance(ctx.author.id, earnings) self.update_balance(member.id, -earnings) await ctx.send(f"{ctx.author.mention} successfully stole **{self.moneyemoji} {earnings:,}** from `{member.display_name}`.") memembed = discord.Embed( title="Money Stolen!", description=f'{ctx.author.mention} has stolen **{self.moneyemoji} {earnings:,}** from you in (*{ctx.guild.name}*)!', color=discord.Color.red()) await member.send(embed=memembed) self.rob_cooldowns[user_id] = datetime.now() + timedelta(minutes=5) self.rob_attempts[user_id] = 0 else: penalty = random.randint(1000, 5000) self.update_balance(ctx.author.id, -penalty) self.update_balance(ctx.member.id, penalty) await ctx.send(f"Haha, you were caught and paid `{member.display_name}` {self.moneyemoji} {penalty:,}!") self.rob_cooldowns[user_id] = datetime.now() + timedelta(seconds=10) nembed = discord.Embed( title="Rob Attempt!", description=f"{ctx.author.mention} tried robbing you in (*{ctx.guild.name}*) but failed.", colour=discord.Colour.red()) await member.send(embed=nembed) async def setup(client): await client.add_cog(Bankrob(client))
Leave a Comment