作者yoche2000 (九龙塘面包粉)
看板Python
标题[问题] 如何同时实现 ChatBot 和 Scheduled Code
时间Fri Feb 12 23:14:02 2021
专案:一个很简单的 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://webptt.com/cn.aspx?n=bbs/Python/M.1613142848.A.8DD.html
1F:→ zerof: discord.ext.tasks 02/13 02:19
2F:→ yoche2000: 喔 太感谢了 一定是我没认真读完documentation 02/13 13:56