college-bot-v1/main.py

139 lines
4 KiB
Python
Raw Normal View History

2022-09-13 14:00:27 +01:00
import discord
from discord.ext import commands
from asyncio import Lock
2022-09-13 14:00:27 +01:00
import config
from datetime import datetime, timezone, timedelta
2023-01-19 14:04:28 +00:00
from utils import registry, console, get_or_none, JimmyBans
2023-02-22 01:33:30 +00:00
from web.server import app
import uvicorn
2022-09-13 14:00:27 +01:00
intents = discord.Intents.default()
intents += discord.Intents.messages
2022-12-18 14:05:48 +00:00
intents += discord.Intents.message_content
intents += discord.Intents.members
intents += discord.Intents.presences
2022-11-30 21:01:16 +00:00
extensions = [
"jishaku",
"cogs.verify",
"cogs.mod",
"cogs.events",
"cogs.assignments",
"cogs.timetable",
"cogs.other",
"cogs.starboard",
2023-01-18 20:54:48 +00:00
"cogs.uptime",
2022-11-30 21:01:16 +00:00
]
2023-02-22 01:33:30 +00:00
class Bot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix=self.get_prefix,
debug_guilds=config.guilds,
allowed_mentions=discord.AllowedMentions.none(),
intents=intents,
)
self.training_lock = Lock()
self.started_at = datetime.now(tz=timezone.utc)
self.bans = JimmyBans()
for ext in extensions:
try:
bot.load_extension(ext)
except discord.ExtensionFailed as e:
console.log(f"[red]Failed to load extension {ext}: {e}")
else:
console.log(f"Loaded extension [green]{ext}")
app.state.bot = self
config = uvicorn.Config(
app,
port=3762
)
bot = Bot()
2022-09-13 20:50:02 +01:00
bot.loop.run_until_complete(registry.create_all())
2022-09-13 14:00:27 +01:00
2022-10-11 14:31:23 +01:00
@bot.listen()
2022-10-09 19:36:21 +01:00
async def on_connect():
2022-10-12 17:40:02 +01:00
console.log("[green]Connected to discord!")
2022-10-09 19:36:21 +01:00
@bot.listen("on_application_command_error")
async def on_application_command_error(ctx: discord.ApplicationContext, error: Exception):
if isinstance(error, commands.CommandOnCooldown):
now = discord.utils.utcnow()
now += timedelta(seconds=error.retry_after)
return await ctx.respond(
f"\N{stopwatch} This command is on cooldown. You can use this command again "
f"{discord.utils.format_dt(now, 'R')}.",
delete_after=error.retry_after,
)
elif isinstance(error, commands.MaxConcurrencyReached):
return await ctx.respond(
f"\N{warning sign} This command is already running. Please wait for it to finish.",
ephemeral=True,
)
await ctx.respond("Application Command Error: `%r`" % error)
2023-01-09 14:36:32 +00:00
raise error
2022-10-15 15:31:21 +01:00
@bot.listen("on_command_error")
2022-10-30 16:05:54 +00:00
async def on_command_error(ctx: commands.Context, error: Exception):
if isinstance(error, commands.CommandNotFound):
return
await ctx.reply("Command Error: `%r`" % error)
2023-01-09 14:36:32 +00:00
raise error
2022-10-15 15:31:21 +01:00
2022-11-01 17:22:56 +00:00
@bot.listen("on_application_command")
async def on_application_command(ctx: discord.ApplicationContext):
console.log(
"{0.author} ({0.author.id}) used application command /{0.command.qualified_name} in "
"#{0.channel}, {0.guild}".format(ctx)
)
2022-10-11 14:31:23 +01:00
@bot.event
2022-09-13 14:00:27 +01:00
async def on_ready():
2022-10-12 17:40:02 +01:00
console.log("Logged in as", bot.user)
2022-09-13 14:00:27 +01:00
@bot.slash_command()
async def ping(ctx: discord.ApplicationContext):
2022-10-12 17:40:02 +01:00
# noinspection SpellCheckingInspection
2022-09-13 14:00:27 +01:00
"""Checks the bot's response time"""
gateway = round(ctx.bot.latency * 1000, 2)
2022-09-13 21:27:14 +01:00
return await ctx.respond(f"\N{white heavy check mark} Pong! `{gateway}ms`.")
2022-09-13 14:00:27 +01:00
2023-01-19 14:04:28 +00:00
@bot.check_once
async def check_not_banned(ctx: discord.ApplicationContext | commands.Context):
if await bot.is_owner(ctx.author):
return True
user = ctx.author
ban: JimmyBans = await get_or_none(JimmyBans, user_id=user.id)
if ban:
dt = datetime.fromtimestamp(ban.until, timezone.utc)
if dt < discord.utils.utcnow():
await ban.delete()
else:
reply = ctx.reply if isinstance(ctx, commands.Context) else ctx.respond
try:
await reply(content=f":x: You can use commands {discord.utils.format_dt(dt, 'R')}")
except discord.HTTPException:
pass
finally:
return False
return True
2022-10-09 19:27:02 +01:00
if __name__ == "__main__":
2023-01-19 14:04:28 +00:00
console.log("Starting...")
2023-02-22 01:33:30 +00:00
bot.started_at = discord.utils.utcnow()
2022-10-09 19:27:02 +01:00
bot.run(config.token)