python - 在 python discordpy 中加载扩展

标签 python discord discord.py

我如何解决导入另一个在discordpy中使用cog的文件的问题?

import discord 
from random import randint, choice
from discord.ext import commands
from discord.utils import get
from discord import utils

from . import config

class CommandErrors(commands.Cog):
def __init__(self, client):
    self.client = client

#Error solving
@commands.Cog.listener()
async def on_command_error( self, ctx, error ):
    if isinstance( error, commands.CommandNotFound ):
        await ctx.send( f'{ ctx.author.name } something went wrong, please write command ``.help`` to see all commands of server.' )
    if isinstance( error, commands.errors.CommandInvokeError ):
        await ctx.send( f'{ ctx.author.name } something went wrong, please tell GrizzlyXGod_ to solve the problem.' )

@clear.error
async def clear_error( self, ctx, error ):
    if isinstance( error, commands.MissingRequiredArgument ):
        await ctx.send( f'{ ctx.author.name } please specify the number of messages to clear ``ex: .clear 100``' )
    if isinstance( error, commands.MissingPermissions ):
        await ctx.send( f'{ ctx.author.name } you don''t'' have permission to use this command.' )

@mute.error
async def mute_error( self, ctx, error ):
    if isinstance( error, commands.MissingRequiredArgument ):
        await ctx.send( f'{ ctx.author.name } please type correct ``ex: .mute @name``' )
    if isinstance( error, commands.MissingPermissions ):
        await ctx.send( f'{ ctx.author.name } you don''t'' have permission to use this command.' )
    if isinstance( error, commands.errors.BadArgument ):
        await ctx.send( f'{ ctx.author.name } you wrote something wrong please try again ``ex: .mute @name``' )

@unmute.error
async def unmute_error( self, ctx, error ):
    if isinstance( error, commands.MissingRequiredArgument ):
        await ctx.send( f'{ ctx.author.name } please type correct ``ex: .unmute @name``' )
    if isinstance( error, commands.MissingPermissions ):
        await ctx.send( f'{ ctx.author.name } you don''t'' have permission to use this command.' )
    if isinstance( error, commands.errors.BadArgument ):
        await ctx.send( f'{ ctx.author.name } you wrote something wrong please try again ``ex: .unmute @name``' )

@kick.error
async def kick_error( self, ctx, error ):
    if isinstance( error, commands.MissingRequiredArgument ):
        await ctx.send( f'{ ctx.author.name } please type correct ``ex: .kick @name``' )
    if isinstance( error, commands.MissingPermissions ):
        await ctx.send( f'{ ctx.author.name } you don''t'' have permission to use this command.' )
    if isinstance( error, commands.errors.BadArgument ):
        await ctx.send( f'{ ctx.author.name } you wrote something wrong please try again ``ex: .kick @name``' )

@ban.error
async def ban_error( self, ctx, error ):
    if isinstance( error, commands.MissingRequiredArgument ):
        await ctx.send( f'{ ctx.author.name } please type correct ``ex: .ban @name``' )
    if isinstance( error, commands.MissingPermissions ):
        await ctx.send( f'{ ctx.author.name } you don''t'' have permission to use this command.' )
    if isinstance( error, commands.errors.BadArgument ):
        await ctx.send( f'{ ctx.author.name } you wrote something wrong please try again ``ex: .ban @name``' )

@unban.error
async def unban_error( self, ctx, error ):
    if isinstance( error, commands.MissingRequiredArgument ):
        await ctx.send( f'{ ctx.author.name } please type correct ``ex: .unban @name``' )
    if isinstance( error, commands.MissingPermissions ):
        await ctx.send( f'{ ctx.author.name } you don''t'' have permission to use this command.' )
    if isinstance( error, commands.errors.BadArgument ):
        await ctx.send( f'{ ctx.author.name } you wrote something wrong please try again ``ex: .unban @name``' )

@addrole.error
async def add_role_error( self, ctx, error ):
    if isinstance( error, commands.errors.MissingRequiredArgument ):
        await ctx.send( f'{ ctx.author.name } please type correct ``ex: .addrole @name @role``' )
    if isinstance( error, commands.MissingPermissions ):
        await ctx.send( f'{ ctx.author.name } you don''t'' have permission to use this command.' )
    if isinstance( error, commands.errors.BadArgument ):
        await ctx.send( f'{ ctx.author.name } please type correct ``ex: .addrole @name @role``' )

@removerole.error
async def remove_role_error( self, ctx, error ):
    if isinstance( error, commands.errors.MissingRequiredArgument ):
        await ctx.send( f'{ ctx.author.name } please type correct ``ex: .addrole @name @role``' )
    if isinstance( error, commands.MissingPermissions ):
        await ctx.send( f'{ ctx.author.name } you don''t'' have permission to use this command.' )
    if isinstance( error, commands.errors.BadArgument ):
        await ctx.send( f'{ ctx.author.name } please type correct ``ex: .addrole @name @role``' )

@userinfo.error
async def userinfo_error( self, ctx, error ):
    if isinstance( error, commands.errors.MissingRequiredArgument ):
        await ctx.send( f'{ ctx.author.name } please type correct ``ex: .userinfo @name`` ' )
    if isinstance( error, commands.errors.BadArgument ):
        await ctx.send( f'{ ctx.author.name } something gone wrong make sure that you have wrote the name correctly ``ex: .userinfo @name`` or make sure that user is the part of this server.' )

@commands.Cog.listener()
async def on_command_completion( self, ctx ):
    print(ctx.command.name + " was invoked successfully.")

#Connect
def setup(client):
client.remove_command("help")
client.add_cog(CommandErrors(client))

extensions = ['CommandCommands']
if __name__ == '__main__':
    for ext in extensions:
        client.load_extension(ext)

我尝试导入另一个 cog 文件,如果您需要该文件中的代码,我可以编辑此问题并添加该部分。非常感谢您的帮助。 我想尽快得到答案! 我尝试创建机器人的另一件事是,任何人都可以告诉我如何编写代码来更改服务器的前缀。 enter image description here

最佳答案

在启动机器人的主文件中,您应该加载扩展。它应该包含:

from discord.ext import commands

bot = commands.Bot(...) # or client, depending on what you've called it

# the elements are just the names of your .py files
cogs = ["events", "members", "owner"]

# you can also add the on_ready event as usual here if you'd like

# making sure the bot only loads the extensions if this
# file was executed directly and not imported
if __name__ == "__main__": 
    for cog in cogs:
        bot.load_extension(cog) # loads in each file, Cog, that you defined in the list

然后相应的齿轮应遵循此布局(但也可以遵循其他布局):

from discord.ext import commands

class CogName(commands.Cog):

    def __init__(self, bot):
        self.bot = bot # now you'll use self.bot instead of just bot when referring to the bot in the code

    # instead of bot.command(), you'll use this:
    @commands.command()
    async def cmd(self, ctx): # self is the first param because it's in a class
        # some code

    @commands.command()
    async def othercmd(self, ctx, arg1, *, arg2): # e.g. args work as normal
        # other code

    # this is how you register events, instead of using @bot.event
    @commands.Cog.listener()
    async def on_message(self, message):
        # some code

# this setup function needs to be in every cog in order for the bot to be able to load it
def setup(bot):
    bot.add_cog(CogName(bot))

引用文献:

  • Example bot with cogs - 除了查看 cogs 之外,此示例还深入介绍了如何让服务器配置自己的前缀。考虑一个数据库,例如 json、sqlite 等。
  • Cogs in rewrite - 从异步更改为重写。
  • Another cog example - 更深入地研究它们以及一些展示它们如何工作的示例。

关于python - 在 python discordpy 中加载扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62351392/

相关文章:

python - 比较 jinja2 模板中的两个变量

python - 网页抓取 futbin.com

javascript - 无法读取未定义的属性(读取 'fetchBans' )

delphi - Indy Post 到不和谐的 webhook 给出了错误请求 400

Python re.sub : ignore backreferences in the replacement string

javascript - 当我对此进行更改时,我的 Discord.js 机器人没有响应,我还是新人,但我看不出出了什么问题

python - 我希望我的机器人告诉你,当你不提及某人时,你必须提及某人

python - 更新文件中的字典

python - Discord NoneType 对象 Discord 文件中出现错误?

python - Django 仅在生产环境中使用私有(private) S3 存储