Я создал бота, который пингует людей в определенное время дня (для развлечения, лол), но бот, похоже, случайным образом пингует в случайное время дня и не печатает сообщение на терминал, как следовало бы, если бы это было обычное сообщение. пинг. Это произошло уже дважды и вызвало большое разочарование, поскольку очевидно, что людям не нравится, когда их пингуют без причины. Я размещаю этого бота на Bot-Hosting.
Вот мой код:
import discord
from datetime import time, datetime, timezone, timedelta, today
from discord.ext import tasks, commands
from time import sleep
def run():
time_role = time(16,7,0, tzinfo=timezone(timedelta(hours=a certain timezone)))
time_person = time(16,7,0, tzinfo=timezone(timedelta(hours=another certain timezone)))
channel_id = # channel id
server_id = # server id
#gives the bot message content intent
intents = discord.Intents.default()
intents.message_content = True
TOKEN = "my token obviously"
client = discord.Client(intents = intents)
#pings @role A at time_role
@tasks.loop(time=time_role)
async def send_time():
await client.get_channel(channel_id).send("<@&role A id>")
await client.get_channel(channel_id).send("get ready guys")
print("sent role A ping at " + today().strftime('%m-%d %H:%M:%S'))
#the above two lines were NOT SENT along with the unexpected pings
#pings @person A at time_person
@tasks.loop(time=time_person)
async def send_person():
await client.get_channel(channel_id).send("<@person A id>")
await client.get_channel(channel_id).send("get ready person A")
print("sent person A ping at " + today().strftime('%m-%d %H:%M:%S'))
#the above two lines were NOT SENT along with the unexpected pings
@client.event
async def on_ready():
print(f"{client.user} is now online!\ntime: "today().strftime('%m-%d %H:%M:%S'))
if not send_time.is_running():
send_time.start()
print("started role ping")
if not send_person.is_running():
send_person.start()
print("started person ping")
client.run(TOKEN)
run()
Я думаю, проблема здесь в том, что у вашего timezone
есть проблемы с установкой правильного атрибута time=
или атрибут @tasks.loop
None
не работает так, как вы ожидаете - в целом я не могу найти причину вашей проблемы.
Но другая проблема, о которой упоминает ваш пользователь, иногда НЕ работает, может быть вызвана тем, что кеш бота не готов. В этом случае вы получите client.get_channel
за такие вещи, как await self.client.wait_until_ready()
— вам следует подождать, пока кеш бота не будет готов с помощью APScheduler
.
Вот почему я рекомендую вам переключиться на Cron
с timezone
, чтобы запланировать отправку упоминаний пользователей в определенное время.
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.cron import CronTrigger
from discord.ext import commands
import discord
client = discord.Client(intents = intents)
async def send_time():
# wait until cache is ready
await self.client.wait_until_ready()
await client.get_channel(channel_id).send("<@&role A id>")
await client.get_channel(channel_id).send("get ready guys")
print("sent role A ping at " + today().strftime('%m-%d %H:%M:%S'))
async def send_person():
# wait until cache is ready
await self.client.wait_until_ready()
await client.get_channel(channel_id).send("<@person A id>")
await client.get_channel(channel_id).send("get ready person A")
print("sent person A ping at " + today().strftime('%m-%d %H:%M:%S'))
@bot.event
async def on_ready():
print("Ready")
#initializing scheduler
scheduler = AsyncIOScheduler()
# add your functions to the scheduler
scheduler.add_job(send_time, CronTrigger(hour = "16", minute = "7", second = "0"))
scheduler.add_job(send_person, CronTrigger(hour = "16", minute = "7", second = "0"))
#starting the scheduler
scheduler.start()
добавление client.await_until_ready() сработало, спасибо!