Beispiel #1
0
    def __init__(self, host="localhost", port=6379, db=0):
        self.log = utilities.getLog("Redis", logging.INFO)

        self.log.info("Connecting to redis...")
        self.__redis = redis.Redis(host=host, port=port, db=db)

        try:
            self.__redis.ping()
        except Exception as e:
            self.log.critical(e)
            exit(1)
Beispiel #2
0
import logging
import traceback
from datetime import datetime, timedelta

import discord.errors
import discord.errors
import pytz
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers import cron
from discord.ext.commands import BucketType
from discord_slash import cog_ext

from source import utilities, dataclass, jsonManager
from source.shared import *

log: logging.Logger = utilities.getLog("Cog::Mute")

del_channel_template = [{
    "channel_id": None,
    "delete_after": None,
}]


class Mute(commands.Cog):
    """Auto Delete Messages in a specified channel"""
    def __init__(self, bot):
        self.bot: dataclass.Bot = bot

        self.emoji = bot.emoji_list

        self.guild_data = {}
Beispiel #3
0
import asyncio
import logging
import os
from datetime import datetime

import discord
from discord_slash import cog_ext
from PIL import Image

from source import dataclass, shared, utilities
from source.shared import *

log: logging.Logger = utilities.getLog("Cog::Log")


class ModLog(commands.Cog):
    """Configuration commands"""
    def __init__(self, bot: dataclass.Bot, s="📬"):
        self.bot = bot

        self.slash = bot.slash

        self.emoji = bot.emoji_list

    async def setup(self):
        """The startup tasks for this cog"""
        self.bot.add_listener(self.on_message, "on_message")
        self.bot.add_listener(self.on_member_join, "on_member_join")
        self.bot.add_listener(self.on_member_remove, "on_member_remove")
        self.bot.add_listener(self.on_member_update, "on_member_update")
        self.bot.add_listener(self.on_message_edit, "on_message_edit")
Beispiel #4
0
import asyncio
import inspect
import traceback
import typing

from source import utilities, shared

log = utilities.getLog("events")


class Event(set):
    def __init__(self, name="DefaultName"):
        super(Event, self).__init__()
        self.name = name

    async def trigger(self, *args, **kwargs):
        for f in self:
            log.debug(f"Calling {f.__name__}")
            try:
                if inspect.iscoroutinefunction(f):

                    await f(*args, **kwargs)
                else:
                    await asyncio.to_thread(f, *args, **kwargs)
            except Exception as e:
                log.error("Ignoring exception in {}: {}".format(
                    f.__name__,
                    "".join(
                        traceback.format_exception(type(e), e,
                                                   e.__traceback__)),
                ))
Beispiel #5
0
import logging
import typing
from datetime import datetime

import discord
from discord.ext import commands
from discord_slash import SlashContext, cog_ext
from discord_slash.utils import manage_commands

from source import utilities, jsonManager, shared, dataclass

log: logging.Logger = utilities.getLog("Cog::uInfo")


class UserInfo(commands.Cog):
    """Gets information about a user"""
    def __init__(self, bot):
        self.bot: dataclass.Bot = bot

        self.emoji = bot.emoji_list

    # todo: add additional user info commands

    @cog_ext.cog_subcommand(**jsonManager.getDecorator("info.user"))
    async def userInfo(self, ctx: SlashContext,
                       user: typing.Union[discord.Member, discord.User]):
        emb = discord.Embed(colour=shared.new_blurple)
        emb.set_thumbnail(url=user.avatar_url)
        emb.description = ""

        # get db data on user
Beispiel #6
0
    except Exception as e:
        print(e)
        return False
    return True


def main():
    from source import bot

    log.info("Ready, calling bot.py")
    bot.run()


if __name__ == "__main__":
    logo = r"""
__________        .__              .___.__        
\______   \_____  |  | _____     __| _/|__| ____  
 |     ___/\__  \ |  | \__  \   / __ | |  |/    \ 
 |    |     / __ \|  |__/ __ \_/ /_/ | |  |   |  \
 |____|    (____  /____(____  /\____ | |__|___|  /
                \/          \/      \/         \/ """

    logo = logo.replace("r", "\033[0m")
    logo = logo.replace("c", "\033[96m")
    print(logo)
    sleep(1)
    sanityChecks()
    log = utilities.getLog("Main")
    log.info("Logging system started")
    main()
Beispiel #7
0
import logging

from discord.ext import commands
from discord_slash import SlashContext, cog_ext
from discord_slash.utils import manage_commands

from source import utilities, dataclass, messageObject

log: logging.Logger = utilities.getLog("Cog::mail")


class ModMail(commands.Cog):
    """Configuration commands"""
    def __init__(self, bot: dataclass.Bot, s="📬"):
        self.bot = bot

        self.slash = bot.slash

        self.emoji = s

    @cog_ext.cog_subcommand(
        base="mail",
        name="send",
        description="Send a message to your moderators",
        options=[
            manage_commands.create_option(
                name="content",
                description="The content of your message",
                option_type=str,
                required=True,
            ),
Beispiel #8
0
import logging

import aiohttp
import discord
from discord.ext import commands

from source import utilities, dataclass

log: logging.Logger = utilities.getLog("Cog::base")


class Base(commands.Cog):
    """Configuration commands"""
    def __init__(self, bot: dataclass.Bot):
        self.bot = bot

        self.slash = bot.slash

        self.emoji = "🚩"

    @commands.command(name="Shutdown", brief="Shuts down the bot")
    async def cmdShutdown(self, ctx: commands.Context):
        if await self.bot.is_owner(ctx.author):
            log.warning("Shutdown called")
            await ctx.send("Shutting down 🌙")
            await self.bot.close()

    @commands.command(name="setname", brief="Renames the bot")
    async def cmdSetName(self, ctx: commands.Context, name: str):
        if await self.bot.is_owner(ctx.author):
            await self.bot.user.edit(username=name)
Beispiel #9
0
import asyncio
import json
import typing

from source import dataclass, utilities

log = utilities.getLog("message")


class Message:
    def __init__(self, bot: dataclass.Bot, guild_id: int = 0, author_id: int = 0):
        # a ref to the bot
        self.bot = bot
        # a ref to the bot's db client
        self.db = bot.db
        # the message id
        self._message_id = None
        # is this message open?
        self.open: bool = True
        # the guild this message belongs to
        self.guildID: int = guild_id
        # the author of this message
        self.authorID: int = author_id
        # the title of this message
        self.title: typing.Union[None, str] = None
        # the content of this message
        self.content: typing.Union[None, str] = None

    def __eq__(self, other):
        if isinstance(other, Message):
            if self._message_id == other._message_id:
Beispiel #10
0
import json
import logging
import time
import traceback
import typing

import discord
from discord.ext import commands, tasks
from discord_slash import cog_ext, SlashContext
from discord_slash.utils import manage_commands
from twitchAPI import Twitch as TwitchAPI
from twitchAPI.types import TwitchAuthorizationException

from source import utilities, dataclass

log: logging.Logger = utilities.getLog("Cog::twitch")


class SetEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, set):
            return list(obj)
        return json.JSONEncoder.default(self, obj)


class Twitch(commands.Cog):
    """Configuration commands"""
    def __init__(self, bot: dataclass.Bot):
        self.bot = bot

        self.slash = bot.slash
Beispiel #11
0
import logging
import typing
from datetime import datetime

import discord
from discord.ext import commands
from discord_slash import SlashContext, cog_ext
from discord_slash.utils import manage_commands

from source import utilities, pagination, jsonManager, shared

log: logging.Logger = utilities.getLog("Cog::lsPerms")


class ListPermissions(commands.Cog):
    """List Permissions for a specified user/role"""
    def __init__(self, bot):
        self.bot = bot

        self.emoji = bot.emoji_list

        self.paginator = pagination.LinePaginator(prefix="", suffix="")

    @cog_ext.cog_subcommand(
        base="permissions",
        name="get",
        description="Get the permissions of a role or user",
        base_default_permission=True,
        options=[
            manage_commands.create_option(
                name="scope",
Beispiel #12
0
import logging
import re
import typing

import discord
from discord.ext import commands
from discord_slash import cog_ext, SlashContext
from discord_slash.utils import manage_commands

from source import utilities, dataclass, shared

log: logging.Logger = utilities.getLog("Cog::LinkDetect")


class LinkDetection(commands.Cog):
    """Configuration commands"""
    def __init__(self, bot):
        self.bot: dataclass.Bot = bot

        self.emoji = bot.emoji_list

        self.bot.add_listener(self.on_message, "on_message")

    async def on_message(self, message: discord.Message):
        if message.author.id == self.bot.user.id:
            return

        discord_invite = "discord.gg/(.*)"
        bot_invite = "(discord|discordapp).com(/api/|/)oauth2/authorize\?client_id=(\d{18})"
        generic_url = "((http|ftp|https)://|[\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])(.*)"
Beispiel #13
0
import logging
import re
import traceback
import typing

import discord
from discord.ext import commands
from discord_slash import cog_ext, SlashContext, model
from discord_slash.utils import manage_commands

from source import utilities, dataclass, shared

log: logging.Logger = utilities.getLog("Cog::Config")


class Config(commands.Cog):
    """Configuration commands"""
    def __init__(self, bot):
        self.bot: dataclass.Bot = bot

        self.emoji = bot.emoji_list

    @cog_ext.cog_subcommand(
        base="guild",
        name="get_config",
        description="Show the current config for this server",
        base_default_permission=True,
    )
    async def get_guild_config(self, ctx: SlashContext):
        await ctx.defer()
Beispiel #14
0
import asyncio
import json
import logging
import traceback
from datetime import datetime, timedelta

from discord.ext import tasks
from discord.utils import snowflake_time
from discord_slash import cog_ext

from source import utilities, dataclass, jsonManager
from source.shared import *

log: logging.Logger = utilities.getLog("Cog::AutoDel")

del_channel_template = [{
    "channel_id": None,
    "delete_after": None,
}]


class AutoDelete(commands.Cog):
    """Auto Delete Messages in a specified channel"""
    def __init__(self, bot):
        self.bot: dataclass.Bot = bot

        self.emoji = bot.emoji_list

        self.events = self.bot.paladinEvents

    async def setup(self):
Beispiel #15
0
import logging

from discord_slash import cog_ext

from source import utilities, dataclass, jsonManager, shared
from source.shared import *

log: logging.Logger = utilities.getLog("Cog::warn")


class UserWarnings(commands.Cog):
    """Configuration commands"""
    def __init__(self, bot: dataclass.Bot):
        self.bot: dataclass.Bot = bot

        self.slash = bot.slash

        self.emoji = bot.emoji_list

    @cog_ext.cog_subcommand(**jsonManager.getDecorator("add.warn.user"))
    async def warnCMD(
        self,
        ctx: SlashContext,
        user: typing.Union[discord.User, discord.Member],
        reason: str = None,
    ):
        """Warns a user, 3 warnings and the user will be kicked"""
        await ctx.defer()
        user_data = await self.bot.get_member_data(ctx.guild_id, user.id)
        warning_num = int(user_data.warnings) + 1
Beispiel #16
0
import json
import os
import logging
from pprint import pprint

from discord_slash.utils import manage_commands

from source import utilities
from source.shared import reasonOption

log = utilities.getLog("slashParser", level=40)

path = "data/commands/"


def read(name: str):
    """Read a json file and returns its information"""
    log.debug(f"Reading {name} from json")
    _path = path + f"{name}.json"
    if not os.path.isfile(_path):
        log.error(f"{_path} does not exist")
        raise FileNotFoundError

    data = json.load(open(_path, "r"))
    return data


def getDecorator(name: str):
    """Get the decorator data for a command"""
    return read(name)["decorator"]