【问题标题】:Python discord bot schedulingPython不和谐机器人调度
【发布时间】:2020-07-22 12:31:44
【问题描述】:

我现在正在计算 d-day 并注意到不和谐的机器人。我需要我的机器人每 12 小时发送一次 d-day 计数消息。我怎样才能做到这一点??

import discord
from discord.ext import commands
from bs4 import BeautifulSoup as bs
import asyncio
import requests

bot = commands.Bot(command_prefix='?')

html = requests.get('https://superkts.com/cal/d_day/20200504')
soup = bs(html.text, 'html.parser')
data1 = soup.find('article', {'class': 'result'}).text

html = requests.get('https://superkts.com/cal/d_day/20201203')
soup = bs(html.text, 'html.parser')
data2 = soup.find('article', {'class': 'result'}).text

html = requests.get('https://superkts.com/cal/d_day/20220105')
soup = bs(html.text, 'html.parser')
data3 = soup.find('article', {'class': 'result'}).text

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')

@bot.command()
async def notice(ctx):
    await ctx.send("문준영 입대" + data1)
    await ctx.send("신원호 수능" + data2)
    await ctx.send("김수한 전역" + data3)

bot.run('TOKEN')

【问题讨论】:

  • 如果您使用的是 Windows,您还应该考虑使用 Windows 任务计划程序。
  • 只是想在代码级别完成

标签: python discord discord.py


【解决方案1】:

如果您只想每 12 小时重复一次,可以将消息放入循环中,并在末尾添加 sleep

@bot.command()
async def notice(ctx):
    while True:
        await ctx.send("문준영 입대" + data1)
        await ctx.send("신원호 수능" + data2)
        await ctx.send("김수한 전역" + data3)
        await asyncio.sleep(12 * 60 * 60)

【讨论】:

  • 感谢您的快速重播^^ 我认为您的代码每次输入“?notice”时都会安排时间,对吗?我只希望在我输入命令时和每 12 点出现该消息。我怎么做这个??
  • 抱歉,您想要每天凌晨 12 点还是每 12 小时一次?您是只想随处发布一份通知,还是每个频道只发一份通知,还是每个公会只发一份通知?
  • 抱歉,我的错误解释让您感到困惑。我希望每天凌晨 12 点,这里只有一个通知。
  • 您可能想考虑使用tasks 而不是commands。让before_loop 等到凌晨 12 点,然后将循环计时器设置为 24 小时。
  • 我尝试使用你说的任务......(下面的代码由我回答)但这次它每秒钟发送一次消息我做错了什么吗?我试图每隔几秒检查一下现在是 12AM,如果是真的,就向频道发送消息。
猜你喜欢
  • 2021-10-30
  • 2021-05-27
  • 2021-07-15
  • 2021-03-29
  • 2021-07-11
  • 2021-03-25
  • 2018-08-13
  • 1970-01-01
  • 2018-11-10
相关资源
最近更新 更多