Esempio n. 1
0
import lightbulb
import hikari
import humanize

import datetime as dt
import typing as t
from textwrap import dedent

import utilities.helpers as helpers
from utilities.navigator import ButtonPages

plugin = lightbulb.Plugin("Core",
                          description="General Commands",
                          include_datastore=True)
plugin.d.emote = helpers.get_emote(":gear:")


@plugin.command()
@lightbulb.command("changelog", "Show 10 latest changes to the bot.")
@lightbulb.implements(lightbulb.PrefixCommandGroup,
                      lightbulb.SlashCommandGroup)
async def changelog_base(ctx: lightbulb.Context):
    '''
    Show 10 latest changes to the bot.
    '''
    await changelog_stable(ctx)


@changelog_base.child
@lightbulb.command("stable", "Show 10 latest changes to the bot.")
@lightbulb.implements(lightbulb.PrefixSubCommand, lightbulb.SlashSubCommand)
Esempio n. 2
0
from sqlalchemy import alias, func, not_, orm
from utils.db import Problem as Problem_DB, Contest as Contest_DB, User as User_DB, Submission as Submission_DB
from utils.jomd_common import is_int, calculate_points, PointRangeConverter, gimme_common
from utils.api import ObjectNotFound
from utils.constants import SITE_URL, TZ, SHORTHANDS
import asyncio
import random
from operator import itemgetter
import logging
from lightbulb.converters import base
from lightbulb.commands.base import OptionModifier
from lightbulb.utils import nav

logger = logging.getLogger(__name__)

plugin = lightbulb.Plugin("User")


class StrNotIntConverter(base.BaseConverter[str]):
    """Implementation of the base converter for converting arguments into a point range."""

    __slots__ = ()

    async def convert(self, arg: str) -> str:
        if is_int(arg):
            raise TypeError("This is an integer")  # kevinyang theorem
        return arg


@plugin.command()
@lightbulb.option("amount", "List last N submissions", int, required=False)
Esempio n. 3
0
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

from extensions.utility import commands
from lib import client

import lightbulb
import sys

plugin = lightbulb.Plugin("Utility")
plugin.command(commands.ping)
plugin.command(commands.userinfo)
plugin.command(commands.about)
plugin.command(commands.avatar)


def load(bot: client.Requiem):
    bot.add_plugin(plugin)


def unload(bot: client.Requiem):
    bot.remove_plugin(plugin)
    del sys.modules[commands.__name__]
# 3rd-party imports.
# Import any libraries that are not standard and not your code.
import lightbulb
import hikari

# Standard imports.
# Import std python libraries here.
import datetime as dt

# Utilities
# It's recommended to shorten their names to not include "utilities"
import utilities.helpers as helpers

# Create a category
plugin = lightbulb.Plugin("Category's name", include_datastore=True)
plugin.d.emote = helpers.get_emote("")


# Create a command
# Order of decorator is bottom-up.
@plugin.command()
@lightbulb.add_checks(...)
@lightbulb.option("arg2", "Description", modifier=helpers.CONSUME_REST_OPTION)
@lightbulb.option("arg1", "Description")
@lightbulb.command("Command's name", "Description")
@lightbulb.implements(lightbulb.PrefixCommand, lightbulb.SlashCommand)
async def slash_cmd(ctx: lightbulb.Context):
    # If it is a simple one-line command then it's not worth it to do this,
    # but you should explicitly declare arguments to shorten the ctx.options.
    arg1 = ctx.options.arg1
    arg2 = ctx.options.arg2
Esempio n. 5
0
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

from extensions.management import commands
from lib import client

import lightbulb
import sys

plugin = lightbulb.Plugin("Management")
plugin.add_checks(lightbulb.owner_only)
plugin.command(commands.terminate)
plugin.command(commands.reload)
plugin.command(commands.load)
plugin.command(commands.unload)


def load(requiem: client.Requiem):
    requiem.add_plugin(plugin)


def unload(requiem: client.Requiem):
    requiem.remove_plugin(plugin)
    del sys.modules[commands.__name__]
Esempio n. 6
0
from utils.graph import plot_type_radar, plot_type_bar, plot_rating, plot_points, plot_solved
from utils.jomd_common import calculate_points
from lightbulb.commands.base import OptionModifier
from operator import attrgetter, itemgetter
from sqlalchemy import or_, orm, func
import asyncio
import io
import bisect
import logging
from lightbulb.converters import base


logger = logging.getLogger(__name__)


plugin = lightbulb.Plugin("Plot")


class PeakConverter(base.BaseConverter[str]):
    """Implementation of the base converter for converting arguments into a peak arguement."""

    __slots__ = ()

    async def convert(self, arg: str) -> str:
        if arg == "+peak":
            return True
        if arg == "+max":
            return True
        raise TypeError("Argument not known")

Esempio n. 7
0

def has_any_role_names(role_names: t.List[str]) -> bool:
    def _has_any_role_names(ctx: lightbulb.Context, *, role_names: t.List[str]):
        assert ctx.member is not None

        if any(role.name in role_names for role in ctx.member.get_roles()):
            return True
        raise lightbulb.errors.MissingRequiredRole(
            "You are missing the roles required in order to run this command %s" % role_names
        )

    return lightbulb.Check(functools.partial(_has_any_role_names, role_names=role_names))


plugin = lightbulb.Plugin("Handles")


@plugin.command()
@lightbulb.option(
    "handle",
    "Dmoj handle",
    str,
    required=False,
    default=None,
)
@lightbulb.option("member", "Discord user", hikari.Member, required=False, default=None)
@lightbulb.command("whois", "Lookup linked account")
@lightbulb.implements(lightbulb.PrefixCommand, lightbulb.SlashCommand)
async def whois(ctx):
    member = ctx.options.member
Esempio n. 8
0
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

from extensions.verins_lunchbox import commands
from lib import client

import lightbulb
import sys

plugin = lightbulb.Plugin("VerinsLunchbox")
plugin.command(commands.neko)
plugin.command(commands.foxgirl)


def load(bot: client.Requiem):
    bot.add_plugin(plugin)


def unload(bot: client.Requiem):
    bot.remove_plugin(plugin)
    del sys.modules[commands.__name__]
Esempio n. 9
0
)
from utils.query import Query
from utils.api import ObjectNotFound
import hikari
import lightbulb
import typing as t
from datetime import datetime, timezone
from sqlalchemy import orm
import asyncio
from lightbulb.utils import nav
from operator import itemgetter, attrgetter
import logging

logger = logging.getLogger(__name__)

plugin = lightbulb.Plugin("Admin")

# TODO: Post new contests
# Rating change predictions for all users in a server


@plugin.command()
@lightbulb.option(
    "args", "[+server, +all, dmoj_handles]", str, required=False, modifier=lightbulb.OptionModifier.GREEDY, default=[]
)
@lightbulb.option("key", "contest key", str)
@lightbulb.command("ranklist", "List rating predictions of a contest", aliases=["contest"])
@lightbulb.implements(lightbulb.PrefixCommand)
async def ranklist(ctx):
    """List rating predictions of a contest"""
    key = ctx.options.key
Esempio n. 10
0
    CurrentGitgud as CurrentGitgud_DB,
    Json,
)
import lightbulb
from lightbulb.converters import base
from lightbulb.commands.base import OptionModifier
import hikari
from lightbulb.utils import nav
from datetime import datetime
from sqlalchemy import func
import logging

logger = logging.getLogger(__name__)


plugin = lightbulb.Plugin("GitGud")


@plugin.command()
@lightbulb.option("filters", "Problem filters", str, required=False, modifier=OptionModifier.GREEDY, default=[])
@lightbulb.option(
    "points",
    "point range, e.g. ('1', '1-10') DOES NOT WORK WITH SLASH COMMANDS",
    PointRangeConverter,
    required=False,
    default=None,
)
@lightbulb.set_help(
    """SHORTHANDS:
    - adhoc
    - math
Esempio n. 11
0
import lightbulb
import hikari

import utilities.helpers as helpers
from utilities.checks import is_dev

plugin = lightbulb.Plugin("Secret", "Developer-only commands.", include_datastore = True)
plugin.d.emote = helpers.get_emote(":computer:")

plugin.add_checks(is_dev)

@plugin.set_error_handler()
async def on_plugin_error(event: lightbulb.CommandErrorEvent) -> bool:
    exception = event.exception.__cause__ or event.exception

    if isinstance(exception, lightbulb.BotMissingRequiredPermission):
        pass
    elif isinstance(exception, lightbulb.MissingRequiredPermission):
        pass
    elif isinstance(exception, lightbulb.CheckFailure):
        exception.message = "`Author must be a MichaelBot developer`"
    
    return False

@plugin.command()
@lightbulb.option("extension", "The extension to reload.")
@lightbulb.command("reload", "Reload an extension.", hidden = True)
@lightbulb.implements(lightbulb.PrefixCommand, lightbulb.SlashCommand)
async def reload(ctx: lightbulb.Context):
    ctx.bot.reload_extensions(ctx.options.extension)
    await ctx.respond(f"Reloaded extension {ctx.options.extension}.", reply = True)
Esempio n. 12
0
import os
import requests
import json
import hikari
import lightbulb
from dotenv import load_dotenv, find_dotenv
from datetime import datetime
from geopy.geocoders import Nominatim


weather_plugin 	= lightbulb.Plugin("Weather")

class Weather:
	"""Weather class that interacts with OpenWeatherMap API
	for weather information
	"""	
	def __init__(self):		
		load_dotenv(dotenv_path=find_dotenv(usecwd=True))
		self._weather_token = os.environ.get('WEATHER_TOKEN')
		self.name = os.environ.get('BOT_NAME')
		self.location = os.environ.get('DEFAULT_LOCATION')

	def t_convert(self, t, time_format = "%m/%d %H:%M"):
		"""Converting UNIX time to human readable time

		Args:
			t (int): UNIX timestamp
			time_format (str, optional): Date format. Defaults to "%m/%d %H:%M".

		Returns:
			str: Human readable time
Esempio n. 13
0
import lightbulb
import hikari

import random

import utilities.helpers as helpers

plugin = lightbulb.Plugin("Fun",
                          description="Fun Commands",
                          include_datastore=True)
plugin.d.emote = helpers.get_emote(":grin:")


@plugin.command()
@lightbulb.command("dice", "Roll a 6-face dice for you.")
@lightbulb.implements(lightbulb.PrefixCommand, lightbulb.SlashCommand)
async def dice(ctx: lightbulb.Context):
    await ctx.respond("It's %d :game_die:" % (random.randint(1, 6)),
                      reply=True)


@plugin.command()
@lightbulb.option("content",
                  "The string to repeat.",
                  modifier=helpers.CONSUME_REST_OPTION)
@lightbulb.command("echo", "Echo echo echo echo.")
@lightbulb.implements(lightbulb.PrefixCommand, lightbulb.SlashCommand)
async def echo(ctx: lightbulb.Context):
    if isinstance(ctx, lightbulb.PrefixContext):
        await ctx.event.message.delete()
    await ctx.respond(ctx.options.content)
Esempio n. 14
0
import lightbulb
import hikari
import lavaplayer

import datetime as dt

import utilities.helpers as helpers
from utilities.converters import IntervalConverter
from utilities.navigator import ButtonPages

plugin = lightbulb.Plugin("Music",
                          description="Music Commands",
                          include_datastore=True)
plugin.d.emote = helpers.get_emote(":musical_note:")

lavalink = lavaplayer.LavalinkClient(
    host="0.0.0.0",  # Lavalink host
    port=2333,  # Lavalink port
    password="******",  # Lavalink password
    user_id=577663051722129427)

# Currently lavaplayer doesn't support adding attr to lavaplayer.objects.Node
# so we'll make a dictionary to manually track additional info.
# { guild_id: {} }
node_extra = {}


# This should be the value of node_extra[guild_id]
def default_node_extra():
    return {
        "queue_loop": False,
Esempio n. 15
0
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.


from extensions.politics_and_war import commands, background, helpers
from lib import client

import lightbulb
import sys


plugin = lightbulb.Plugin("PoliticsAndWar")
plugin.command(commands.infra_cost)
plugin.command(commands.land_cost)
plugin.command(commands.city_cost)
plugin.command(commands.nation_info)
plugin.command(commands.raids)
plugin.command(commands.alliance_info)


def load(bot: client.Requiem) -> None:
    background.gather_and_run_queries.start(bot)
    bot.add_plugin(plugin)


def unload(bot: client.Requiem) -> None:
    background.gather_and_run_queries.stop()