python - 如何在 discord.py 中一次运行多个函数?
问题描述
在我的机器人中,我有一个函数可以每秒一次地向字典中的值添加值,以表示“付费员工”。我还有一个@client.command 函数,它在发送命令时显示字典的键和值。虽然“支付”功能(总是)打开,但查找功能不起作用,on_message 功能起作用。如何使机器人并行检测@client.command 函数?
import discord
from discord.ext import commands
from discord.ext import tasks
import asyncio
client = commands.Bot(command_prefix='/')
payroll = []
data = {}
# /start will start operations and manage payroll for everyone on the server
# will make it on_ready
@client.event
async def on_ready():
global data
server = client.get_guild(670006903815929889)
# starts balance for everyone on the server at the time of the command and adds them to the payroll
for person in server.members:
person = str(person)
payroll.append(person)
data[person] = int(0)
print(data)
await asyncio.sleep(1)
# pays everyone at a steady BASE rate
while True:
for person in payroll:
data[person] += 10
print(data)
await asyncio.sleep(60)
# on message
@client.event
async def on_message(ctx):
global data
balance = int(data[str(ctx.author)])
data[str(ctx.author)] -= 5
if balance <= 25 and ctx.author.id != 734119994761150585:
await ctx.channel.send('Be careful {author}! Your balance is ${balance}.')
if balance <= 0 and ctx.author.id != 734119994761150585:
# delete message
await ctx.channel.send('Oops! {author}, you have run out of money. As a consequence, you will be deducted $15.')
data[str(ctx.author)] -= 15
if message.startswith("/dm"):
await message.author.send('Hello World!')
# look-up stats
@client.command()
async def dm(message):
await message.author.send('stats go here')
client.run("token")
解决方案
由于您没有处理命令,因此命令功能将不起作用。为此,请在消息函数中添加小行:
@client.event()
async def on_message(message):
#YOUR CODE HERE
await client.process_commands(message)
对于持续运行函数或一次运行多个:您可以在函数中添加将持续运行或在给定时间差运行的任务。深入的文档可以在 discord.py 文档中找到。
代码片段:
from discord.ext import tasks
@tasks.loop(seconds = 5)
async def test_function():
#YOUR CODE
pass
@client.event
async def on_ready():
#TASK RUN
test_function.start()
推荐阅读
- python - Python按小时和分钟对数据进行子集化,忽略日期
- string - SwiftUI String 一个字符一个字符地显示
- google-apps-script - 使用 Appscript 将每列的最后一行替换为 G-Slides
- azure - 在 Azure AD 上,您在哪里看到失败的应用程序登录尝试
- cmd - 由于缺少管理员权限,我无法访问 F:/ 目录中的 SD 卡,如何使用命令提示符进行更改?
- android - Google Play 将在后台拒绝使用位置(Warning Email),Expo React native
- java - Selenium/Java 没有这样的元素异常在点击主页链接后的页面元素
- ios - 如何 popViewController 并发送回数据
- excel - 使用vba在单元格中编写公式
- javascript - VScode 不会识别书面代码的语法,但它会识别复制/粘贴的代码