async def on_guild_join(self, guild): try: self.bot.guild_options[guild.id] = DEFAULT_GUILD_SETTINGS.copy() async with utils.Transaction(self.bot.db) as conn: await conn.execute('INSERT INTO guilds VALUES (?, ?, ?, ?, ?)', (guild.id,) + DEFAULT_GUILD_ROW) except sqlite3.IntegrityError: pass # rejoining a guild
async def disable_cmd(self, ctx, command): """ Disable a command. """ command = self.bot.get_command(command) disabled_commands = self.bot.guild_options[ ctx.guild.id]['disabled_commands'] async with utils.Transaction(self.bot.db) as conn: if command is None: return await ctx.send('Command not found.') elif (command.parent is not None and command.parent.name in ['command'] or command.name in ['command']): return await ctx.send('You cannot disable this command.') elif command.parent is not None and command.parent.name in disabled_commands: return await ctx.send( f'`{command.name}`\'s parent, `{command.parent.name}`, is already disabled.' ) elif command.qualified_name in disabled_commands: return await ctx.send( f'`{command.qualified_name}` is already disabled.') disabled_commands.add(command.qualified_name) await conn.execute( 'UPDATE guilds SET disabled_commands = ? WHERE id = ?', (pickle.dumps(disabled_commands), ctx.guild.id)) await ctx.send(f'`{command.qualified_name}` disabled.')
async def enable(self, ctx, channel: discord.TextChannel): """ Enables approve-only mode for build submission on this server. """ async with utils.Transaction(self.bot.db) as conn: self.bot.guild_options['builds_channel'] = channel.id await conn.execute( 'UPDATE guilds SET builds_channel = ? WHERE id = ?', (channel.id, ctx.guild.id)) await ctx.send(f'Approve-only mode enabled with {channel.mention}.' )
async def reset(self, ctx): """ Reset prefixes to default. """ async with utils.Transaction(self.bot.db) as conn: self.bot.guild_options[ ctx.guild.id]['prefixes'] = config.default_prefixes.copy() await conn.execute( 'UPDATE guilds SET prefixes = ? WHERE id = ?', (pickle.dumps(config.default_prefixes.copy()), ctx.guild.id)) await ctx.send('Prefixes reset.')
def deliver_tx(self, raw_tx): """ Mutate state if valid Tx """ try: # Handle unvalid txn tx = utils.Transaction(raw_tx) except Exception: return Result.error(log='txn syntax invalid') self.new_block_txs.append(tx) self.db.update_state(tx=tx) return Result.ok()
def deliver_tx(self, raw_tx): """ Mutate state if valid Tx """ try: # Handle unvalid txn tx = utils.Transaction(raw_tx) except Exception: return ResponseDeliverTx(log='txn syntax invalid', code=1) self.new_block_txs.append(tx) self.db.update_state(tx=tx) return ResponseDeliverTx(code=CodeTypeOk)
async def debug(self, ctx, *, string=''): """ Debug command. """ async with utils.Transaction(self.bot.db) as conn: # await conn.execute('ALTER TABLE guilds ADD builds_channel INTEGER') # await conn.execute('ALTER TABLE builds ADD in_queue INTEGER DEFAULT 0') # await conn.execute('CREATE TABLE IF NOT EXISTS stats (id timestamp PRIMARY KEY, stats BLOB)') # await conn.execute(f'ALTER TABLE guilds ADD disabled_commands BLOB') # await conn.execute(f'ALTER TABLE guilds ADD disabled_categories BLOB') # await conn.execute(f'UPDATE guilds SET disabled_commands = ?', (pickle.dumps(set()),)) # await conn.execute(f'UPDATE guilds SET disabled_categories = ?', (pickle.dumps(set()),)) # await conn.execute('ALTER TABLE guilds RENAME TO guilds_orig') # await conn.execute('CREATE TABLE guilds(id INTEGER PRIMARY KEY, prefixes BLOB, builds_channel INTEGER, disabled_commands BLOB, disabled_cogs BLOB)') # await conn.execute('INSERT INTO guilds(id, prefixes, builds_channel, disabled_commands, disabled_cogs) SELECT id , prefixes, builds_channel, disabled_commands, disabled_categories FROM guilds_orig') # await conn.execute('DROP TABLE guilds_orig') # self.bot.guild_options[ctx.guild.id]['disabled_cogs'] = set() # await conn.execute('ALTER TABLE users RENAME TO users_orig') # await conn.execute('CREATE TABLE users(id INTEGER PRIMARY KEY, data BLOB)') # c = await conn.execute('SELECT * FROM users_orig') # table = await c.fetchall() # for user in table: # await conn.execute('INSERT INTO users VALUES (?, ?)', (user['id'], pickle.dumps({'contours_played': user['contours_played'], 'contours_record': user['contours_record']}))) # c = await conn.execute('SELECT * FROM users') # table = await c.fetchall() # print(table) # await conn.execute('DROP TABLE users_orig') pass peedz = self.bot.get_guild(500601711635726336) peedz_chat = peedz.get_channel(501338962548359179) senate = peedz.get_channel(621648295017709593) # print(peedz.roles) # print(peedz.me.guild_permissions.manage_roles) # print('start of fetch') # async for message in senate.history(limit=100): # print(f'{message.author} {message.content}') kia = self.bot.get_guild(690060098558492692) print('\n'.join([ f'{channel.name} ({len(channel.members)}) [{channel.id}]' for channel in kia.channels if type(channel) == discord.TextChannel and channel.permissions_for(kia.me).read_messages ])) t_channel = kia.get_channel(692530714654015548) print('start of fetch') async for message in t_channel.history(limit=100): print(f'{message.author} {message.content}') await ctx.send('Done.')
async def sms(self, ctx, user_id, streak: int, last: int, skips: int): """ Debug tool. """ data = await utils.fetch_user(self.bot.db, user_id) data['morning_streak'] = streak data['morning_last'] = last data['morning_skips'] = skips async with utils.Transaction(self.bot.db) as conn: await conn.execute('UPDATE users SET data = ? WHERE id = ?', (pickle.dumps(data), user_id)) await ctx.send('Done.')
async def delete(self, ctx, prefix): """ Delete a prefix. """ prefixes = self.bot.guild_options[ctx.guild.id]['prefixes'] async with utils.Transaction(self.bot.db) as conn: try: prefixes.remove(prefix) await conn.execute( 'UPDATE guilds SET prefixes = ? WHERE id = ?', (pickle.dumps(prefixes), ctx.guild.id)) await ctx.send('Prefix removed.') except KeyError: await ctx.send('Prefix not found.')
async def add(self, ctx, prefix): """ Add a prefix. Prefixes with spaces should use " to wrap the whole prefix, "like this". """ prefixes = self.bot.guild_options[ctx.guild.id]['prefixes'] async with utils.Transaction(self.bot.db) as conn: if len(prefixes) >= 10: return await ctx.send( 'Maximum number of prefixes (10) reached. Please remove some before adding another.' ) elif prefix in prefixes: return await ctx.send('Prefix already exists.') prefixes.add(prefix) await conn.execute('UPDATE guilds SET prefixes = ? WHERE id = ?', (pickle.dumps(prefixes), ctx.guild.id)) await ctx.send('Prefix added.')
async def enable_cat(self, ctx, category): """ Enable a category. """ cog = self.bot.get_cog(category.title()) disabled_cogs = self.bot.guild_options[ctx.guild.id]['disabled_cogs'] async with utils.Transaction(self.bot.db) as conn: if cog is None: return await ctx.send('Category not found.') try: disabled_cogs.remove(cog.qualified_name) await conn.execute( 'UPDATE guilds SET disabled_cogs = ? WHERE id = ?', (pickle.dumps(disabled_cogs), ctx.guild.id)) await ctx.send(f'`{cog.qualified_name}` enabled.') except KeyError: await ctx.send(f'`{cog.qualified_name}` is already enabled.')
async def disable(self, ctx): """ Disables approve-only mode for build submission on this server. **All builds that were in queue will be approved!** """ await utils.confirm( ctx, 'This action will approve all builds currently in the queue. Are you sure?' ) async with utils.Transaction(self.bot.db) as conn: self.bot.guild_options['builds_channel'] = None await conn.execute( 'UPDATE guilds SET builds_channel = ? WHERE id = ?', (None, ctx.guild.id)) await conn.execute( 'UPDATE builds SET in_queue = 0 WHERE guild_id = ?', (ctx.guild.id, )) await ctx.send('Approve-only mode disabled.')
async def debug(self, ctx, *, string=''): """ Debug command. """ async with utils.Transaction(self.bot.db) as conn: # await conn.execute('ALTER TABLE guilds ADD builds_channel INTEGER') # await conn.execute('ALTER TABLE builds ADD in_queue INTEGER DEFAULT 0') # await conn.execute('CREATE TABLE IF NOT EXISTS stats (id timestamp PRIMARY KEY, stats BLOB)') # await conn.execute(f'ALTER TABLE guilds ADD disabled_commands BLOB') # await conn.execute(f'ALTER TABLE guilds ADD disabled_categories BLOB') # await conn.execute(f'UPDATE guilds SET disabled_commands = ?', (pickle.dumps(set()),)) # await conn.execute(f'UPDATE guilds SET disabled_categories = ?', (pickle.dumps(set()),)) # await conn.execute('ALTER TABLE guilds RENAME TO guilds_orig') # await conn.execute('CREATE TABLE guilds(id INTEGER PRIMARY KEY, prefixes BLOB, builds_channel INTEGER, disabled_commands BLOB, disabled_cogs BLOB)') # await conn.execute('INSERT INTO guilds(id , prefixes, builds_channel, disabled_commands, disabled_cogs) SELECT id , prefixes, builds_channel, disabled_commands, disabled_categories FROM guilds_orig') # await conn.execute('DROP TABLE guilds_orig') # self.bot.guild_options[ctx.guild.id]['disabled_cogs'] = set() pass await ctx.send('Done.')
def check_tx(self, raw_tx): """Validate the Tx before entry into the mempool""" try: # Check txn syntax tx = utils.Transaction(raw_tx) except Exception: return Result.error(log='txn syntax invalid') # Check "sender" account has enough coins if int(self.db.get_address_info(tx.sender)['balance']) < tx.amount: return ResponseCheckTx(log='insufficient funds', code=1) if tx.signature_invalid: # Check txn signature return ResponseCheckTx(log='signature invalid', code=1) if tx.timestamp_invalid: # Check timestamp for a big delay return ResponseCheckTx(log='lag time is more than 2 hours', code=1) # Hooray! return ResponseCheckTx(code=CodeTypeOk)
async def disable_cat(self, ctx, category): """ Disable a category. """ cog = self.bot.get_cog(category.title()) disabled_cogs = self.bot.guild_options[ctx.guild.id]['disabled_cogs'] async with utils.Transaction(self.bot.db) as conn: if cog is None: return await ctx.send('Category not found.') elif cog.qualified_name in ['Options']: return await ctx.send('You cannot disable this category.') elif cog.qualified_name in disabled_cogs: return await ctx.send( f'`{cog.qualified_name}` is already disabled.') disabled_cogs.add(cog.qualified_name) await conn.execute( 'UPDATE guilds SET disabled_cogs = ? WHERE id = ?', (pickle.dumps(disabled_cogs), ctx.guild.id)) await ctx.send(f'`{cog.qualified_name}` disabled.')
async def escape(self, ctx, min_moves=16, max_moves=60): """ An implementation of [Michael Fogleman](https://www.michaelfogleman.com/rush/)'s solved Rush Hour puzzles. - Get the primary piece (represented in red) to the exit. - You may only slide pieces along their length. """ embed = discord.Embed(title='Escape!', description='You find yourself in a strange place...\n\n' 'Escape by getting the primary piece (red) to the exit.\n' 'You may only slide pieces along their length.', color=self.bot.color) async with utils.Transaction(self.bot.rush) as conn: c = await conn.execute('SELECT * FROM puzzles WHERE moves >= ? AND moves <= ? ORDER BY RANDOM() LIMIT 1', (min_moves, max_moves)) row = await c.fetchone() if row is None: return await ctx.send('No level found with specified bounds.') await EscapeMenu(embed, row['moves'], row['setup']).start(ctx)
async def enable_cmd(self, ctx, command): """ Enable a command. """ command = self.bot.get_command(command) disabled_commands = self.bot.guild_options[ ctx.guild.id]['disabled_commands'] async with utils.Transaction(self.bot.db) as conn: if command is None: return await ctx.send('Command not found.') try: disabled_commands.remove(command.qualified_name) await conn.execute( 'UPDATE guilds SET disabled_commands = ? WHERE id = ?', (pickle.dumps(disabled_commands), ctx.guild.id)) await ctx.send(f'`{command.qualified_name}` enabled.') except KeyError: await ctx.send( f'`{command.qualified_name}` is already enabled.')
async def get_prefix(self, message): prefixes = {f'<@!{self.user.id}> ', f'<@{self.user.id}> ' } # Nicknamed mention and normal mention, respectively if message.guild is None: return prefixes | config.default_prefixes else: try: return prefixes | self.guild_options[ message.guild.id]['prefixes'] except KeyError: print('Attempting to fix missing guild...') try: self.guild_options[ message.guild.id] = DEFAULT_GUILD_SETTINGS.copy() async with utils.Transaction(self.db) as conn: await conn.execute( 'INSERT INTO guilds VALUES (?, ?, ?, ?, ?)', (message.guild.id, ) + DEFAULT_GUILD_ROW) return prefixes | self.guild_options[ message.guild.id]['prefixes'] except sqlite3.IntegrityError: pass # rejoining a guild
def process_csv(read_file): if not re.match(r"(.*)\.csv$", read_file): raise ValueError("All files must be given the .csv extension") with open(read_file, "r", newline="") as fp: write_file = re.sub(r"(.*)\.csv", r"\1_output.csv", read_file) analyzer = utils.Analyzer(write_file) reader = csv.reader(fp, dialect="pipes") next(reader) for row in reader: (user_id, _, amount, _, trans_date, trans_type, _) = row user_id = int(user_id) amount = float(amount) trans_date = datetime.fromisoformat(trans_date).date() trans_type = utils.TransactionType.from_str(trans_type) trans = utils.Transaction(amount=amount, transaction_type=trans_type) analyzer.add_transaction(user_id, trans_date, trans) analyzer.write_output()
async def on_ready(self): if not self.bot.started: self.bot.db = await aiosqlite.connect('assets/private/bot.db') self.bot.gameparams = await aiosqlite.connect('assets/private/gameparams.db') self.bot.maplesyrup = await aiosqlite.connect('assets/private/maplesyrup.db') self.bot.rush = await aiosqlite.connect('assets/private/rush.db') self.bot.db.row_factory = dict_factory self.bot.gameparams.row_factory = dict_factory self.bot.maplesyrup.row_factory = dict_factory self.bot.rush.row_factory = aiosqlite.Row async with utils.Transaction(self.bot.db) as conn: # Get guild options c = await conn.execute(f'SELECT * FROM guilds') guilds = await c.fetchall() self.bot.guild_options = {guild['id']: guild for guild in guilds} # Check if bot was invited to new guilds while offline for guild in self.bot.guilds: if guild.id not in self.bot.guild_options: self.bot.guild_options[guild.id] = DEFAULT_GUILD_SETTINGS.copy() await conn.execute('INSERT INTO guilds VALUES (?, ?, ?, ?, ?)', (guild.id,) + DEFAULT_GUILD_ROW) # Get latest row of stats c = await conn.execute('SELECT stats FROM stats ORDER BY stats DESC LIMIT 1') stats = await c.fetchone() self.bot.stats = stats if stats is not None else Counter() self.bot.errors_channel = self.bot.get_channel(ERRORS_CHANNEL_ID) self.bot.mentions_channel = self.bot.get_channel(MENTIONS_CHANNEL_ID) self.bot.started = True print(f'Ready! [{datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")}]\n' f'Name: {self.bot.user} | ID: {self.bot.user.id}')
#!/usr/bin/env python import harvester, sqlite3, utils, sys harvester.CHUNK_SIZE = int(sys.argv[1]) with sqlite3.connect("test.sqlite3", timeout=120, isolation_level=None) as db: db.cursor().execute(""" CREATE TABLE IF NOT EXISTS data (rowid INTEGER PRIMARY KEY) """) for i in range(1): with open("input.log") as f: out = f.read() data = utils.interpret_output(out) with utils.Transaction(db, behavior="IMMEDIATE"): utils.sql_insert_many(db, "data", data)
async def on_guild_join(self, guild): self.bot.guild_options[guild.id] = DEFAULT_GUILD_SETTINGS async with utils.Transaction(self.bot.db) as conn: await conn.execute('INSERT INTO guilds VALUES (?, ?, ?)', (guild.id, ) + DEFAULT_GUILD_SETTINGS)
async def logout(self): async with utils.Transaction(self.db) as conn: await conn.execute('INSERT INTO stats VALUES (?, ?)', (int(time.time()), pickle.dumps(self.stats))) await super().logout()