我正在为我的discord bot进行琐事/测验功能,并希望为wait_for做一个“检查”功能,以便我可以将参数传递给要过滤的对象/针对,因为目前我正在“硬编码”测验问题和功能。虽然我希望拥有一个包含所有琐事问题的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)
`
在我的主文件中调用上述函数“测验”:
`
@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)
`
答案 0 :(得分:0)
我能够通过将我的问题和答案存储在JSON文件中来解决自己的问题,对于“检查”功能,我做了一个全局变量“ triv”,并在quiz函数中使用json的答案进行了更新文件,然后调用wait_for and check函数。效果很好。
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)