Fallback function to register

This commit is contained in:
klemek
2020-11-06 18:44:25 +01:00
parent 33eb60474a
commit 5ed605ab7b
2 changed files with 16 additions and 0 deletions
+4
View File
@@ -14,6 +14,9 @@ import discord
async def hello(client: discord.client, message: discord.Message, *args: str):
await message.channel.send("Hello!")
async def mention(client: discord.client, message: discord.Message, *args: str):
await message.channel.send(f"Did you mention me {message.author.mention}?")
bot = Bot(
"test-app", # name
@@ -29,6 +32,7 @@ bot.register_command(
f"\tSays 'Hello!'.\n"
f"```"
)
bot.register_fallback(mention) # the bot was mentioned or the alias was used
bot.start()
# this bot respond to "|help", "|info" and "|hello"
```
+12
View File
@@ -49,6 +49,7 @@ class Bot(object):
self.__last_error = None
# init
self.__commands = []
self.__fallback = None
self.games = [f"v{version}",
lambda:f"{len(self.client.guilds)} guilds"]
if self.alias is not None:
@@ -145,6 +146,8 @@ class Bot(object):
command_args = parse_arguments(message.content)
if len(command_args) == 0:
if self.__fallback is not None and is_mention:
await self.__fallback(self.client, message, *command_args)
return # Empty message
is_alias = self.alias is not None and command_args[0].startswith(self.alias)
@@ -154,6 +157,8 @@ class Bot(object):
if not is_direct and not is_mention and not is_alias:
return # Not for the bot
command_found = False
for command in self.__commands:
if re.match(command.regex, command_args[0].lower() if self.lower_command_names else command_args[0]):
if self.log_calls:
@@ -169,9 +174,13 @@ class Bot(object):
f" #{message.channel} in server '{message.guild}'"
)
return
command_found = True
await command.compute(self.client, message, *command_args)
break
if not command_found and self.__fallback is not None:
await self.__fallback(self.client, message, *command_args)
async def on_guild_join(self, guild: discord.guild):
if self.guild_logs_file is not None:
with open(self.guild_logs_file, encoding="utf-8", mode="a") as f:
@@ -189,6 +198,9 @@ class Bot(object):
regex = regex + "$"
self.__commands.insert(0, Command(regex, compute, help_short, help_long))
def register_fallback(self, compute: CommandFunction):
self.__fallback = compute
def start(self):
logging.info(f"Current PID: {os.getpid()}")
env_file_found = load_dotenv()