解决了Discord.py的“on_message”在我执行“schedule”后无法工作的问题

2024-09-30 08:30:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉Python,所以我担心这对你们所有人来说都是一个愚蠢的问题,但我已经尽力解决了

我自己做了一个项目,制作一个机器人来做一些无聊的任务,只是为了好玩

首先,我做了一个函数,让它接收带有“on_message”事件的消息,效果很好。这是密码

import discord
import os

discordClient = discord.Client()

@discordClient.event  #event register
async def on_ready():  
    print('Logged in as {0.user}'.format(discordClient))
    await routineAnnouncer.createDisocrdRoutine(discordClient)

@discordClient.event
async def on_message(message):
    checked = False

    if message.author == discordClient.user:
      checked = True
      return
    else:
      print("Get Message {0.content} from {0.author.name} ({0.author.id}) @{0.channel.name} ({0.channel.id})".
      format(message))

#-------------------------- RUN ----------------------

print('Registering EVENTS COMPLETE')
discordClient.run(os.environ['discordToken'])

我在Repl.it上对它进行编码,“os.environ”是它检索.env的方式

以下是“on_ready”事件中使用的“routineAnnouncer”中的代码

import os  #ใช้ดึง .env (secret)
import schedule
import time

def scheduleAnnouncer(discordClient,announceType,announceDetail):
  print("Announcing {} {}".format(announceType,announceDetail))
  lzChannel = discordClient.get_channel(int(os.environ['lz_token_test']))
  discordClient.loop.create_task(lzChannel.send("Announcing {} {}".format(announceType,announceDetail)))

async def createDisocrdRoutine(discordClient):
  print("Registering CRONJOBS...")
  scheduleAnnouncer(discordClient,"headerTest","descTest")
  schedule.every(5).seconds.do(scheduleAnnouncer,discordClient,"header1","desc1")
  schedule.every(10).seconds.do(scheduleAnnouncer,discordClient,"header2","desc2")
  # while True:
    #   schedule.run_pending()
    #   time.sleep(5)

因此,它应该在连接准备好并设置调度文本后执行createdisocrdolotine()

如您所见,代码的最后一部分已注释。它应该是一个循环,触发通过discord发送到指定channel.id的预定文本

至此。代码运行良好。“on_message(message)”部分可以打印发送到频道的任何内容。 “scheduleAnnouncer”功能也可以正常工作。它可以向频道发送消息。 Discord ScreenRepl.it Screen

循环后的将取消注释“while:True”,以使计划正常工作。 循环工作正常。它打印出循环中显示的文本。但是discord无法检测到以前发送到同一频道的任何文本。甚至应该发送消息的“scheduleAnnouncer”功能也被破坏了。感觉就像一旦while:True“未注释,任何与不和谐有关的内容都会被打破。 Discord ScreenRepl.it Screen

我试着把日程安排分成另一个线程,但没有成功。我尝试使用其他cronjob管理,如cronjob、sched或其他。他们中的大多数人让我面对另一个问题

  • 我需要将参数发送到任务中(discordClient、announceType、announceDetail)
  • 我需要使用发送的具体日期/时间。不是每5秒的间隔。(需要发送的文本因时间和日期而异。周一的文本与周五的文本不同) 从这两个标准来看。“时间表”很合适,而且应该可以正常工作

先谢谢你。我不知道下一步该做什么或检查。每次我试图解决它。我总是循环回到“时间表”,并尝试一遍又一遍地处理它

我希望这些信息足够了。非常感谢您抽出时间


Tags: 文本importtrueformatmessageosondef
1条回答
网友
1楼 · 发布于 2024-09-30 08:30:18

time.sleep()不是异步的,因此它将冻结您的程序。使用await asyncio.sleep()。这是因为它暂停了整个程序,而不仅仅是该功能

The reason you’d want to use wait() here is because wait() is non-blocking, whereas time.sleep() is blocking. What this means is that when you use time.sleep(), you’ll block the main thread from continuing to run while it waits for the sleep() call to end. wait() solves this problem.

引用RealPython

相关问题 更多 >

    热门问题