如何以动态方式使用与"wait_for"一起使用的 Discord.py"检查"参数/函数?我想将参数传递给"检查"函数



我正在为我的discord机器人制作一个琐事/测验功能,并想为wait_fo制作一个"check"函数,我可以将参数传递给它,以确定根据/反对什么进行筛选,因为目前我正在对测验问题和功能进行"硬编码"。虽然我希望有一个JSON文件,其中包含所有琐碎的问题,我可以从中随机选择问题,并将答案传递给检查函数,而不是我目前所拥有的:

编辑:我已经想好了,并在下面留下了我的解决方案作为答案。

`

import os
import discord
import json
import random
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
def obama_check(message):
obama = ['Barack Obama', 'barack obama']
content = message.content.lower()
return any(t in content for t in obama)
async def quiz(ctx, cache_msg, bot):
for reaction in cache_msg.reactions:
async for user in reaction.users():
users = []
users.append(user)
await new_msg.edit(content=":confetti_ball: Game Starting!! :confetti_ball:")
await asyncio.sleep(1)
await new_msg.edit(content="Who is the 44th president of the United States?")
obama = ['Barack Obama', 'barack obama']
msg = await bot.wait_for('message', check=obama_check)
if msg:
await msg.add_reaction('✅')
await ctx.send(str(msg.author.name) + "wins this one")
await asyncio.sleep(2)
await new_msg.edit(content="What is the name of Han Solo’s ship?")
msg = await bot.wait_for('message', check=hansolo_check)
if msg:
await msg.add_reaction('✅')
await ctx.send(str(msg.author.name) + "wins this one")
await asyncio.sleep(2)

`

我想让它发挥作用的一些伪代码:

`

await new_msg.edit(content=rndm_question.question)
msg = await bot.wait_for('message', check=check(ctx, message, rndm_question.answer_list))
if msg:
await msg.add_reaction('✅')
await ctx.send(str(msg.author.name) + "wins this one")
await asyncio.sleep(2)

`

上面的函数"quiz"在我的主文件中被调用如下:

`

@bot.command()
async def test(ctx):
msg = await ctx.send('TEST')
await msg.add_reaction('✅')
await asyncio.sleep(5)
users = []
cache_msg = discord.utils.get(bot.cached_messages, id=msg.id)
await quiz(ctx, cache_msg, bot)

`

我能够通过将我的问题+答案存储在JSON文件中来解决我自己的问题,对于"check"函数,我制作了一个全局var"triv",在调用wait_fo和check函数之前,它会在quiz函数中用JSON文件中的答案更新。它运行得很好。

triv = []
async def play_trivia(new_msg, ctx, bot):
with open("trivia_questions.json", 'r') as f:
trivia = json.load(f)
data = trivia['items']
random.shuffle(data)
for item in data:
flag = 0
for key in item:
q = item['q']
a = item['a']
if flag < 1:
flag += 1
await new_msg.edit(content=q)
global triv
triv = a
msg = await bot.wait_for('message', check=check)
if msg:
await msg.add_reaction('✅')
await ctx.send(str(msg.author.name) + "wins this one")
await asyncio.sleep(2)
else:
flag += 1
await ctx.send(q)
triv = a
msg = await bot.wait_for('message', check=check)
if msg:
await msg.add_reaction('✅')
await ctx.send(str(msg.author.name) + "wins this one!!")
await asyncio.sleep(2)
def check(message):
content = message.content.lower()
return any(t in content for t in triv)

最新更新