【问题标题】:Print the time a command was used into Terminal. -Discord.py (Rewrite)将命令使用的时间打印到终端中。 -Discord.py(重写)
【发布时间】:2020-08-09 09:10:32
【问题描述】:

我目前正在用python(重写)编写一个不和谐的机器人,我想打印一个命令的使用时间以及它是什么命令进入终端。

import sys, discord, random, os, datetime, time
from discord.ext import commands
from datetime import datetime

client = commands.Bot(command_prefix = ';')



# Startup

@client.event
async def on_ready():
    print('Commands is online.')

def ConsoleCMD(cmd):
    print((datetime.now().strftime('%H:%M:%S')),f"\tSomeone used the '{cmd}' command!")


# ----I'm not sure if this is necessary but I'll include it just in case----

@client.command()
async def load(ctx, extension):
    client.load_extension(f'cogs.{extension}')
    print('Loaded')

@client.command()
async def unload(ctx, extension):
    client.unload_extension(f'cogs.{extension}')
    print('Unloaded')

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

#----------------


# Commands

@client.command()
async def test(ctx):
    await ctx.send('Testing, Testing 1 2 3')
    ConsoleCMD(test)

client.run('Insert ID here')

主文件有效,但是当我包含 cogs 时,它不起作用

这是齿轮之一:

import discord, time, os, sys, datetime
from discord.ext import commands
from datetime import datetime

class Fun(commands.Cog):

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

    # Events

    @commands.Cog.listener()
    async def on_ready(self):
        print('Fun is online.')

    def ConsoleCMD(cmd):
        print((datetime.now().strftime('%H:%M:%S')),f"\tSomeone used the '{cmd}' command!")


    # Commands

    @commands.command()
    async def ping(self, ctx):
        await ctx.send('Pong!')
        ConsoleCMD(ping)


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

这是输出:

discord.ext.commands.errors.CommandInvokeError:命令引发异常:NameError:未定义名称“ConsoleCMD”

【问题讨论】:

  • 如果您打算对每个命令都执行此操作,那么使用 on_command 事件可能是明智之举,这样您就不必为每个命令重复代码

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


【解决方案1】:

您创建的函数在一个类中,必须通过该类调用。查看 Corey Schafer 的 this playlist 以更好地理解类和 OOP。
要完成这项工作,您必须使用 self 调用该方法,并将 self 作为参数添加到 ConsoleCMD

def ConsoleCMD(self, cmd):
    print((datetime.now().strftime('%H:%M:%S')),f"\tSomeone used the '{cmd}' command!")

@commands.command()
async def ping(self, ctx):
    await ctx.send('Pong!')
    self.ConsoleCMD(self, "ping")

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 2013-04-14
    • 2019-01-30
    • 1970-01-01
    • 2019-12-22
    • 2020-10-19
    • 2021-07-15
    • 1970-01-01
    相关资源
    最近更新 更多