如何在扩展中使用机器人类方法 (get_user())? (不和谐.py)

时间:2021-06-15 06:53:47

标签: python discord discord.py

我现在拥有的机器人有很多命令,我正计划将其中几个移动到扩展文件中。我的一些命令需要 bot 方法,例如 get_user(),我想知道如何将其实现到扩展中。

一个例子是

import discord
from discord.ext import commands

@commands.command()
async def bonk(ctx, member: discord.Member, reason = "being bad"):
    [command here]

    if not [condition]:
        dev = bot.get_user([myIDHere])
        await dev.send('Failed to update sheet')

def setup(bot):
    bot.add_command(bonk)

1 个答案:

答案 0 :(得分:1)

您应该将扩展称为齿轮。

from discord.ext import commands
import discord

class Example(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def bonk(ctx, member: discord.Member, reason = "being bad"):

    if not [condition]:
        dev = self.bot.get_user([myIDHere])
        await dev.send('Failed to update sheet')

def setup(bot):
    bot.add_cog(Example(bot))

然后在您的 main.py 中,在底部运行它。顶级文件必须位于名为 cogs 的文件夹中(如果您尚未这样做)。

for cog_new in os.listdir("cogs"):
    if cog_new.endswith(".py"):
        try:
            cog = f"cogs.{cog_new.replace('.py', '')}"
            bot.load_extension(cog)
        except Exception as e:
            print(f"{cog_new} can not be loaded: {e}")