Ejemplo n.º 1
0
def main():
    logging.basicConfig(
        level=logging.DEBUG if Config()["DEBUG"] else logging.INFO)
    Bot(Config()["TELEGRAM_API_TOKEN"])
    from bot import start
    from bot import splitit
    aiogram.executor.start_polling(Bot().dispatcher, skip_updates=True)
Ejemplo n.º 2
0
    async def censor(self, ctx, *, word: Optional[str] = None) -> None:
        """
		Censors many words
		"""

        # Syntax check
        if word is None:
            await ctx.send("**Invalid syntax**. `!censor word`")
            return

        words = word.split(" ")
        for w in words:
            # Make sure the word is not already censored
            w = w.lower()
            async with Bot().censored_words_db() as db:
                db_word = db.search(Query().word == w)
            if db_word:
                await ctx.send(f"**{w}** is already censored!")
                continue

            # Censor new word
            async with Bot().censored_words_db() as db:
                db.insert({"word": w})

            # Bot's reply
            await ctx.send(f"**{w}** is now censored!")
Ejemplo n.º 3
0
    async def uncensor(self, ctx, *, word: Optional[str] = None) -> None:
        """
		Uncensors many words
		"""

        # Syntax check
        if word is None:
            await ctx.send("**Invalid syntax**. `!uncensor word`")
            return

        # Make sure the word is censored
        for w in word.split(" "):
            w = w.lower()
            async with Bot().censored_words_db() as db:
                db_word = db.search(Query().word == w)
            if not db_word:
                await ctx.send(f"**{w}** is not censored!")
                continue

            # Uncensor word
            async with Bot().censored_words_db() as db:
                db.remove(Query().word == w)

            # Bot's reply
            await ctx.send(f"**{w}** isn't censored anymore!")
Ejemplo n.º 4
0
    async def on_message(self, message: discord.Message) -> None:
        # Don't do anything in private messages or for messages sent in other servers
        if type(message.channel) is not discord.TextChannel \
          or message.channel.guild.id not in Bot().allowed_server_ids \
          or message.author == self.bot.user:
            return

        # Process commands
        # try:
        # 	await self.bot.process_commands(message)
        # except discord.ext.commands.errors.CheckFailure:
        # 	pass

        # Censor only for non-admins
        if not message.author.bot and not checks.is_admin(message):
            async with Bot().censored_words_db() as db:
                banned_words = set(x["word"] for x in db.all())
            message_words = message.content.lower()
            for banned_word in banned_words:
                if banned_word in message_words:
                    await message.delete()
                    Bot().logger.info(
                        f"Deleted message from {message.author.name} [{message.author.id}] ({message.content})"
                    )
                    await Bot().log(
                        f"**Deleted message from {message.author.mention}:** "
                        f"`{message.clean_content.replace('`', '')}`")
Ejemplo n.º 5
0
	async def on_message(self, message: discord.Message) -> None:
		if message.channel.id != Bot().reports_user_channel_id \
				or message.author == self.bot.user:
			return
		e = discord.Embed(
			title="New Player Report Received!",
			colour=discord.Colour.from_rgb(*(random.randint(0, 255) for _ in range(3))),
			timestamp=datetime.now()
		).set_thumbnail(
			url=message.author.avatar_url
		).add_field(
			name="Author", value=message.author.mention, inline=False
		).add_field(
			name="Report", value=message.content, inline=False
		)
		admin_message = await self.bot.get_channel(Bot().reports_admin_channel_id).send(embed=e)

		async def add_emojis():
			for x in ("👍", "👎", "❗"):
				await admin_message.add_reaction(x)
		asyncio.ensure_future(add_emojis())

		await message.delete()
		await message.author.send(
			f"Hey there, {message.author}! Thank you for your report. "
			"It will be reviewed by the Ripple Community Managers soon!",
			embed=e
		)
Ejemplo n.º 6
0
def main():
    # Read config
    conf = Config().config

    # Connect to MySQL
    asyncio.get_event_loop().run_until_complete(Db().create(
        host=conf["DB_HOST"],
        port=conf["DB_PORT"],
        username=conf["DB_USERNAME"],
        password=conf["DB_PASSWORD"],
        database=conf["DB_DATABASE"],
        maxsize=conf["DB_POOL_SIZE"]))

    # Initialize sentry
    if Config().config["SENTRY_DSN"] != "":
        SentryClient(conf["SENTRY_DSN"],
                     enable_breadcrumbs=True,
                     transport=ThreadedHTTPTransport,
                     string_max_length=8192)
    else:
        print("Sentry logging disabled")

    # Initialize bot
    bot = Bot(conf["TELEGRAM_API_TOKEN"])

    from commands import start
    from commands import meme
    from commands import chatid
    from commands import callback

    print("Click da circlez")
    bot.run()
Ejemplo n.º 7
0
def main() -> None:
    # Logging
    logging.basicConfig(
        level=logging.DEBUG if Config()["DEBUG"] else logging.INFO)
    logging.info("""
      __      _                                   
     / _|    | |                                  
    | |_ ___ | | ____ ___      _____   ___   ___  
    |  _/ _ \\| |/ / _` \\ \\ /\\ / / _ \\ / _ \\ / _ \\ 
    | || (_) |   < (_| |\\ V  V / (_) | (_) | (_) |
    |_| \\___/|_|\\_\\__,_| \\_/\\_/ \\___/ \\___/ \\___/ 
    """)

    # Setup Bot singleton
    if use_uvloop:
        uvloop.install()
        logging.info("Using uvloop")
    else:
        logging.warning("Using asyncio")
    Bot(
        wss=Config()["WSS"],
        nickname=Config()["BOT_NICKNAME"],
        commands_prefix=Config()["COMMANDS_PREFIX"],
        bancho_api_client=BanchoApiClient(Config()["BANCHO_API_TOKEN"],
                                          Config()["BANCHO_API_BASE"]),
        ripple_api_client=RippleApiClient(Config()["RIPPLE_API_TOKEN"],
                                          Config()["RIPPLE_API_BASE"]),
        lets_api_client=LetsApiClient(Config()["LETS_API_BASE"]),
        cheesegull_api_client=CheesegullApiClient(
            Config()["CHEESEGULL_API_BASE"]),
        osu_api_client=OsuAPIClient(Config()["OSU_API_TOKEN"]),
        misirlou_api_client=MisirlouApiClient(
            Config()["MISIRLOU_API_TOKEN"],
            Config()["MISIRLOU_API_BASE"],
        ),
        http_host=Config()["HTTP_HOST"],
        http_port=Config()["HTTP_PORT"],
        redis_host=Config()["REDIS_HOST"],
        redis_port=Config()["REDIS_PORT"],
        redis_database=Config()["REDIS_DATABASE"],
        redis_password=Config()["REDIS_PASSWORD"],
        redis_pool_size=Config()["REDIS_POOL_SIZE"],
        tinydb_path=Config()["TINYDB_PATH"],
    )
    # Register all events
    import events

    # Import all required plugins (register bot commands)
    for plugin in Config()["BOT_PLUGINS"]:
        imported_plugin = importlib.import_module(f"plugins.{plugin}")
        if hasattr(imported_plugin, "init"):
            logging.debug(f"Plugin {plugin} has init hook.")
            Bot().init_hooks.append(
                InitHook(plugin, getattr(imported_plugin, "init")))
        Bot().logger.info(f"Loaded plugin plugins.{plugin}")

    # Finally, run the bot
    Bot().run()
Ejemplo n.º 8
0
async def last(request):
    resp = {}
    try:
        secret = request.headers.get("Secret", None)
        if secret is None or secret != Config()["INTERNAL_API_SECRET"]:
            raise FokaAPIError(403, "Forbidden")
        request_data = await request.json()
        if "user_id" not in request_data:
            raise FokaAPIError(400, "Missing required arguments.")
        users = await Bot().ripple_api_client.get_user(
            user_id=request_data["user_id"])
        if users is None or not users:
            raise FokaAPIError(404, "No such user")
        username = users[0]["username"]
        msg = await pp.last_inner(username, pm=True)
        Bot().send_message(msg, username)
        resp = {"code": 200, "message": "ok"}
    except FokaAPIError as e:
        resp = {"code": e.status, "message": e.message}
    except:
        resp = {"code": 500, "message": "Internal server error"}
        traceback.print_exc()
    finally:
        code = resp["code"] if "code" in resp else 200
        return web.json_response(resp, status=code)
Ejemplo n.º 9
0
    async def censoredwords(self, ctx) -> None:
        """
		Lists all currently censored words
		"""

        async with Bot().censored_words_db() as db:
            results = db.all()
        await ctx.send("**Censored words:** {}".format(", ".join(
            x["word"] for x in results)))
Ejemplo n.º 10
0
async def send_message(request):
    resp = {}
    try:
        secret = request.headers.get("Secret", None)
        if secret is None or secret != Config()["INTERNAL_API_SECRET"]:
            raise FokaAPIError(403, "Forbidden")
        request_data = await request.json()
        if "message" not in request_data or "target" not in request_data:
            raise FokaAPIError(400, "Missing required arguments.")
        Bot().send_message(request_data["message"], request_data["target"])
        resp = {"code": 200, "message": "ok"}
    except FokaAPIError as e:
        resp = {"code": e.status, "message": e.message}
    except:
        resp = {"code": 500, "message": "Internal server error"}
        traceback.print_exc()
    finally:
        code = resp["code"] if "code" in resp else 200
        return web.json_response(resp, status=code)
Ejemplo n.º 11
0
import plugins.base
import utils
from constants.mods import Mod, ModSpecialMode
from constants.scoring_types import ScoringType
from constants.team_types import TeamType
from constants.teams import Team
from plugins.base import Arg
from constants.privileges import Privileges
from singletons.bot import Bot
from utils import general, schema
from utils.rippleapi import BanchoApiBeatmap
from constants.slot_statuses import SlotStatus
from constants.game_modes import GameMode

bot = Bot()


def resolve_mp(f: Callable) -> Callable:
    async def wrapper(*, recipient: Dict[str, Any], **kwargs):
        assert recipient["display_name"] == "#multiplayer"
        match_id = int(recipient["name"].split("_")[1])
        return await f(match_id=match_id, recipient=recipient, **kwargs)

    return wrapper


@bot.command("mp make")
@plugins.base.protected(Privileges.USER_TOURNAMENT_STAFF)
@plugins.base.arguments(
    plugins.base.Arg("name", Schema(str)),
Ejemplo n.º 12
0
from singletons.config import Config

if __name__ == "__main__":
    logging.getLogger("discord").setLevel(logging.ERROR)
    logging.basicConfig(level=logging.INFO)
    logging.info("""\n
     _         _   _             
 ___| |_ ___ _| |_| |___ _ _ _ _ 
| . |   | -_| . | . | .'| | |_'_|
|_  |_|_|___|___|___|__,|___|_,_|
|___|                            
      Gheddaux - Made by Nyo""")
    bot = Bot(command_prefix=";",
              allowed_server_ids=Config()["SERVER_IDS"],
              log_channel_id=Config()["LOG_CHANNEL_ID"],
              welcome_channel_id=Config()["WELCOME_CHANNEL_ID"],
              reports_user_channel_id=Config()["REPORTS_USER_CHANNEL_ID"],
              reports_admin_channel_id=Config()["REPORTS_ADMIN_CHANNEL_ID"],
              db_file=Config()["DB_FILE"]).bot

    @bot.event
    async def on_command_error(ctx, exception) -> None:
        # I don't even want to know why the f**k I have to do this in the first place
        try:
            raise exception
        except:
            Bot().logger.exception("An unhandled exception has been raised.")

    if Bot().welcome_channel_id:
        bot.add_cog(Welcome(bot))
    else:
Ejemplo n.º 13
0
 async def on_command_error(ctx, exception) -> None:
     # I don't even want to know why the f**k I have to do this in the first place
     try:
         raise exception
     except:
         Bot().logger.exception("An unhandled exception has been raised.")
Ejemplo n.º 14
0
def is_server_allowed(message: discord.Message) -> bool:
    return message.channel.guild.id in Bot().allowed_server_ids
Ejemplo n.º 15
0
async def handle(data: Dict[str, Any]) -> None:
    Bot().send_message(data["message"], data["recipient"])
Ejemplo n.º 16
0
from typing import Dict, Any

import pubsub
from singletons.bot import Bot
from utils.schema import NonEmptyString

bind = Bot().pubsub_binding_manager


@bind.register_pubsub_handler("fokabot:message")
@pubsub.schema({"recipient": NonEmptyString, "message": NonEmptyString})
async def handle(data: Dict[str, Any]) -> None:
    Bot().send_message(data["message"], data["recipient"])
Ejemplo n.º 17
0
    print("=> Connecting to database")

    # Connect to database and create table if needed
    await Database().connect(Config()["DB_DSN"], loop=asyncio.get_event_loop())
    await Database().execute("""
CREATE TABLE IF NOT EXISTS `banned_words` (
    `id`	INTEGER PRIMARY KEY AUTOINCREMENT,
    `word`	TEXT UNIQUE
);""")

    # Load forbidden words
    await WordsCache().reload()


# Initialize some variables for decorators
bot = Bot(command_prefix=";")


@bot.event
async def on_ready():
    print("=> Logged in as {} [{}]. Ready!".format(bot.user.name, bot.user.id))


@bot.event
async def on_message(message):
    # Don't do anything in private messages
    if message.server is None:
        return

    # Process commands
    try: