【问题标题】:Issue when running some commands from within cogs discord.py从 cogs discord.py 中运行某些命令时出现问题
【发布时间】:2020-06-25 00:23:43
【问题描述】:

好的,所以我在从 cogs 内部运行几个命令时遇到了问题。无论我将其放入什么命令,一个命令都不会运行,而另一个命令根本不会从 cog 内运行。

命令是设置前缀和我的消息计数器。 [消息计数器实际上是一个侦听器而不是命令,但有同样的问题]。

他们不断抛出的错误基本上是这样的:

Traceback (most recent call last):   File "C:\Users\Joshu\PycharmProjects\Discord_Bots\Ranma\venv\lib\site-packages\discord\client.py", line 312, in _run_event     await coro(*args, **kwargs) TypeError: on_message() missing 1 required positional argument: 'message'

我已经将消息计数器移动到一个单独的系统中,并将其重新实现为一个正常工作的自动响应程序,现在唯一需要修复的是尝试让前缀命令在一个 cog 中工作。

这是我的Admin.py Cog,我尝试让_prefix 命令工作:

import discord
from discord.ext import commands
import discord.utils
import os
import functools
import sys
import json

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

    with open("./data/config.json") as f:
        prefixes = json.load(f)
        default_prefix = "r?"


    def prefix(client, message):
        id = message.guild.id
        return prefixes.get(id, default_prefix)
    

    @commands.command(name="Prefix", aliases=["prefix", "setprefix"], hidden=True)
    @commands.has_permissions(manage_guild=True)
    async def _prefix(self, ctx, new_prefix):
        guild = ctx.guild
        msg = ctx.message
        prefixes[msg.guild.id] = new_prefix
        cli = self.client.user
        gold = discord.Color.dark_gold()
        with open("./data/config.json", "w") as f:
            json.dump(prefixes, f, indent=4)
            await msg.add_reaction(emoji="✅")


    @_prefix.error
    async def _prefix_error(self, ctx, error):
        guild = ctx.guild
        msg = ctx.message
        cli = client.user
        red = discord.Color.dark_red()
        e_1 = str("""```css\nPlease pass in all required arguments.```""")
        e_2 = str("""```css\nYou do not have permission to use this command.```""")
        if isinstance(error, commands.MissingRequiredArgument):
            embed = discord.Embed(color=red, name=cli.display_name, timestamp=msg.created_at)
            embed.set_author(name="Command Failed", icon_url=cli.avatar_url)
            embed.add_field(name="Missing Required arguments", value=e_1, inline=False)
            embed.set_thumbnail(url=cli.avatar_url)
            embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
            await msg.send(embed=embed)
        elif isinstance(error, commands.MissingPermissions):
            embed = discord.Embed(color=red, name=cli.display_name, timestamp=msg.created_at)
            embed.set_author(name="Access denied", icon_url=cli.avatar_url)
            embed.add_field(name="Insufficient Permissions", value=e_2, inline=False)
            embed.set_thumbnail(url=cli.avatar_url)
            embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
            await msg.send(embed=embed)

    

    @commands.command(name="ServerInvite", aliases=["serverinvite", "sinv"])
    @commands.has_permissions(manage_guild=True)
    async def _create_invite(self, ctx):
        if not ctx.author.bot:
            guild = ctx.guild
            msg = ctx.message
            cli = self.client.user
            await msg.delete()
            gold = discord.Color.dark_gold()
            link = await ctx.channel.create_invite(max_age = 300)
            embed = discord.Embed(color=gold, timestamp=msg.created_at)
            embed.set_author(name=cli.display_name, icon_url=cli.avatar_url)
            embed.add_field(name=f"{guild.name} invite", value=link, inline=False)
            embed.set_thumbnail(url=cli.avatar_url)
            embed.set_footer(text=guild.name, icon_url=guild.icon_url)
            await ctx.send(embed=embed)


    @_create_invite.error
    async def _create_invite_error(self, ctx, error):
        guild = ctx.guild
        msg = ctx.message
        cli = self.client.user
        red = discord.Color.dark_red()
        e_1 = str("""```css\nPlease pass in all required arguments.```""")
        e_2 = str("""```css\nYou do not have permission to use this command.```""")
        if isinstance(error, commands.MissingRequiredArgument):
            embed = discord.Embed(color=red, name=cli.display_name, timestamp=msg.created_at)
            embed.set_author(name="Command Failed", icon_url=cli.avatar_url)
            embed.add_field(name="Missing Required arguments", value=e_1, inline=False)
            embed.set_thumbnail(url=cli.avatar_url)
            embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
            await msg.send(embed=embed)
        elif isinstance(error, commands.MissingPermissions):
            embed = discord.Embed(color=red, name=cli.display_name, timestamp=msg.created_at)
            embed.set_author(name="Access denied", icon_url=cli.avatar_url)
            embed.add_field(name="Insufficient Permissions", value=e_2, inline=False)
            embed.set_thumbnail(url=cli.avatar_url)
            embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
            await msg.send(embed=embed)



    @commands.command(name="Announce", aliases=["A", "a", "announce", "Ann", "ann", "ANN"])
    @commands.has_permissions(manage_messages=True)
    async def _announce(self, ctx, *, message):
        """Sends an announcement via the bot."""
        guild = ctx.guild
        msg = ctx.message
        cli = self.client.user
        author = ctx.author
        gold = discord.Color.dark_gold()
        c_announce = str(f"""```css\n{message}```""")
        for channel in guild.channels:
            if str(channel.name) == "????announcements-and-suggestions":
                embed = discord.Embed(color=gold, name=cli.display_name, timestamp=msg.created_at)
                embed.set_author(name="Announcement", icon_url=cli.avatar_url)
                embed.add_field(name=f"Sent by {author.display_name}", value=c_announce, inline=False)
                embed.set_thumbnail(url=cli.avatar_url)
                embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
                await msg.add_reaction(emoji="✅")
                await channel.send(embed=embed)

    @_announce.error
    async def _announce_error(self, ctx, error):
        guild = ctx.guild
        msg = ctx.message
        cli = self.client.user
        red = discord.Color.dark_red()
        e_1 = str("""```css\nPlease pass in all required arguments.```""")
        e_2 = str("""```css\nYou do not have permission to use this command.```""")
        if isinstance(error, commands.MissingRequiredArgument):
            embed = discord.Embed(color=red, name=cli.display_name, timestamp=msg.created_at)
            embed.set_author(name="Command Failed", icon_url=cli.avatar_url)
            embed.add_field(name="Missing Required arguments", value=e_1, inline=False)
            embed.set_thumbnail(url=cli.avatar_url)
            embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
            await msg.send(embed=embed)
        elif isinstance(error, commands.MissingPermissions):
            embed = discord.Embed(color=red, name=cli.display_name, timestamp=msg.created_at)
            embed.set_author(name="Access denied", icon_url=cli.avatar_url)
            embed.add_field(name="Insufficient Permissions", value=e_2, inline=False)
            embed.set_thumbnail(url=cli.avatar_url)
            embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
            await msg.send(embed=embed)


    @commands.command(name="Ban", aliases=["ban", "B", "b"])
    @commands.has_permissions(manage_guild=True)
    async def _ban(self, ctx, member: discord.Member, *, reason=None):
        guild = ctx.guild
        msg = ctx.message
        author = ctx.author
        red = discord.Color.dark_red()
        for channel in guild.channels:
            if str(channel.name) == "????log":
                await member.ban(reason=reason)
                c_ban = str(f"""```css\n{member.mention} has been banned from the guild by {author.display_name}.```""")
                embed = discord.Embed(color=red, timestamp=msg.created_at)
                embed.set_author(name=f"{self.client.user.name} Saotomi", icon_url=self.client.user.avatar_url)
                embed.add_field(name="User Banned", value=c_ban, inline=False)
                embed.set_thumbnail(url=ctx.member.avatar_url)
                embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
                await msg.add_reaction(emoji="✅")
                await channel.send(embed=embed)

    @_ban.error
    async def _ban_error(self, ctx, error):
        guild = ctx.guild
        msg = ctx.message
        cli = self.client.user
        red = discord.Color.dark_red()
        e_1 = str("""```css\nPlease pass in all required arguments.```""")
        e_2 = str("""```css\nYou do not have permission to use this command.```""")
        if isinstance(error, commands.MissingRequiredArgument):
            embed = discord.Embed(color=red, name=cli.display_name, timestamp=msg.created_at)
            embed.set_author(name="Command Failed", icon_url=cli.avatar_url)
            embed.add_field(name="Missing Required arguments", value=e_1, inline=False)
            embed.set_thumbnail(url=cli.avatar_url)
            embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
            await msg.send(embed=embed)
        elif isinstance(error, commands.MissingPermissions):
            embed = discord.Embed(color=red, name=cli.display_name, timestamp=msg.created_at)
            embed.set_author(name="Access denied", icon_url=cli.avatar_url)
            embed.add_field(name="Insufficient Permissions", value=e_2, inline=False)
            embed.set_thumbnail(url=cli.avatar_url)
            embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
            await msg.send(embed=embed)

    @commands.command(name="Unban", aliases=["u", "U", "unban"])
    @commands.has_permissions(ban_members=True)
    async def _unban(self, ctx, *, member, reason=None):
        """Unbans a specified user from the guild."""
        author = ctx.author
        guild = ctx.guild
        msg = ctx.message
        orange = discord.Color.dark_orange()
        for channel in guild.channels:
            if str(channel.name) == "????log":                
                banned_users = await ctx.guild.bans()
                member_name, member_discriminator = member.split("#")

                for ban_entry in banned_users:
                    user = ban_entry.user
                    if (user.name, user.discriminator) == (member.name, member.discriminator):
                        await ctx.guild.unban(reason=reason)
                        await ctx.guild.unban(user)
                        c_unban = str(f"""```css\n{author.display_name} has unbanned {user.mention} from {guild.name}```""")
                        embed = discord.Embed(color=orange, timestamp=msg.created_at)
                        embed.set_author(name=f"{self.client.user.name} Saotomi", icon_url=self.client.user.avatar_url)
                        embed.add_field(name="User Unbanned", value=c_unban, inline=False)
                        embed.set_thumbnail(url=f"{member.avatar_url}")
                        embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
                        await msg.add_reaction(emoji="✅")
                        await channel.send(embed=embed)

    @_unban.error
    async def _unban_error(self, ctx, error):
        guild = ctx.guild
        msg = ctx.message
        cli = self.client.user
        red = discord.Color.dark_red()
        e_1 = str("""```css\nPlease pass in all required arguments.```""")
        e_2 = str("""```css\nYou do not have permission to use this command.```""")
        if isinstance(error, commands.MissingRequiredArgument):
            embed = discord.Embed(color=red, name=cli.display_name, timestamp=msg.created_at)
            embed.set_author(name="Command Failed", icon_url=cli.avatar_url)
            embed.add_field(name="Missing Required arguments", value=e_1, inline=False)
            embed.set_thumbnail(url=cli.avatar_url)
            embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
            await msg.send(embed=embed)
        elif isinstance(error, commands.MissingPermissions):
            embed = discord.Embed(color=red, name=cli.display_name, timestamp=msg.created_at)
            embed.set_author(name="Access denied", icon_url=cli.avatar_url)
            embed.add_field(name="Insufficient Permissions", value=e_2, inline=False)
            embed.set_thumbnail(url=cli.avatar_url)
            embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
            await msg.send(embed=embed)

    @commands.command(name="Purge", aliases=["p", "P", "purge"])
    @commands.has_permissions(manage_guild=True)
    async def _purge(self, ctx, amount: int):
        """Purges a specified amount of messages. Includes user pins."""
        msg = ctx.message
        author = ctx.author
        guild = ctx.guild
        ch = ctx.channel
        orange = discord.Color.dark_orange()
        for channel in guild.channels:
            if str(channel.name) == "????log":
                await ch.purge(limit=amount + 1)
                c_purge = (f"""```Purged {amount} messages in {ch.name}```""")
                embed = discord.Embed(color=orange, timestamp=msg.created_at)
                embed.set_author(name="Messages Purged", icon_url=self.client.user.avatar_url)
                embed.add_field(name=f"{author.display_name}", value=c_purge, inline=False)
                embed.set_thumbnail(url=self.client.user.avatar_url)
                embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
                await channel.send(embed=embed)

    @_purge.error
    async def _purge_error(self, ctx, error):
        guild = ctx.guild
        msg = ctx.message
        cli = self.client.user
        red = discord.Color.dark_red()
        e_1 = str("""```css\nPlease pass in all required arguments.```""")
        e_2 = str("""```css\nYou do not have permission to use this command.```""")
        if isinstance(error, commands.MissingRequiredArgument):
            embed = discord.Embed(color=red, name=cli.display_name, timestamp=msg.created_at)
            embed.set_author(name="Command Failed", icon_url=cli.avatar_url)
            embed.add_field(name="Missing Required arguments", value=e_1, inline=False)
            embed.set_thumbnail(url=cli.avatar_url)
            embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
            await msg.send(embed=embed)
        elif isinstance(error, commands.MissingPermissions):
            embed = discord.Embed(color=red, name=cli.display_name, timestamp=msg.created_at)
            embed.set_author(name="Access denied", icon_url=cli.avatar_url)
            embed.add_field(name="Insufficient Permissions", value=e_2, inline=False)
            embed.set_thumbnail(url=cli.avatar_url)
            embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
            await msg.send(embed=embed)


def setup(client):
    client.add_cog(Admin(client))

如果有帮助,我正在使用 discord.py rewrite。

【问题讨论】:

    标签: python python-3.x discord.py discord.py-rewrite


    【解决方案1】:

    消息事件只需要一个附加参数到self,即message。您不必将上下文传递给此事件。

    https://discordpy.readthedocs.io/en/latest/api.html?highlight=on_message#discord.on_message

    【讨论】:

    • 补充一下,因为代码还是用ctx,可以通过bot.get_contextdiscordpy.readthedocs.io/en/latest/ext/commands/…获取ctx对象
    • 这只是让它停止响应。没有错误,根本没有响应....
    • 您的机器人代码中是否有 另一个 on_message 事件处理程序?
    • 我最终将计数器改造成一个运行良好的自动响应系统。现在唯一仍然无法在 cog 中工作的是 set prefix 命令。
    • 如果有人可以让它工作,我还想从config.json加载default_prefix
    猜你喜欢
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多