有没有办法将参数从主 bot.py 文件中的命令传递到 cog discord.py

时间:2021-05-13 19:19:36

标签: python discord.py

所以,我想从这个命令传递一个参数(频道 ID):

@bot.command()
async def countingon(ctx):
    if (ctx.message.author.permissions_in(ctx.message.channel).manage_messages):
        bot.load_extension('cogs.counting')
        await ctx.send('Counting is on')
    else:
        await ctx.send("You can't do that!")

给一个齿轮:

import discord
from discord.ext import commands
from discord.ext.commands.core import command

a = 1
target : discord.Member
class counting(commands.Cog):
    def __init__(self, bot):
        self.bot = bot  

    

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.channel.id == ({argument here}):
    ...

我不知道如何做到这一点,所以我在这里问

1 个答案:

答案 0 :(得分:0)

将通道 ID 作为参数添加到 cog 构造函数:

class counting(commands.Cog):
    def __init__(self, bot, channel_id):
        self.bot = bot
        self.channel_id = channel_id

然后使用以下方法签入 on_message

@commands.Cog.listener()
async def on_message(self, message):
    if message.channel.id == self.channel_id:
        ...

要将频道 ID 传递给 cog,请使用 bot.add_cog 而不是 load_extension

from cogs import counting

@bot.command()
async def countingon(ctx):
    if ctx.author.permissions_in(ctx.channel).manage_messages:
        # you probably also need to check if the cog is already loaded here
        bot.add_cog(counting(bot, ctx.channel.id))
        await ctx.send("Counting is on")
    else:
        await ctx.send("You can't do that!")