Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def dict_factory(cursor, row):
"""Makes values returned by cursor fetch functions return a dictionary instead of a tuple.
To implement this, the connection's row_factory method must be replaced by this one."""
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
class LootScanException(commands.CommandError):
pass
class Loot(commands.Cog, CogUtils):
def __init__(self, bot: NabBot):
self.bot = bot
self.processing_users = []
if not os.path.isfile(LOOTDB):
raise FileNotFoundError("Couldn't find loot database. Can't start cog.")
self.loot_conn = sqlite3.connect(LOOTDB)
self.loot_conn.row_factory = dict_factory
@checks.can_embed()
@commands.group(invoke_without_command=True, case_insensitive=True)
async def loot(self, ctx: NabCtx):
"""Scans an image of a container looking for Tibia items and shows an approximate loot value.
An image must be attached with the message. The prices used are NPC prices only.
The image requires the following:
continue
importance.append((gear, important))
importance.sort(key=lambda t: t[1], reverse=True)
if len(importance) == 0:
raise commands.BadArgument('Could not find anything.')
top, score = importance[0]
if score == 100:
return [top]
return [g for g, _ in importance]
class Splatoon(commands.Cog):
"""Splatoon related commands."""
BASE_URL = yarl.URL('https://app.splatoon2.nintendo.net')
def __init__(self, bot):
self.bot = bot
self.splat2_data = config.Config('splatoon2.json', loop=bot.loop,
object_hook=splatoon2_decoder, encoder=Splatoon2Encoder)
self.map_data = []
self._splatnet2 = bot.loop.create_task(self.splatnet2())
self._authenticator = bot.loop.create_task(self.splatnet2_authenticator())
self._is_authenticated = asyncio.Event(loop=bot.loop)
# mode: List[Rotation]
self.sp2_map_data = {}
import sys
import datetime
import pyowm.exceptions
from utilities import checks
sys.path.insert(0, "..")
from units.location import get_geocode_data, get_timezone_data, wind_degrees_to_direction, UnitOutputError
sys.path.pop(0)
def setup(bot):
bot.add_cog(Location(bot))
class Location(commands.Cog):
'''
Commands regarding locations
Also see Random cog for random location commands
'''
def __init__(self, bot):
self.bot = bot
# TODO: handle random location command
@commands.command()
@checks.not_forbidden()
async def country(self, ctx, *, country : str):
'''Information about a country'''
# TODO: subcommands for other options to search by (e.g. capital)
@commands.Cog.listener()
async def on_member_join(self, member):
await member.add_roles(self.bot.roles['Probation'], reason="Auto Probation")
HTML_COLOURS = json.load(f)
with open(Path("bot/resources/evergreen/xkcd_colours.json")) as f:
XKCD_COLOURS = json.load(f)
COLOURS = [
(255, 0, 0, 255), (255, 128, 0, 255), (255, 255, 0, 255), (0, 255, 0, 255),
(0, 255, 255, 255), (0, 0, 255, 255), (255, 0, 255, 255), (128, 0, 128, 255)
] # Colours to be replaced - Red, Orange, Yellow, Green, Light Blue, Dark Blue, Pink, Purple
IRREPLACEABLE = [
(0, 0, 0, 0), (0, 0, 0, 255)
] # Colours that are meant to stay the same - Transparent and Black
class EggDecorating(commands.Cog):
"""Decorate some easter eggs!"""
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@staticmethod
def replace_invalid(colour: str) -> Union[int, None]:
"""Attempts to match with HTML or XKCD colour names, returning the int value."""
with suppress(KeyError):
return int(HTML_COLOURS[colour], 16)
with suppress(KeyError):
return int(XKCD_COLOURS[colour], 16)
return None
@commands.command(aliases=["decorateegg"])
async def eggdecorate(
import emoji
import pydealer
import pyparsing
import clients
from modules import utilities
from utilities import checks
def setup(bot):
cog = Random(bot)
bot.add_cog(cog)
# Add fact subcommands as subcommands of corresponding commands
for command, parent in ((cog.fact_cat, cog.cat), (cog.fact_date, cog.date), (cog.fact_number, cog.number)):
utilities.add_as_subcommand(cog, command, parent, "fact", aliases = ["facts"])
class Random(commands.Cog):
def __init__(self, bot):
self.bot = bot
# Add commands as random subcommands
for name, command in inspect.getmembers(self):
if isinstance(command, commands.Command) and command.parent is None and name != "random":
self.bot.add_command(command)
self.random.add_command(command)
# Add random subcommands as subcommands of corresponding commands
self.random_subcommands = ((self.blob, "Blobs.blobs"), (self.color, "Resources.color"),
(self.giphy, "Images.giphy"), (self.map, "Location.map"),
(self.photo, "Images.image"), (self.streetview, "Location.streetview"),
(self.time, "Location.time"), (self.uesp, "Search.uesp"),
(self.user, "User.user"), (self.wikipedia, "Search.wikipedia"),
(self.xkcd, "Resources.xkcd"))
for command, parent_name in self.random_subcommands:
farm_conditions = response_json['anti_bot_farm']['leave_guild_if']
del response_json
def farm_check(guild):
if guild.member_count > farm_conditions['min_member_count']:
bots = [member for member in guild.members if member.bot]
result = (len(bots) / guild.member_count) * 100
if result > farm_conditions['min_bot_rate']:
return True
else:
return False
else:
return False
class AntiFarm(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
for guild in self.bot.guilds:
if farm_check(guild):
await guild.leave()
@commands.Cog.listener()
async def on_guild_join(self, guild):
if farm_check(guild):
await guild.leave()
@commands.Cog.listener()
async def on_member_join(self, member):
import discord
from discord.ext import commands
from roombot.database.room import Room
from roombot.database.settings import Settings
from roombot.utils.functions import load_cog, pop_flags, iter_len
from roombot.utils.text import langs, get_text
from roombot.utils.pagesembed import FieldPagesEmbed
class Admin(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.color = discord.Color.red()
async def cog_check(self, ctx):
return ctx.message.author.guild_permissions.administrator
async def cog_command_error(self, ctx, error):
if type(error) == discord.ext.commands.errors.CheckFailure:
settings = Settings.get_for(ctx.guild.id)
await ctx.send(settings.get_text('not_admin'))
@commands.command()
@commands.guild_only()
async def reset_settings(self, ctx):
self.title = data.get('title')
self.url = data.get('url')
@classmethod
async def from_url(cls, url, *, loop=None):
loop = loop or asyncio.get_event_loop()
data = await loop.run_in_executor(
None, lambda: ytdl.extract_info(url, download=False))
if 'entries' in data:
data = data['entries'][0]
filename = data["url"]
return cls(
discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
class Music(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.states = {}
def __unload(self):
for state in self.states.values():
self.bot.loop.create_task(self.stop_playing(state.guild))
@commands.command(usage="")
async def play(self, ctx, *, url):
"""Play a song,
Supported sites include youtube and most other video streaming sites"""
await self.enqueue(ctx, url)
@commands.command(name="queue")
import discord
import re
from discord.ext import commands
class NXErr(commands.Cog):
"""
Parses NX (Nintendo Switch) error codes.
Uses http://switchbrew.org/index.php?title=Error_codes
"""
def __init__(self, bot):
self.bot = bot
print(f'Cog "{self.qualified_name}" loaded')
# Modules
modules = {
1: "Kernel ",
2: "FS ",
3: "OS (Memory, Thread, Mutex, NVIDIA) ",
4: "HTCS ",
5: "NCM ",
6: "DD ",