【问题标题】:How do I use schedule py and Discord py together?如何同时使用 schedule py 和 Discord py?
【发布时间】:2021-06-07 23:01:18
【问题描述】:

主要目标: 每星期三 08:00

向频道发送消息

这是我当前的代码:

import schedule
import time
import discord
import asyncio
from discord.ext import commands, tasks
from discord.ext.tasks import loop

client = discord.Client()

# IMPORTANT
channel = 
botToken = ""

async def sendloop():
  while True:
    schedule.run_pending()
    await asyncio.sleep(1)

@client.event
async def on_ready():
        general_channel = client.get_channel(channel)
        print('ready')
        schedule.every(2).seconds.do(lambda:loop.create_task(general_channel.send('TEST')))

client.run(botToken)

到目前为止,没有任何错误,只是停留在“就绪”状态。我是使用 VS Code 的初学者。

【问题讨论】:

  • 欢迎来到 Stack Overflow!你是不是想在某个地方给sendloop()打电话?
  • 你好,@Coder-256!老实说,这是我从 Discord 上的 discord.py 服务器获得的解决方案。在官方 schedule py 文档中,while 循环可以独立存在。我不知道他为什么要为此创建一个函数。 pypi.org/project/schedule
  • 看起来sendloop() 函数的目的是异步运行,但它不应该有太大的区别,无论哪种方式都有效。如果您选择这种方式,我认为您需要在文件底部添加asyncio.run(sendloop())之类的内容。

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


【解决方案1】:

我不建议使用调度程序,因为不和谐扩展 task 可以与您尝试在代码中实现的相同:

from discord.ext import commands, tasks

ch = id_channel
client = commands.Bot(command_prefix='.')
TOKEN = "Token"

#every week at this time, you can change this to seconds=2 
#to replicate what you have been testing
@tasks.loop(hours=168) 
async def every_wednesday():
    message_channel = client.get_channel(ch)
    await message_channel.send("Your message")

@every_wednesday.before_loop
async def before():
    await client.wait_until_ready()

every_wednesday.start()

client.run(TOKEN)

如果您要在您希望它重复的时间运行此代码,它会完成您想要的。另一种方法是检查before() 函数,如果您不想等待并在您希望它运行的那一天运行代码,则检查它是否是运行的正确时间。

但如果你真的想使用日程安排模块,这篇文章可以帮到你:Discord.py Time Schedule

【讨论】:

    猜你喜欢
    • 2020-10-07
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 2019-06-19
    • 2021-06-15
    • 2021-04-24
    相关资源
    最近更新 更多