Aioschedule останавливает весь код, помогите
Я конечно тупой, но не думал что настолько. Пишу просто так бота в дискорде, и хочу что бы пользователь мог написать "таймер - 11:30", и в 11:30 бот бы что то сделал. Это работает, но при этом бот перестаёт отвечать на любые другие сообщения. Я понимаю что это из за while True. Я пытался вынести его в отдельный поток, но ничего не получилось. Обращаюсь к сверх разумным людям за помощью. Вот мой ужасный код:
import discord
from discord.ext import commands
from config import settings
import re
import secrets
from random import randint
import urllib
import os
import threading
from threading import Thread
import asyncio
import aioschedule as schedule
import pyttsx3
import requests
import time
from pyrandmeme import *
import random
from bs4 import BeautifulSoup
bot = commands.Bot(command_prefix = settings['prefix'])
engine = pyttsx3.init()
#настройка голоса
rate = engine.getProperty('rate') # getting details of current speaking rate
print (rate) #printing current voice rate
engine.setProperty('rate', 150) # setting up new voice rate
volume = engine.getProperty('volume') #getting to know current volume level (min=0 and max=1)
print (volume) #printing current volume level
engine.setProperty('volume',1.0) # setting up volume level between 0 and 1
voices = engine.getProperty('voices') #getting details of current voice
engine.setProperty('voice', voices[0].id) #changing index, changes voices. o for male
@bot.event
async def on_message(ctx):
text_without_chars = ctx.content.lower()
text_without_chars = re.sub(r'[()\"#/@;:<>{}=~|.?,$]', '', str(text_without_chars))
chunks = text_without_chars.split(' ')
print(chunks)
if ctx.author != bot.user:
if ctx.content.lower() == "хубик" or ctx.content.lower() == "нубик":
await ctx.reply("вы меня звали?")
elif ctx.content.lower() == "доброе утро" or ctx.content.lower() == "доброе":
ctx.reply("доброе утро")
elif ctx.content.lower() == "зачем" or ctx.content.lower() == "зочем" or ctx.content.lower() == "зач":
await ctx.reply("незнаю")
elif ctx.content.lower() == "ура победа":
await ctx.reply("ага")
elif ctx.content.lower() == "да":
await ctx.reply("ага")
elif ctx.content.lower() == "нет":
await ctx.reply("возможно")
elif set(['бот', 'уйди']).issubset(chunks) or set(['бот', 'уходи']).issubset(chunks) or set(['бот', 'замолчи']).issubset(chunks):
party = bot.get_emoji(854433622492839996)
await ctx.reply('Ну блин, {}'.format(party))
elif set(['выбери', 'игру']).issubset(chunks):
await ctx.reply(choose_from_variants(ctx.content))
elif 'таймер' in chunks:
timer_time = ctx.content.lower().split('-', 1)[1].split('.')[0]
await ctx.reply('Я уведомлю вас когда таймер закончится')
print(timer_time)
thread = Thread(target=await run_phrase_after_time(timer_time, ctx))
thread.setDaemon(True)
thread.start()
await bot.process_commands(ctx)
@bot.command(name="музыка")
async def music(ctx):
user=ctx.message.author
voice_channel=user.voice.channel
channel=None
# only play music if user is in a voice channel
if voice_channel != None:
# grab user's voice channel
channel=voice_channel.name
# create StreamPlayer
vc = await voice_channel.connect()
vc.play(discord.FFmpegPCMAudio(enable_music_random()), after=lambda e: print('готово', e))
vc.source = discord.PCMVolumeTransformer(vc.source)
vc.source.volume = 0.03
while vc.is_playing():
await asyncio.sleep(1)
# disconnect after the player has finished
vc.stop()
await vc.disconnect()
else:
await ctx.reply('зайди пожалуйста в голосовой канал')
def get_random_game():
script_dir = os.path.dirname(__file__)
rel_path = "games/"
abs_file_path = os.path.join(script_dir, rel_path)
with open(abs_file_path + "games.txt", encoding="utf-8") as file:
playlist = [row.strip() for row in file]
return secrets.choice(playlist)
def choose_from_variants(text):
variants = text.split('-', 1)[1].split('.')[0]
answers = variants.split(',')
return random.choice(answers)
"""async def meme():
url = "https://dtf.ru/kek/entries/new"
header = {
"user-agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.90 Safari/537.36"
}
r = requests.get(url, headers=header).text
soup = BeautifulSoup(r, 'html.parser')
bs = soup.find('div', class_='content-image')
bs2 = bs.find('div', class_='andropov_image')
list = open("list.txt", "w+")
link = (bs2['data-image-src']) # Сам парсер мемов
if link not in list:
with open("list.txt", "r+") as file:
file.write(link)
return str(link)
print(f"[{datetime.datetime.now()}] Отправил") # лог в консоль
else:
print(f"[{datetime.datetime.now()}] Новых мемов пока нет") # лог в консоль"""
def enable_music_random():
script_dir = os.path.dirname(__file__)
rel_path = "music/"
abs_file_path = os.path.join(script_dir, rel_path)
path=abs_file_path
file = random.choice(os.listdir(path))
audioFile = ".mp3"
try:
return path+file
except:
return "Не, сегодня без танцулек"
async def phrase_after_time(ctx):
script_dir = os.path.dirname(__file__)
rel_path = "phrases/"
abs_file_path = os.path.join(script_dir, rel_path)
try:
user = ctx.author
voice_channel = user.voice.channel
channel = None
# only play music if user is in a voice channel
if user.voice.channel != None:
# grab user's voice channel
channel = voice_channel.name
# create StreamPlayer
vc = await voice_channel.connect()
engine.save_to_file("алё, закругляемся, время прошло", abs_file_path+"phrase.wav")
engine.runAndWait()
vc.play(discord.FFmpegPCMAudio(abs_file_path+"phrase.wav"), after=lambda e: print('готово', e))
vc.source = discord.PCMVolumeTransformer(vc.source)
vc.source.volume = 0.1
while vc.is_playing():
await asyncio.sleep(1)
# disconnect after the player has finished
vc.stop()
await vc.disconnect()
else:
await ctx.reply('зайди пожалуйста в голосовой канал')
except:
await ctx.reply('закругляемся ребятки, всё')
return schedule.CancelJob
async def run_phrase_after_time(timer, ctx):
schedule.every().day.at(timer).do(phrase_after_time, ctx)
while True:
await schedule.run_pending()
time.sleep(0.1)
if __name__ == "__main__":
bot.run(settings['token'])
Ответы (1 шт):
Автор решения: LZLZZ
→ Ссылка
неважно, заменил time.sleep() на asyncio.sleep(), и всё заработало. Удивительно