[問題] 如何同時實現 ChatBot 和 Scheduled Code

看板Python作者 (九龍塘麵包粉)時間3年前 (2021/02/12 23:14), 編輯推噓0(002)
留言2則, 2人參與, 3年前最新討論串1/1
專案:一個很簡單的 Discord Bot IDE:repl.it 主要套件:discord 各位前輩好想問的問題應該算直白 就是希望DiscordBot 等待event同時也可以執行 code code 在下面 簡單解釋一下 有個最主要 Method get_quote() 功能是request一個api 回傳值是一句心靈雞湯 當discord 出現 command "$inspire" 時就會觸發 回傳一句心靈雞湯到聊天室 這是目前的功能 discord bot 是 event based 但如果今天想要建製一個新機制 讓他每天凌晨多執行一次 get_quote() 往聊天室丟一句心靈雞湯 原本的功能(應該說Chat Bot的傳統功能)是 event based 而想新加的功能我只會用很爛的方法, 用loop裡面放 conditional statement 檢查時間 但感覺兩個部分哪個前哪個後都不太對 想知道有甚麼方法可以同時執行 event based 和 loop 確不打架 目前有想到用多個 thread 一個執行 bot 一個執行 loop 不知道可不可行 以及有沒有更聰明的做法 以下是目前的 code 還請各位賜教 --- import discord import os import requests import json import random from replit import db from keepalive import keep_alive def get_quote(): response = requests.get("https://zenquotes.io/api/random") json_data = json.loads(response.text) print(json_data) quote = json_data[0]['q'] + " -" + json_data[0]['a'] return quote @client.event async def on_ready(): print("We have logged in as {0.user}".format(client)) @client.event async def on_message(msg): if msg.author == client.user: return if msg.content.startswith("$hello"): await msg.channel.send("hello") content = msg.content if content.startswith("$inspire"): message = get_quote() await msg.channel.send(message) client.run(os.getenv("TOKEN")) -- /╲ ▊ ▂ ▅ ◢ ▋▄▅▄ ▄ \ \▊▎/ ▎ ▄ ▏ ▎▄ ▄▃ ▎▏ ▆◢▊ ▂▃ ▊▎▆/ <R U Ready?> ▄▆ LOVELYZ 2nd Album -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 165.132.5.143 (韓國) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1613142848.A.8DD.html

02/13 02:19, 3年前 , 1F
discord.ext.tasks
02/13 02:19, 1F

02/13 13:56, 3年前 , 2F
喔 太感謝了 一定是我沒認真讀完documentation
02/13 13:56, 2F
文章代碼(AID): #1W9fj0ZT (Python)