Beispiel #1
0
from client import client
import discord

cmd_name = "unmorse"

client.basic_help(title=cmd_name,
                  desc="reverses a Morse Code message back into text")

detailed_help = {
    "Usage":
    f"{client.default_prefix}{cmd_name}",
    "Description":
    "This command takes a given Morse Code string and reverts it back to text. Spaces denote separate letters and spaces with slashes denote separate words.",
}
client.long_help(cmd=cmd_name, mapping=detailed_help)

morse_lookup = {
    "A": ".-",
    "B": "-...",
    "C": "-.-.",
    "D": "-..",
    "E": ".",
    "F": "..-.",
    "G": "--.",
    "H": "....",
    "I": "..",
    "J": ".---",
    "K": "-.-",
    "L": ".-..",
    "M": "--",
    "N": "-.",
Beispiel #2
0
import importlib
import modules

client.basic_help("livepatch",
                  "A module to load, reload, or unload modules on-the-fly")

detailed_help = {
    "Usage":
    f"`{client.default_prefix}livepatch <subcommands> []`",
    "Description":
    "This module is a kit of commands that can load and unload "
    "modules on the fly while a bot is running, and show information about "
    "currently loaded commands. Beware that this command can disable itself."
}

client.long_help("livepatch", detailed_help)

permissible_users = [  # list of IDs permitted to use the command
    288438228959363073
]

# Correct for framework version 0.6
# As of 0.7 these remove the leading underscore
client_lists = [
    # a list of all handlers the bot has
    client._background_tasks,
    client._ready_handlers,
    client._shutdown_handlers,
    client._message_handlers,
    client._member_join_handlers,
    client._member_remove_handlers,
Beispiel #3
0
    use_mpl = False
else:
    use_mpl = True

detailed_help = {
    "Usage":
    f"{client.default_prefix}logstat <days> <stat> [count]",
    "Arguments":
    "`days` - days to look back in logs\n`stat` - statistic to view. \"users\" or \"channels\"\n`count` (Optional) - how many to show in scoreboard (ignored if viewing channels)",
    "Description":
    "This command looks through all logs in the bot and shows a record of the top users and channels in a server. This requires the bot to be actually logging messages. This command may take a very long time to run, depending on the number of log messages.",
    "Related Commands":
    f"`{client.default_prefix}stats` - show running statistics for the bot",
}

client.long_help(cmd="logstat", mapping=detailed_help)

re_ts = re.compile(r"^\[2018-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{6}\] ")
re_lvl = re.compile(r" \[[DMIWECF]\] ")
re_server_raw = re.compile(
    r" \[[^(\[\]#).]+ - \d+\] ")  # this should work ...?
re_channel_raw = re.compile(
    r" \[#[a-z0-9_-]+ - \d{18}\] "
)  # this was SOOOO MUCH EASIER thankfully (thanks Discord!)
re_msg_id = re.compile(r"\[message id: \d{18}\]")
re_user_raw = re.compile(r"\[[\w'-]+#\d{4} - \d+\]")


def get_channel_name(id, message) -> str:
    c = message.guild.get_channel(id)
    if c is None:
Beispiel #4
0
	422047295941640212,  # ham-voice
]

lock_help = {
	"Usage": f"`{client.default_prefix}lock`\n"
			f"`{client.default_prefix}unlock`",
	"Arguments": "None",
	"Description": "Locks or unlocks the specified channel in case of a raid or general chaos. This command must be run in the target channel. Moderator-only channels cannot be locked."
}

purge_help = {
	"Usage": f"`{client.default_prefix}purge [n]`",
	"Arguments": "`n` - (Optional) Number of messages to delete, capped at 100. (default 25)",
	"Description": "Nukes some number of recent messages in a channel.",
}
client.long_help("lock", lock_help)
client.long_help("unlock", lock_help)
client.long_help("purge", purge_help)

try:
	yarc_role = client.get_guild(364480908528451584).get_role(639519325287350272)
except AttributeError:
	log.critical(f"YARC moderator role not found. Mod commands will raise an exception when run.")


@client.command(trigger="lock", aliases=["l"])
async def lock(command: str, message: discord.Message):
	if message.guild.id != 364480908528451584:
		if message.guild.id != 452274699641159683:
			# wrong guild
			await message.channel.send("Invalid server")
Beispiel #5
0
import discord
import time
import key
import log
import os


client.basic_help(title="exit", desc="Cleans up and shuts down the bot.")

detailed_help = {
	"Usage": f"{client.default_prefix}exit [pid]",
	"Arguments": "`pid` - (Optional) Process ID identifying which bot to exit out of",
	"Description": "This command completely exits out of the bot, and performs any registered cleanup procedures. A user ID check is performed against a builtin list of users allowed to run this command.",
	# NO Aliases field, this will be added automatically!
}
client.long_help(cmd="exit", mapping=detailed_help)


@client.command(trigger="exit")
async def command(command: str, message: discord.Message):
	if not __common__.check_permission(message.author):
		await message.add_reaction("❌")
		if message.author.id == key.shutdown_easter_egg_user:
			await message.channel.send("*hehehe*\n\nCan't fool me! >:3")
		return
	else:
		parts = command.split(" ")
		try:
			target_pid = int(parts[2])
		except IndexError:
			target_pid = os.getpid()
Beispiel #6
0
http_client = aiohttp.ClientSession()
last_run_time = 0
blacklist_users = []

client.basic_help(
    title=f"{client.default_prefix}wa",
    desc="Performs a Wolfram|Alpha query and returns the results")
client.long_help(
    cmd="wa",
    mapping={
        "Usage":
        f"{client.default_prefix}wa",
        "Arguments":
        "Query to be evaluated",
        "Description":
        "The Wolfram|Alpha engine is a web-based computation engine that can perform a wide array of "
        "mathematical, scientific, or engineering computations, statistical and information lookup, "
        "conversion and calculation using units, and much, *much* more.",
        "Note about results":
        "Because Wolfram|Alpha can return results about (seemingly) anything under the sun, "
        "it is difficult to automatically return intended, desired answers. For that reason, "
        "if you encounter a query that does not show the answer or shows it improperly, "
        "please notify ntoskrnl to be fixed."
    })


# todo: File system caching
# todo: more data in embeds (show everything)?
# todo: help
@client.command("wa", aliases=["wolframalpha", "w|a", "wolfram|alpha"])
async def WolframAlphaQuery(command: str, message: discord.Message):
Beispiel #7
0
from client import client
from datetime import datetime

import asyncio
import discord
import subprocess
import time

client.basic_help(title="time",
                  desc="Shows the current time, accounting for delays.")
client.long_help(
    cmd="time",
    mapping={
        "Usage":
        f"`{client.default_prefix}time",
        "Description":
        "This command shows the current UTC time as per the system clock, synchronized to a GPS receiver.\n"
        "Typical accuracy of the clock is <500ns.\nDelays due to message sending in Discord are accounted "
        "for with two test messages before recording and fudging the current time, and sending it back to you.\n"
        "For further information on the clock synchronization on this machine, run the "
        f"`{client.default_prefix}ntp` command.",
    })

last_run = 0


@client.command(trigger="time")
async def show_simple_time(command: str, message: discord.Message):
    global last_run

    if (time.time() - last_run) < 15.0:  # if cooldown,
        await message.add_reaction("❌")  # reject the command
Beispiel #8
0
    import psutil
except ModuleNotFoundError:
    has_psutil = False
    psutil = None
else:
    has_psutil = True
    psutil_update_thread = None

client.basic_help(title="stats", desc=f"Shows running statistics of {client.bot_name}")

detailed_help = {
    "Usage": f"{client.default_prefix}stats",
    "Description": f"This command shows different available statistics of {client.bot_name}, including servers, uptime, and commands run.",
    "Related": f"`{client.default_prefix}info` - shows information about {client.bot_name}",
}
client.long_help(cmd="stats", mapping=detailed_help)


@client.command(trigger="stats", aliases=["statistics", "s", "status"])
async def statistics(command: str, message: discord.Message):
    if "--uptime" in command:
        up = time.perf_counter() - client.first_execution
        await message.channel.send(f"Uptime:\n`{up:.3f}` seconds\n`{up/86400:.4f}` days")
        return
    
    async with message.channel.typing():
        
        embed = discord.Embed(title=f"Running statistics for {client.bot_name}", description=discord.Embed.Empty, color=0x404040)
        
        up = time.perf_counter() - client.first_execution
        embed = embed.add_field(name="Uptime", value=f"{up:.3f} seconds\n{up/86400:.4f} days")
Beispiel #9
0
                     "then the provided measurement will be converted into standard SI/physics unit dimensions of "
                     "length (meters), mass (kilograms), and time (seconds).",
    "Comparing measurements": "It is possible to pass in two whole measurements in order to compare the two, assuming "
                              "they are of the same dimensions (ie. they are both mass, or velocity, or whatever). The "
                              "resulting scalar value is the ratio of how greater the first value is to the second "
                              "(eg. `units 5km 2.5km` returns 2.0, because 5km is twice as large as 2.5km). Using "
                              "units that cannot be compared results in a conformability error.",
    "Conformability errors": "When it is impossible to convert or compare the measurements given (eg. minutes into "
                             "kilometers), a *conformability error* will result. The two resulting values given are "
                             "the base SI units for both given measurements, as if you had performed the one argument "
                             "usage using it.",
    "Performing math": "The units command can perform rather complex math, by entering an expression to calculate in "
                       "the form of one argument usage. Trig functions are done in radians (as they rightfully "
                       "should), and proper evaulation order is followed.\nExample: `units 12+3/(2sin(pi/2))`",
}
client.long_help(cmd="units", mapping=help_dict)


@client.command(trigger="units", aliases=["unit", "convert", "u"])
async def convert_units(command: str, message: discord.Message):
    parts = command.split(" ")
    
    if len(parts) == 1:
        # no args
        await message.channel.send(f"Need more arguments to run command. See command help for help.")
        return
    if len(parts) == 2:
        proc = subprocess.Popen(["units", "-t", parts[1]], stdout=subprocess.PIPE)
    if len(parts) == 3:
        proc = subprocess.Popen(["units", "-t", parts[1], parts[2]], stdout=subprocess.PIPE)
    if len(parts) == 4:
Beispiel #10
0
detailed_help = {
	"Usage": f"{client.default_prefix}music <subcommand> [args]",
	"Arguments": "`subcommand` - subcommand to run\n`args` - (optional) arguments specific to the subcommand being run",
	"Description": "This command manages music related functionality within the bot. Music is available to several servers at once.",
	"Subcommands": f"`{client.default_prefix}music join` - Joins a voice channel\n"
					f"`{client.default_prefix}music add <url>` - Adds the specified song to the queue\n"
					f"`{client.default_prefix}music play` - Plays music in the queue\n"
					f"`{client.default_prefix}music pause` - Toggles pause\n"
					f"`{client.default_prefix}music playing` - Shows what is currently playing\n"
					f"`{client.default_prefix}music skip` - Skips the currently playing song\n"
					f"`{client.default_prefix}music queue` - Shows the current music queue\n"
					f"`{client.default_prefix}music info [index]` - Shows song information for the specified song in the queue\n"
					f"`{client.default_prefix}music volume <volume>` - Sets the music volume, on a scale of 0.0-2.0\n"
					f"`{client.default_prefix}music exit` - Exits the channel (also aliased to `stop` and `quit`)\n",
}
client.long_help(cmd="music", mapping=detailed_help)

voice_enable = False
access_lock = asyncio.Lock()
song_info_embed_colour = 0xbf35e3
playlist_dir = "playlists/"

cooldown: Dict[int, datetime] = defaultdict(lambda: datetime(1970, 1, 1, 0, 0, 0, 0))
guild_channel: Dict[int, discord.TextChannel] = {}
guild_queue: Dict[int, List["Song"]] = defaultdict(list)
guild_now_playing_song: Dict[int, "Song"] = {}
guild_volume: Dict[int, float] = defaultdict(lambda: float(1.0))
active_clients: Dict[int, discord.VoiceClient] = {}

music_blacklist = []
Beispiel #11
0
                description=f"Unknown command",
                colour=0xa20303)
            embed = embed.set_footer(text=__common__.get_timestamp())
            await message.channel.send(embed=embed)

        elif type(sub_help) == dict:
            embed = discord.Embed(
                title=f"Help for command `{command.lower()[5:]}`",
                description=sub_help.get("_description", discord.Embed.Empty),
                colour=0x06b206)
            for title, text in sub_help.items():
                embed = embed.add_field(name=title, value=text, inline=False)
            if client.cmd_aliases.get(command.lower()[5:], []):
                embed = embed.add_field(name="Aliases",
                                        value="\n".join(
                                            client.cmd_aliases.get(
                                                command.lower()[5:], [])))
            embed = embed.set_footer(text=__common__.get_timestamp())
            await message.channel.send(embed=embed)


help_long_help = {
    "Usage:":
    f"`{client.default_prefix}help [command]`",
    "Arguments":
    "`command` - (Optional) Bot command to fetch detailed help with.",
    "Description":
    "This command fetches help information for a command or for all commands."
}
client.long_help("help", help_long_help)
Beispiel #12
0
from client import client

import discord


@client.command(trigger="ping", aliases=["p"])
async def help_command(command: str, message: discord.Message):
    await message.channel.send(
        f"Latency to the connected Discord API endpoint: `{client.latency*1000:.0f} ms`"
    )
    return


client.basic_help("ping",
                  "Returns the bot's latency to its connected API endpoint.")

help_long_help = {
    "Usage:":
    f"`{client.default_prefix}ping`",
    "Description":
    "This command returns the bot's latency to the Discord API endpoint it is connected to."
}
client.long_help("ping", help_long_help)
Beispiel #13
0
import discord
import requests

client.basic_help(title="call",
                  desc="Looks up a callsign from the callook.info database.")

detailed_help = {
    "Usage":
    f"{client.default_prefix}call <callsign>",
    "Arguments":
    "`<callsign>` - the callsign to look up",
    "Description":
    "This command is a reimplementation of HamTheMan's `htm call` command. It retrieves information about a specified callsign and returns some info about it. This command exists in here because Ben doesn't know how to keep a bot online :P",
    # NO Aliases field, this will be added automatically!
}
client.long_help(cmd="call", mapping=detailed_help)


@client.command(trigger="call")
async def call(command: str, message: discord.Message):
    try:
        requested_call = command.split(" ", 1)[1].lower()
    except TypeError:
        await message.channel.send(
            "Argument error: Callsign argument not given")
        return
    if requested_call[0] not in ["w", "a", "n", "k"]:
        await message.channel.send(
            f"Argument error: The underlying API only retrieves information for US calls (prefixes `N`, `K`, `W`, and `AA-AL`).\nFor non-US calls please use HamTheMan instead: `htm call {requested_call}`"
        )
        return
Beispiel #14
0
import datetime
import discord
import key

client.basic_help(title="n2yo",
                  desc="Shows information about amateur satellites.")

cmd_help = {
    "Usage":
    "`n2yo <action> [args] [--debug] [--apicount]`",
    "Arguments":
    "`action` - what you want to do\n`--debug` - shows extra information about the command while running\n`--apicount` - shows api usage in past hour",
    "Further help":
    "For detailed help about the functionality of this command, run `n2yo` without any arguments."
}
client.long_help(cmd="n2yo", mapping=cmd_help)

cmd_desc = "This command uses the N2YO.com API to show information about various satellites that are in the sky at " \
   "your location. \nSatellites are referred to by their NORAD catalogue number. To get a list of sateliite " \
   "numbers run the command with the singular argument \"sats\". If you know the NORAD ID of another " \
   "satellite you can use its ID as well.\n"
get_sat_pos = "Usage: `n2yo pos <sat_id> <grid> ['--alt' your_altitude] `\n\nGets the current position of a satellite in your " \
    "sky given the satellite ID and your grid square. An altitude of 100m is used by default, altitude in " \
    "meters can be provided as an optional third argument and can help increase accuracy."
get_passes = "Usage: `n2yo passes <sat_id> <grid> <min_elevation> ['--alt' your_altitude]`\n\n`min_elevation` - " \
   "minimum maximum elevation of the pass\n`--alt [x]` - specifies your altitude in meters for better " \
   "accuracy (recommended)"
sat_norad_ids = """```
25544: Space Station
40967: Fox-1A / AO-85
43017: Fox-1B / AO-91
import log
import key

accepted_phrases = [
	"hail awoobis",
	"hail awoobis!",
	"hail lord awoobis",
	"hail lord awoobis!",
]

help_count = {
	"Usage": f"{client.default_prefix}count",
	"Arguments": "None",
	"Description": "Shows the number of hails you have made to Awoobis.",
}
client.long_help("count", help_count)
help_reps = {
	"Usage": f"{client.default_prefix}reps <int>",
	"Arguments": "`<int>` - number of top reputation members to show. Negative values can be entered to see worst reputation people.",
	"Description": "Shows the reputation scoreboard of people in the server, including top and bottom reputation members.",
}
client.long_help("reps", help_reps)
help_top = {
	"Usage": f"{client.default_prefix}top <int>",
	"Arguments": "`<int>` - number of top hailers to show.",
	"Description": "Shows the scoreboard of who has Hailed Awoobis the most times in the server. ",
}
client.long_help("top", help_top)

other_roles = []
record = Counter()