【问题标题】:Trying To Call a command from outside an async尝试从异步外部调用命令
【发布时间】:2021-08-17 19:35:43
【问题描述】:

我有一个 discord bot (python),它有两个功能。

首先,它具有使用硬编码前缀在通道中键入的命令。其次,我使用线程,因此我可以在特定时间安排特定命令。这允许两者同时运行(该机器人不断线程化,并且由于它不在循环中,因此它允许使用其他命令。问题是,它没有按预期工作,我不确定我在做什么在这里做错了。任何帮助将不胜感激。

我已经尝试过这个命令的各种形式,下面是我尝试过的大约 40 种不同方法之一。如果您愿意,我确实可以发布迄今为止我尝试过的各种方法,但如果您知道一种以更简单的方式完成此操作的方法,我们将不胜感激。

请注意,除了 client.get_command 部分之外,一切都运行良好。我通过输入诸如“print(f'当前时间是{current_time}')之类的行来测试计数器和线程,所以我知道除了调用命令之外一切都是可操作的。

import discord
from discord.ext import commands, tasks
from dotenv import load_dotenv
from discord.utils import get
import os
import sqlite3
import datetime
from sqlite3 import Error
import time
import threading

def checkTime():
  threading.Timer(1, checkTime).start()

  now = datetime.datetime.now()

  current_time = now.strftime("%H:%M:%S")

  if current_time == '00:00:00':
    print('Its Time. . . ')
    client.get_command('manualcheckdisable')
  

checkTime()


@client.command()
async def manualcheckdisable(ctx):
  # Do things here manually by command, or on schedule at midnight

【问题讨论】:

  • 你应该看看pypi.org/project/aioschedule,或者discord.ext.tasks
  • 你只是得到命令,你没有调用它。一个更好的主意是简单地使用异步函数和discord.ext.tasks
  • 看看我的一个previous answers 来调用命令,虽然你总是需要ctx
  • 谢谢各位。在您的指导下,我已经解决了我的问题。我会发布答案。

标签: python discord.py


【解决方案1】:

感谢 cmets 的帮助,我能够通过进行一些更改来解决此问题:

首先,我让机器人在开始时运行循环:

@client.event
async def on_ready():
  guild = client.guilds[0]
  print('Bot Ready. . .')
  startloop.start()

接下来,我创建的任务如下:

@tasks.loop(seconds=30.0)
async def startloop():
  now = datetime.datetime.now()
  current_time = now.strftime("%H:%M")
  print(f'Current Time is {current_time}')
  if current_time == '00:00':
    print('Running Nightly Audit Loop. . .')# Do things. . .(about 150 lines of code)

最后,我知道这可能不是最佳做法,但它确实有效,这才是最重要的。我创建了一个新命令,它基本上是循环的副本,没有循环:

@client.command
async def manuallaunch(ctx):
  # Do things (about 150 lines of code)

感谢您为我指明了正确的方向。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    相关资源
    最近更新 更多