2020-06-05 00:29:14 +02:00
|
|
|
import asyncio
|
|
|
|
import datetime
|
2020-11-08 01:07:27 +01:00
|
|
|
import importlib
|
2020-06-04 19:16:51 +02:00
|
|
|
import logging
|
2021-05-16 23:21:27 +02:00
|
|
|
import sys
|
2020-10-22 00:00:48 +02:00
|
|
|
from collections import Counter
|
2021-05-16 23:21:27 +02:00
|
|
|
from typing import List, Tuple, Union
|
2020-06-03 01:07:43 +02:00
|
|
|
|
2020-10-22 00:00:48 +02:00
|
|
|
import aiohttp
|
2020-06-04 19:16:51 +02:00
|
|
|
import discord
|
2020-06-03 01:07:43 +02:00
|
|
|
from discord.ext import commands
|
2020-08-28 23:05:04 +02:00
|
|
|
from rich import box
|
|
|
|
from rich.columns import Columns
|
|
|
|
from rich.panel import Panel
|
2021-01-27 15:14:05 +01:00
|
|
|
from rich.progress import Progress
|
2020-08-28 23:05:04 +02:00
|
|
|
from rich.table import Table
|
2020-11-08 01:07:27 +01:00
|
|
|
from tortoise import Tortoise
|
2020-10-19 00:20:58 +02:00
|
|
|
|
2020-08-28 23:05:04 +02:00
|
|
|
from tuxbot import version_info
|
2020-11-08 01:07:27 +01:00
|
|
|
from tuxbot.core.utils.data_manager import (
|
|
|
|
logs_data_path,
|
2021-02-16 19:28:30 +01:00
|
|
|
config_file,
|
2020-11-08 01:07:27 +01:00
|
|
|
)
|
2021-01-27 15:14:05 +01:00
|
|
|
from tuxbot.core.utils.functions.extra import ContextPlus
|
|
|
|
from tuxbot.core.utils.functions.prefix import get_prefixes
|
|
|
|
from tuxbot.core.utils.console import console
|
|
|
|
from tuxbot.core.config import (
|
2020-10-19 22:17:19 +02:00
|
|
|
Config,
|
|
|
|
ConfigFile,
|
|
|
|
search_for,
|
|
|
|
)
|
2020-08-28 01:06:57 +02:00
|
|
|
from . import __version__, ExitCodes
|
2020-10-19 00:20:58 +02:00
|
|
|
from . import exceptions
|
2020-06-04 19:16:51 +02:00
|
|
|
|
|
|
|
log = logging.getLogger("tuxbot")
|
|
|
|
|
2021-04-21 18:28:09 +02:00
|
|
|
packages: Tuple = (
|
2020-11-08 01:07:27 +01:00
|
|
|
"jishaku",
|
2020-11-09 01:18:55 +01:00
|
|
|
"tuxbot.cogs.Admin",
|
|
|
|
"tuxbot.cogs.Logs",
|
2021-01-27 15:14:05 +01:00
|
|
|
"tuxbot.cogs.Dev",
|
2020-11-09 01:18:55 +01:00
|
|
|
"tuxbot.cogs.Utils",
|
2020-11-12 00:03:01 +01:00
|
|
|
"tuxbot.cogs.Polls",
|
2021-01-19 14:30:25 +01:00
|
|
|
"tuxbot.cogs.Custom",
|
2021-01-26 10:21:39 +01:00
|
|
|
"tuxbot.cogs.Network",
|
2021-04-25 23:33:30 +02:00
|
|
|
"tuxbot.cogs.Linux",
|
2021-05-13 16:45:49 +02:00
|
|
|
"tuxbot.cogs.Mod",
|
2021-05-16 00:32:14 +02:00
|
|
|
"tuxbot.cogs.Tags",
|
2021-04-21 18:28:09 +02:00
|
|
|
)
|
2020-06-03 01:07:43 +02:00
|
|
|
|
|
|
|
|
|
|
|
class Tux(commands.AutoShardedBot):
|
2020-06-05 00:29:14 +02:00
|
|
|
_loading: asyncio.Task
|
2021-01-27 15:14:05 +01:00
|
|
|
_progress = {"tasks": {}, "main": Progress()}
|
2020-06-05 00:29:14 +02:00
|
|
|
|
|
|
|
def __init__(self, *args, cli_flags=None, **kwargs):
|
2020-06-03 19:41:30 +02:00
|
|
|
# by default, if the bot shutdown without any intervention,
|
|
|
|
# it's a crash
|
2020-06-05 00:29:14 +02:00
|
|
|
self.shutdown_code = ExitCodes.CRITICAL
|
2020-06-04 00:14:50 +02:00
|
|
|
self.cli_flags = cli_flags
|
|
|
|
self.last_exception = None
|
2021-02-16 19:28:30 +01:00
|
|
|
self.logs = logs_data_path()
|
2020-06-03 19:41:30 +02:00
|
|
|
|
2020-10-22 00:00:48 +02:00
|
|
|
self.console = console
|
|
|
|
|
|
|
|
self.stats = {"commands": Counter(), "socket": Counter()}
|
|
|
|
|
2021-02-16 19:28:30 +01:00
|
|
|
self.config: Config = ConfigFile(config_file, Config).config
|
|
|
|
self.instance_name = self.config.Core.instance_name
|
2020-06-04 19:16:51 +02:00
|
|
|
|
|
|
|
async def _prefixes(bot, message) -> List[str]:
|
2020-10-19 00:20:58 +02:00
|
|
|
prefixes = self.config.Core.prefixes
|
2020-06-05 00:29:14 +02:00
|
|
|
|
2020-10-19 00:20:58 +02:00
|
|
|
prefixes.extend(get_prefixes(self, message.guild))
|
2020-06-04 19:16:51 +02:00
|
|
|
|
2020-10-19 00:20:58 +02:00
|
|
|
if self.config.Core.mentionable:
|
2020-06-04 19:16:51 +02:00
|
|
|
return commands.when_mentioned_or(*prefixes)(bot, message)
|
|
|
|
return prefixes
|
|
|
|
|
|
|
|
if "command_prefix" not in kwargs:
|
|
|
|
kwargs["command_prefix"] = _prefixes
|
2020-06-03 19:41:30 +02:00
|
|
|
|
|
|
|
if "owner_ids" in kwargs:
|
|
|
|
kwargs["owner_ids"] = set(kwargs["owner_ids"])
|
|
|
|
else:
|
2020-10-19 00:20:58 +02:00
|
|
|
kwargs["owner_ids"] = self.config.Core.owners_id
|
2020-06-03 19:41:30 +02:00
|
|
|
|
2021-04-21 18:28:09 +02:00
|
|
|
message_cache_size = 10_000
|
2020-06-03 19:41:30 +02:00
|
|
|
kwargs["max_messages"] = message_cache_size
|
2020-06-04 00:14:50 +02:00
|
|
|
self.max_messages = message_cache_size
|
2020-06-03 19:41:30 +02:00
|
|
|
|
2020-06-04 00:14:50 +02:00
|
|
|
self.uptime = None
|
2021-02-11 18:11:19 +01:00
|
|
|
self.last_on_ready = None
|
2020-06-05 00:29:14 +02:00
|
|
|
self._app_owners_fetched = False # to prevent abusive API calls
|
2021-04-20 15:43:20 +02:00
|
|
|
self.loop = asyncio.get_event_loop()
|
2020-06-04 00:14:50 +02:00
|
|
|
|
2020-11-09 01:27:19 +01:00
|
|
|
super().__init__(
|
2021-04-20 15:43:20 +02:00
|
|
|
*args,
|
|
|
|
intents=discord.Intents.all(),
|
|
|
|
loop=self.loop,
|
|
|
|
**kwargs,
|
2020-11-09 01:27:19 +01:00
|
|
|
)
|
2020-10-22 00:00:48 +02:00
|
|
|
self.session = aiohttp.ClientSession(loop=self.loop)
|
2020-06-04 00:14:50 +02:00
|
|
|
|
2021-01-26 11:37:52 +01:00
|
|
|
async def _is_blacklisted(self, message: discord.Message) -> bool:
|
2021-01-19 16:05:20 +01:00
|
|
|
"""Check for blacklists."""
|
|
|
|
if message.author.bot:
|
|
|
|
return True
|
|
|
|
|
|
|
|
if (
|
2021-02-11 18:40:00 +01:00
|
|
|
search_for(self.config.Users, message.author.id, "blacklisted")
|
2021-01-19 16:05:20 +01:00
|
|
|
or search_for(
|
|
|
|
self.config.Channels, message.channel.id, "blacklisted"
|
|
|
|
)
|
2021-02-11 18:40:00 +01:00
|
|
|
or (
|
|
|
|
message.guild
|
|
|
|
and search_for(
|
|
|
|
self.config.Servers, message.guild.id, "blacklisted"
|
|
|
|
)
|
|
|
|
)
|
2021-01-19 16:05:20 +01:00
|
|
|
):
|
|
|
|
return True
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
2020-06-05 00:29:14 +02:00
|
|
|
async def load_packages(self):
|
|
|
|
if packages:
|
2020-08-28 23:05:04 +02:00
|
|
|
with Progress() as progress:
|
|
|
|
task = progress.add_task(
|
2020-10-19 00:20:58 +02:00
|
|
|
"Loading packages...", total=len(packages)
|
2020-08-28 23:05:04 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
for package in packages:
|
|
|
|
try:
|
|
|
|
self.load_extension(package)
|
|
|
|
progress.console.print(f"{package} loaded")
|
|
|
|
except Exception as e:
|
|
|
|
log.exception(
|
2020-10-19 00:20:58 +02:00
|
|
|
"Failed to load package %s", package, exc_info=e
|
2020-08-28 23:05:04 +02:00
|
|
|
)
|
|
|
|
progress.console.print(
|
|
|
|
f"[red]Failed to load package {package} "
|
|
|
|
f"[i](see "
|
|
|
|
f"{str((self.logs / 'tuxbot.log').resolve())} "
|
|
|
|
f"for more details)[/i]"
|
|
|
|
)
|
|
|
|
|
|
|
|
progress.advance(task)
|
2020-06-06 18:51:47 +02:00
|
|
|
|
2020-06-04 19:16:51 +02:00
|
|
|
async def on_ready(self):
|
2021-02-11 18:11:19 +01:00
|
|
|
if self.uptime is not None:
|
|
|
|
self.last_on_ready = datetime.datetime.now()
|
|
|
|
return
|
|
|
|
|
2020-06-05 00:29:14 +02:00
|
|
|
self.uptime = datetime.datetime.now()
|
2021-02-11 18:11:19 +01:00
|
|
|
self.last_on_ready = self.uptime
|
2020-10-19 22:17:19 +02:00
|
|
|
|
2021-01-27 15:14:05 +01:00
|
|
|
with self._progress["main"] as progress:
|
|
|
|
progress.stop_task(self._progress["tasks"]["discord_connecting"])
|
|
|
|
progress.remove_task(self._progress["tasks"]["discord_connecting"])
|
|
|
|
self._progress["tasks"].pop("discord_connecting")
|
|
|
|
self.console.clear()
|
2020-08-28 23:05:04 +02:00
|
|
|
|
2021-01-27 15:14:05 +01:00
|
|
|
self.console.print(
|
2020-08-28 23:05:04 +02:00
|
|
|
Panel(f"[bold blue]Tuxbot V{version_info.major}", style="blue"),
|
2020-10-19 00:20:58 +02:00
|
|
|
justify="center",
|
2020-08-28 23:05:04 +02:00
|
|
|
)
|
2021-01-27 15:14:05 +01:00
|
|
|
self.console.print()
|
2020-08-28 23:05:04 +02:00
|
|
|
|
2021-01-27 15:14:05 +01:00
|
|
|
columns = Columns(align="center", expand=True)
|
2020-08-28 23:05:04 +02:00
|
|
|
|
2020-10-19 00:20:58 +02:00
|
|
|
table = Table(style="dim", border_style="not dim", box=box.HEAVY_HEAD)
|
2020-08-28 23:05:04 +02:00
|
|
|
table.add_column(
|
|
|
|
"INFO",
|
|
|
|
)
|
|
|
|
table.add_row(str(self.user))
|
2020-10-19 00:20:58 +02:00
|
|
|
table.add_row(f"Prefixes: {', '.join(self.config.Core.prefixes)}")
|
|
|
|
table.add_row(f"Language: {self.config.Core.locale}")
|
2020-08-28 23:05:04 +02:00
|
|
|
table.add_row(f"Tuxbot Version: {__version__}")
|
|
|
|
table.add_row(f"Discord.py Version: {discord.__version__}")
|
2021-05-16 23:21:27 +02:00
|
|
|
table.add_row(f"Python Version: {sys.version.split(' ')[0]}")
|
2021-02-16 19:28:30 +01:00
|
|
|
table.add_row(f"Instance name: {self.instance_name}")
|
2020-08-28 23:05:04 +02:00
|
|
|
table.add_row(f"Shards: {self.shard_count}")
|
|
|
|
table.add_row(f"Servers: {len(self.guilds)}")
|
|
|
|
table.add_row(f"Users: {len(self.users)}")
|
|
|
|
columns.add_renderable(table)
|
|
|
|
|
2020-10-19 00:20:58 +02:00
|
|
|
table = Table(style="dim", border_style="not dim", box=box.HEAVY_HEAD)
|
2020-08-28 23:05:04 +02:00
|
|
|
table.add_column(
|
|
|
|
"COGS",
|
|
|
|
)
|
2020-06-05 00:29:14 +02:00
|
|
|
for extension in packages:
|
2020-08-28 23:05:04 +02:00
|
|
|
if extension in self.extensions:
|
2020-11-12 00:03:01 +01:00
|
|
|
status = f"[green]:heavy_check_mark: {extension} "
|
2020-08-28 23:05:04 +02:00
|
|
|
else:
|
2020-11-12 00:03:01 +01:00
|
|
|
status = f"[red]:heavy_multiplication_x: {extension} "
|
2020-06-04 19:16:51 +02:00
|
|
|
|
2020-08-28 23:05:04 +02:00
|
|
|
table.add_row(status)
|
|
|
|
columns.add_renderable(table)
|
2020-06-04 19:16:51 +02:00
|
|
|
|
2021-01-27 15:14:05 +01:00
|
|
|
self.console.print(columns)
|
|
|
|
self.console.print()
|
2020-06-05 00:29:14 +02:00
|
|
|
|
2020-10-19 00:20:58 +02:00
|
|
|
async def is_owner(
|
2021-05-16 23:21:27 +02:00
|
|
|
self, user: Union[discord.User, discord.Member, discord.Object]
|
2020-10-19 00:20:58 +02:00
|
|
|
) -> bool:
|
2020-06-05 00:29:14 +02:00
|
|
|
"""Determines if the user is a bot owner.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-05-16 23:21:27 +02:00
|
|
|
user: Union[discord.User, discord.Member]
|
2020-06-05 00:29:14 +02:00
|
|
|
|
|
|
|
Returns
|
|
|
|
-------
|
|
|
|
bool
|
|
|
|
"""
|
2020-10-19 00:20:58 +02:00
|
|
|
if user.id in self.config.Core.owners_id:
|
2020-06-05 00:29:14 +02:00
|
|
|
return True
|
|
|
|
|
|
|
|
owner = False
|
|
|
|
if not self._app_owners_fetched:
|
|
|
|
app = await self.application_info()
|
|
|
|
if app.team:
|
|
|
|
ids = [m.id for m in app.team.members]
|
2020-10-19 00:20:58 +02:00
|
|
|
self.config.Core.owners_id = ids
|
2020-06-05 00:29:14 +02:00
|
|
|
owner = user.id in ids
|
|
|
|
self._app_owners_fetched = True
|
|
|
|
|
|
|
|
return owner
|
|
|
|
|
2020-10-19 00:20:58 +02:00
|
|
|
# pylint: disable=unused-argument
|
2020-06-05 00:29:14 +02:00
|
|
|
async def get_context(self, message: discord.Message, *, cls=None):
|
2021-01-26 11:37:52 +01:00
|
|
|
ctx: ContextPlus = await super().get_context(message, cls=ContextPlus)
|
2020-06-05 00:29:14 +02:00
|
|
|
|
2021-01-26 11:37:52 +01:00
|
|
|
if (ctx is None or not ctx.valid) and (
|
|
|
|
user_aliases := search_for(
|
2021-01-19 16:05:20 +01:00
|
|
|
self.config.Users, message.author.id, "aliases"
|
2021-01-26 11:37:52 +01:00
|
|
|
)
|
|
|
|
):
|
|
|
|
# noinspection PyUnboundLocalVariable
|
|
|
|
for alias, command in user_aliases.items():
|
|
|
|
back_content = message.content
|
|
|
|
message.content = message.content.replace(alias, command, 1)
|
2021-01-19 16:05:20 +01:00
|
|
|
|
2021-01-26 11:37:52 +01:00
|
|
|
if (
|
|
|
|
ctx := await super().get_context(message, cls=ContextPlus)
|
|
|
|
) is None or not ctx.valid:
|
|
|
|
message.content = back_content
|
|
|
|
else:
|
|
|
|
break
|
|
|
|
|
|
|
|
return ctx
|
|
|
|
|
|
|
|
async def process_commands(self, message: discord.Message):
|
|
|
|
ctx: ContextPlus = await self.get_context(message)
|
2021-01-19 16:05:20 +01:00
|
|
|
|
|
|
|
if ctx is not None and ctx.valid:
|
2021-01-30 16:43:42 +01:00
|
|
|
if message.guild and ctx.command in search_for(
|
2021-04-21 18:28:09 +02:00
|
|
|
self.config.Servers, message.guild.id, "disabled_command", ()
|
2020-10-19 00:20:58 +02:00
|
|
|
):
|
|
|
|
raise exceptions.DisabledCommandByServerOwner
|
|
|
|
|
|
|
|
if ctx.command in self.config.Core.disabled_command:
|
|
|
|
raise exceptions.DisabledCommandByBotOwner
|
|
|
|
|
2020-06-05 00:29:14 +02:00
|
|
|
await self.invoke(ctx)
|
2021-01-26 11:37:52 +01:00
|
|
|
else:
|
|
|
|
self.dispatch("message_without_command", message)
|
2020-06-05 00:29:14 +02:00
|
|
|
|
|
|
|
async def on_message(self, message: discord.Message):
|
2021-01-26 11:37:52 +01:00
|
|
|
if not await self._is_blacklisted(message):
|
|
|
|
await self.process_commands(message)
|
2020-06-05 00:29:14 +02:00
|
|
|
|
2021-04-20 15:43:20 +02:00
|
|
|
async def start(self, token): # pylint: disable=arguments-differ
|
2021-01-27 15:14:05 +01:00
|
|
|
"""Connect to Discord and start all connections."""
|
|
|
|
with Progress() as progress:
|
|
|
|
task = progress.add_task(
|
|
|
|
"Connecting to PostgreSQL...", total=len(self.extensions)
|
2020-11-08 01:07:27 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
models = []
|
|
|
|
|
|
|
|
for extension, _ in self.extensions.items():
|
|
|
|
if extension == "jishaku":
|
2021-01-27 15:14:05 +01:00
|
|
|
progress.advance(task)
|
2020-11-08 01:07:27 +01:00
|
|
|
continue
|
|
|
|
|
|
|
|
if importlib.import_module(extension).HAS_MODELS:
|
|
|
|
models.append(f"{extension}.models.__init__")
|
|
|
|
|
2021-01-27 15:14:05 +01:00
|
|
|
progress.advance(task)
|
|
|
|
|
2020-11-08 01:07:27 +01:00
|
|
|
await Tortoise.init(
|
|
|
|
db_url="postgres://{}:{}@{}:{}/{}".format(
|
|
|
|
self.config.Core.Database.username,
|
|
|
|
self.config.Core.Database.password,
|
|
|
|
self.config.Core.Database.domain,
|
|
|
|
self.config.Core.Database.port,
|
|
|
|
self.config.Core.Database.db_name,
|
|
|
|
),
|
|
|
|
modules={"models": models},
|
|
|
|
)
|
|
|
|
await Tortoise.generate_schemas()
|
|
|
|
|
2021-01-27 15:14:05 +01:00
|
|
|
with self._progress["main"] as progress:
|
|
|
|
task_id = self._progress["tasks"][
|
|
|
|
"discord_connecting"
|
2020-10-19 00:20:58 +02:00
|
|
|
] = progress.add_task(
|
2021-02-16 19:28:30 +01:00
|
|
|
"Connecting to Discord...",
|
|
|
|
task_name="discord_connecting",
|
2021-01-27 15:14:05 +01:00
|
|
|
start=False,
|
2020-08-28 23:05:04 +02:00
|
|
|
)
|
2020-10-19 00:20:58 +02:00
|
|
|
progress.update(task_id)
|
2021-04-20 15:43:20 +02:00
|
|
|
await super().start(token)
|
2020-08-28 23:05:04 +02:00
|
|
|
|
2020-06-05 00:29:14 +02:00
|
|
|
async def logout(self):
|
|
|
|
"""Disconnect from Discord and closes all actives connections.
|
|
|
|
|
|
|
|
Todo: add postgresql logout here
|
|
|
|
"""
|
2021-01-27 15:14:05 +01:00
|
|
|
with self._progress["main"] as progress:
|
|
|
|
for task in self._progress["tasks"]:
|
|
|
|
progress.log("Shutting down", task)
|
2020-08-28 23:05:04 +02:00
|
|
|
|
2021-01-27 15:14:05 +01:00
|
|
|
progress.stop_task(self._progress["tasks"][task])
|
|
|
|
progress.remove_task(self._progress["tasks"][task])
|
|
|
|
progress.stop()
|
2020-08-28 23:05:04 +02:00
|
|
|
|
|
|
|
pending = [
|
2020-10-19 00:20:58 +02:00
|
|
|
t for t in asyncio.all_tasks() if t is not asyncio.current_task()
|
2020-08-28 23:05:04 +02:00
|
|
|
]
|
|
|
|
|
|
|
|
for task in pending:
|
2021-01-27 15:14:05 +01:00
|
|
|
self.console.log(
|
|
|
|
"Canceling", task.get_name(), f"({task.get_coro()})"
|
|
|
|
)
|
2021-05-16 17:07:26 +02:00
|
|
|
try:
|
|
|
|
task.cancel()
|
|
|
|
except Exception as e:
|
|
|
|
self.console.log(e)
|
2020-09-02 00:08:06 +02:00
|
|
|
await asyncio.gather(*pending, return_exceptions=False)
|
2020-08-28 23:05:04 +02:00
|
|
|
|
2021-04-20 15:43:20 +02:00
|
|
|
await super().close()
|
2020-06-05 00:29:14 +02:00
|
|
|
|
|
|
|
async def shutdown(self, *, restart: bool = False):
|
|
|
|
"""Gracefully quit.
|
|
|
|
|
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
restart:bool
|
|
|
|
If `True`, systemd or the launcher gonna see custom exit code
|
|
|
|
and reboot.
|
|
|
|
|
|
|
|
"""
|
2021-02-11 23:18:12 +01:00
|
|
|
|
|
|
|
self.shutdown_code = (
|
|
|
|
ExitCodes.RESTART if restart else ExitCodes.SHUTDOWN
|
|
|
|
)
|
2020-06-05 00:29:14 +02:00
|
|
|
|
|
|
|
await self.logout()
|
2020-09-02 00:08:06 +02:00
|
|
|
|
|
|
|
sys_e = SystemExit()
|
|
|
|
sys_e.code = self.shutdown_code
|
|
|
|
|
|
|
|
raise sys_e
|