** This article is for those using the discord.py command workframe. ** **
Do you know that? This article seems to be the 7th day article of Discord Bot Adcare. ~~ It's Christmas already, ~~ Christmas is over ...
The so-called custom prefix is a feature that allows bots to dynamically set a prefix for each server, whereas the prefix usually does not change on any server. It is relatively useful when many bots are installed and the prefix is covered.
The command_prefix of commands.Bot is usually passed as a string or a list of str, but you can also pass a ** function ** that takes commands.Bot
, discord.Message
as arguments.
We will set the prefix dynamically using this specification.
Now, how to save the prefix, it is good to use a .json file or database, but this time I would like to save it to a nickname to make it easier. It feels like [hoge] bot name
. (In this case hoge
is prefix)
I implemented it as follows.
main.py
import discord
from discord.ext import commands
def _prefix_callable(bot: commands.Bot, msg: discord.Message) -> str:
if msg.guild is None: #For dm
return "/"
else:
if msg.guild.me.nick is None:
return "/"
nick = msg.guild.me.display_name
result = nick.replace("[", "").replace(f"]{bot.user.name}", "")
return result
bot = commands.Bot(command_prefix=_prefix_callable)
bot.run("TOKEN")
In the case of dm, the prefix is not affected (there is no other bot in the first place), so it branches with if msg.guild is None
and returns/
.
It also returns /
if the nickname is not set (= custom prefix is not set) in if msg.guild.me.nick is None:
.
Well, the main subject is from here. I will explain what to do when a custom prefix is set.
Let's assume that the name of the bot is hoge
and the nickname is [prefix] hoge
.
First, msg.guild.me
gets the Member
object of the bot itself, and .display_name
gets the nickname and stores it in nick
.
Then replace`` [
and] hoge
from nick
to get the string prefix
.
Finally, return this!
Sorry for the rather crude article this time ... Please forgive me because it will be solid from the next time
Have a nice discord bot life with a custom prefix!
Recommended Posts