Issue when running some commands from within cogs discord.py

北城余情 提交于 2020-06-29 03:59:07

问题


Ok so I'm having an issue running a couple commands from inside cogs. One command won't run regardless of what I put it into and the other simply won't run from within the cog.

The commands are set prefix and my message counter. [the message counter is actually a listener not a command but has the same issue].

The error they keep throwing is basically this:

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'

Here is my message_counter:

import discord
from discord.ext import commands
import discord.utils
import json

def load_counters():
    with open('counters.json', 'r') as f:
       counters = json.load(f)
    return counters

def save_counters(counters):
    with open('counters.json', 'w') as f:
       json.dump(counters, f, indent=4)

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

     @commands.Cog.listener()
     async def on_message(self, ctx, message):
         if "oof" in message.content:
             counters = load_counters()
             counters["oof"] += 1
             await ctx.send(str(counters["oof"]))
             save_counters(counters)
         elif "Thot" in message.content:
             counters = load_counters()
             counters["Thot"] += 1
             await ctx.send(str(counters["Thot"]))
             save_counters(counters)

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

And here is my set prefix command:

import discord
from discord.ext import commands
import discord.utils
import os
import json
with open("./data/config.json", "r") as configjsonFile:
    configData = json.load(configjsonFile)
    login_token = configData["discordtoken"]

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

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

client = commands.Bot(command_prefix=prefix)
client.remove_command('help')

@client.command(name="Prefix", aliases=["prefix", "setprefix"])
@commands.has_permissions(administrator=True)
async def _prefix(ctx, new_prefix):
    guild = ctx.guild
    for channel in guild.channels:
        if str(channel.name) == "modlog":
            prefixes[ctx.message.guild.id] = new_prefix
            with open("./data/prefixes.json", "w") as f:
                json.dump(prefixes, f, indent=4)
            embed = discord.Embed(color=discord.Color.dark_purple(), timestamp=ctx.message.created_at)
            embed.set_author(name=client.user.display_name, icon_url=client.user.avatar_url)
            embed.add_field(name="Prefix Updated", value=f"Successfully changed prefix changed to `{new_prefix}`")
            embed.set_thumbnail(url=client.user.avatar_url)
            embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
            await ctx.message.add_reaction(emoji="✅")
            await channel.send(embed=embed)


@_prefix.error
async def _prefix_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        if isinstance(error, commands.MissingRequiredArgument):
            guild = ctx.guild
            embed = discord.Embed(color=discord.Color.dark_red(), timestamp=ctx.message.created_at)
            embed.set_author(name="Command Failed", icon_url=client.user.avatar_url)
            embed.add_field(name="Missing Required arguments", value="Please pass in all required arguments.")
            embed.set_thumbnail(url=client.user.avatar_url)
            embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
            await ctx.message.add_reaction(emoji="⚠")
            await ctx.message.author.send(embed=embed)

        elif isinstance(error, commands.MissingPermissions):
            guild = ctx.guild
            embed = discord.Embed(color=discord.Color.dark_red, timestamp=ctx.message.created_at)
            embed.set_author(name="Access denied", icon_url=client.user.avatar_url)
            embed.add_field(name="Insufficient Permissions", value="You do not have permission to use this command")
            embed.set_thumbnail(url=client.user.avatar_url)
            embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
            await ctx.message.add_reaction(emoji="⛔")
            await ctx.message.author.send(embed=embed)

for filename in os.listdir("./cogs"):
    if filename.endswith(".py"):
        client.load_extension(f"cogs.{filename[:-3]}")

client.run(login_token)

As you can see the set prefix works out side a cog but my issue was getting it to work from inside a cog. And my message counter isn't working at all no matter where I load the counter.json or where i put the actual method for loading it.

In both cases I get the missing 1 required positional argument: 'message' error .

I was told to make a separate question for this since it would be hard to answer in a comment for my message_counter. I'm guessing the issue is the same issue for both of them? I'm not entirely sure but any help would be much appreciated.

As it is the set prefix command IS working, it's simply being loaded from my main.py file instead of from within a cog.

If it helps, I'm using discord.py rewrite.


回答1:


The message event only takes one additional parameter to self, which is message. You do not have to pass context into this event.

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



来源:https://stackoverflow.com/questions/62566015/issue-when-running-some-commands-from-within-cogs-discord-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!