<commit_before>
import discord
from discord.ext import commands

import asyncio
import copy
import random
import re
import sys
import timeit
from typing import Optional

from bs4 import BeautifulSoup
import pydealer

# from modules import war
from utilities import checks

sys.path.insert(0, "..")
from units import games
from units.twenty_four import check_solution, generate_numbers
sys.path.pop(0)

def setup(bot):
	bot.add_cog(Games(bot))

class Games(commands.Cog):
	
	'''
	Also see Adventure, Chess, Fish, Maze, Poker, and Trivia categories
	'''
	
	def __init__(self, bot):
		self.bot = bot
		self.war_channel, self.war_players = None, []
		self.taboo_players = []
		self.blackjack_ranks = copy.deepcopy(pydealer.const.DEFAULT_RANKS)
		self.blackjack_ranks["values"].update({"Ace": 0, "King": 9, "Queen": 9, "Jack": 9})
		for value in self.blackjack_ranks["values"]:
			self.blackjack_ranks["values"][value] += 1
		#check default values
		
		self.bot.loop.create_task(self.initialize_database(), name = "Initialize database")

	async def initialize_database(self):
		await self.bot.connect_to_database()
		await self.bot.db.execute("CREATE SCHEMA IF NOT EXISTS games")
		await self.bot.db.execute(
			"""
			CREATE TABLE IF NOT EXISTS games.erps (
				object			TEXT, 
				against			TEXT, 
				action			TEXT, 
				PRIMARY KEY 	(object, against)
			)
			"""
		)
		exists = await self.bot.db.fetchval("SELECT EXISTS (SELECT * from games.erps)")
		if not exists:
			url = "http://www.umop.com/rps101/alloutcomes.htm"
			async with self.bot.aiohttp_session.get(url) as resp:
				data = await resp.text()
			raw_text = BeautifulSoup(data, "lxml").text
			raw_text = re.sub("\n+", '\n', raw_text).strip()
			raw_text = raw_text.lower().replace("video game", "game")
			raw_text = raw_text.split('\n')[:-1]
			for line in raw_text:
				words = line.split()
				if words[0].isdecimal() and words[1] == '-':
					object = words[-1]
				else:
					await self.bot.db.execute(
						"""
						INSERT INTO games.erps (object, against, action)
						VALUES ($1, $2, $3)
						ON CONFLICT (object, against) DO
						UPDATE SET action = $3
						""", 
						object, words[-1], ' '.join(words[:-1])
					)
			# TODO: Properly handle object against not at end
	
	@commands.command(name = "24", aliases = ["twenty-four"])
	@checks.not_forbidden()
	async def twenty_four(self, ctx):
		'''24 Game'''
		numbers = generate_numbers()
		
		CEK = '\N{COMBINING ENCLOSING KEYCAP}'
		numbers = list(map(str, numbers))
		await ctx.embed_reply(f"{numbers[0]}{CEK}{numbers[1]}{CEK}\n"
								f"{numbers[2]}{CEK}{numbers[3]}{CEK}\n")
		
		async def incorrect(message, value):
			response_ctx = await ctx.bot.get_context(message)
			await response_ctx.embed_reply(f"{message.content} = {value}", title = "Incorrect", 
											in_response_to = False, attempt_delete = False)
		
		def check(message):
			if message.channel != ctx.channel:
				return False
			if (value := check_solution(numbers, message.content)) is False:
				return False
			elif value != 24:
				ctx.bot.loop.create_task(incorrect(message, int(value)), 
											name = "Send response to incorrect solution for 24 Game")
				return False
			return True
		
		message = await ctx.bot.wait_for('message', check = check)
		ctx = await ctx.bot.get_context(message)
		await ctx.embed_reply(f"{message.content} = 24", title = "Correct!", 
								in_response_to = False, attempt_delete = False)
	
	@commands.command()
	@checks.not_forbidden()
	async def blackjack(self, ctx):
		'''
		Play a game of blackjack
		Manage Messages permission required for message cleanup
		'''
		# TODO: S17
		deck = pydealer.Deck()
		deck.shuffle()
		dealer = deck.deal(2)
		player = deck.deal(2)
		dealer_string = f":grey_question: :{dealer.cards[1].suit.lower()}: {dealer.cards[1].value}"
		player_string = self.cards_to_string(player.cards)
		dealer_total = self.blackjack_total(dealer.cards)<commit_msg>[Discord] Improve 24 command formatting<commit_after>
import discord
from discord.ext import commands

import asyncio
import copy
import random
import re
import sys
import timeit
from typing import Optional

from bs4 import BeautifulSoup
import pydealer

# from modules import war
from utilities import checks

sys.path.insert(0, "..")
from units import games
from units.twenty_four import check_solution, generate_numbers
sys.path.pop(0)

def setup(bot):
	bot.add_cog(Games(bot))

class Games(commands.Cog):
	
	'''
	Also see Adventure, Chess, Fish, Maze, Poker, and Trivia categories
	'''
	
	def __init__(self, bot):
		self.bot = bot
		self.war_channel, self.war_players = None, []
		self.taboo_players = []
		self.blackjack_ranks = copy.deepcopy(pydealer.const.DEFAULT_RANKS)
		self.blackjack_ranks["values"].update({"Ace": 0, "King": 9, "Queen": 9, "Jack": 9})
		for value in self.blackjack_ranks["values"]:
			self.blackjack_ranks["values"][value] += 1
		#check default values
		
		self.bot.loop.create_task(self.initialize_database(), name = "Initialize database")

	async def initialize_database(self):
		await self.bot.connect_to_database()
		await self.bot.db.execute("CREATE SCHEMA IF NOT EXISTS games")
		await self.bot.db.execute(
			"""
			CREATE TABLE IF NOT EXISTS games.erps (
				object			TEXT, 
				against			TEXT, 
				action			TEXT, 
				PRIMARY KEY 	(object, against)
			)
			"""
		)
		exists = await self.bot.db.fetchval("SELECT EXISTS (SELECT * from games.erps)")
		if not exists:
			url = "http://www.umop.com/rps101/alloutcomes.htm"
			async with self.bot.aiohttp_session.get(url) as resp:
				data = await resp.text()
			raw_text = BeautifulSoup(data, "lxml").text
			raw_text = re.sub("\n+", '\n', raw_text).strip()
			raw_text = raw_text.lower().replace("video game", "game")
			raw_text = raw_text.split('\n')[:-1]
			for line in raw_text:
				words = line.split()
				if words[0].isdecimal() and words[1] == '-':
					object = words[-1]
				else:
					await self.bot.db.execute(
						"""
						INSERT INTO games.erps (object, against, action)
						VALUES ($1, $2, $3)
						ON CONFLICT (object, against) DO
						UPDATE SET action = $3
						""", 
						object, words[-1], ' '.join(words[:-1])
					)
			# TODO: Properly handle object against not at end
	
	@commands.command(name = "24", aliases = ["twenty-four"])
	@checks.not_forbidden()
	async def twenty_four(self, ctx):
		'''24 Game'''
		numbers = generate_numbers()
		
		CEK = '\N{COMBINING ENCLOSING KEYCAP}'
		numbers = list(map(str, numbers))
		await ctx.embed_reply(
			f"{numbers[0]}{CEK}{numbers[1]}{CEK}\n"
			f"{numbers[2]}{CEK}{numbers[3]}{CEK}\n"
		)
		
		async def incorrect(message, value):
			response_ctx = await ctx.bot.get_context(message)
			await response_ctx.embed_reply(
				f"{message.content} = {value}", title = "Incorrect", 
				in_response_to = False, attempt_delete = False
			)
		
		def check(message):
			if message.channel != ctx.channel:
				return False
			if (value := check_solution(numbers, message.content)) is False:
				return False
			elif value != 24:
				ctx.bot.loop.create_task(
					incorrect(message, int(value)), 
					name = "Send response to incorrect solution for 24 Game"
				)
				return False
			return True
		
		message = await ctx.bot.wait_for('message', check = check)
		ctx = await ctx.bot.get_context(message)
		await ctx.embed_reply(
			f"{message.content} = 24", title = "Correct!", 
			in_response_to = False, attempt_delete = False
		)
	
	@commands.command()
	@checks.not_forbidden()
	async def blackjack(self, ctx):
		'''
		Play a game of blackjack
		Manage Messages permission required for message cleanup
		'''
		# TODO: S17
		deck = pydealer.Deck()
		deck.shuffle()
		dealer = deck.deal(2)
		player = deck.deal(2)
		dealer_string = f":grey_question: :{dealer.cards[1].suit.lower()}: {dealer.cards[1].value}"
		player_string = self.cards_to_string(player.cards)
		dealer_total = self.blackjack_total(dealer.cards)
{'fraction_non_alphanumeric': 0.13689948028901, 'fraction_numerical': 0.01064773735581189, 'mean_word_length': 3.7188995215311005, 'pattern_counts': {'":': 10, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '74944', 'n_tokens_mistral': 3215, 'n_tokens_neox': 2705, 'n_words': 661}