Python 如何在discord.py中一次运行多个函数?
在我的bot中,我有一个函数,它每秒向字典中的值添加一次,以表示“付费员工”。我还有一个@client.command函数,显示发送命令时字典的键和值。虽然“paying”(付款)功能处于启用状态(始终),但查找功能不起作用,而on_消息功能起作用。如何使bot并行检测@client.command函数Python 如何在discord.py中一次运行多个函数?,python,discord.py,discord.py-rewrite,Python,Discord.py,Discord.py Rewrite,在我的bot中,我有一个函数,它每秒向字典中的值添加一次,以表示“付费员工”。我还有一个@client.command函数,显示发送命令时字典的键和值。虽然“paying”(付款)功能处于启用状态(始终),但查找功能不起作用,而on_消息功能起作用。如何使bot并行检测@client.command函数 import discord from discord.ext import commands from discord.ext import tasks import asyncio cli
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")
导入不一致
从discord.ext导入命令
从discord.ext导入任务
导入异步
client=commands.Bot(命令前缀=“/”)
工资单=[]
数据={}
#/start将为服务器上的每个人启动操作并管理工资单
#你准备好了吗
@客户端事件
_ready()上的异步定义:
全球数据
服务器=client.get_guild(670006903815929889)
#在执行命令时启动服务器上所有人的余额,并将其添加到工资单中
对于server.members中的人员:
person=str(person)
工资单追加(人)
数据[人]=整数(0)
打印(数据)
等待asyncio.sleep(1)
#以稳定的基本利率支付所有人
尽管如此:
薪金总额中的人士:
数据[人]+=10
打印(数据)
等待异步睡眠(60)
#留言
@客户端事件
异步def on_消息(ctx):
全球数据
balance=int(数据[str(ctx.author)])
数据[str(ctx.author)]-=5
如果balance命令功能将不起作用,因为您没有处理该命令。
为此,请在消息函数中添加一小行:
@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()
不要使用阻塞代码,也要使用命令框架。对于稳定的任务,您应该使用discord.py内置的任务
调度