Let's implement a custom prefix on discord.py!

** 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 ...

What is it delicious

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.

Implementation method

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.

Preservation method

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)

Implementation

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!

Finally

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

Let's implement a custom prefix on discord.py!
Let's introduce Custom prefix! !!
Implement a Django app on Hy
Implement a custom View Decorator in Pyramid
Implement a Custom User Model in Django
[Part 2] Let's build a web server on EC2 Linux
[Part 1] Let's set up a Minecraft server on Linux
Until OSD335X runs U-boot on a custom board (memo)