Skip to content

Instantly share code, notes, and snippets.

@4Kaylum
Created September 6, 2019 22:29
Show Gist options
  • Save 4Kaylum/65adcb99788d87b80411e4058d8f641f to your computer and use it in GitHub Desktop.
Save 4Kaylum/65adcb99788d87b80411e4058d8f641f to your computer and use it in GitHub Desktop.
A bot that gives you a set of random trivia questions
"""A bot that gives you random trivia questions and you have to vote on an answer"""
import random
import asyncio
import html
import discord
from discord.ext import commands
from cogs import utils
class Trivia(utils.Cog):
def __init__(self, bot:utils.CustomBot):
super().__init__(bot)
@commands.command()
async def trivia(self, ctx:commands.Context):
"""Gives you some random trivia"""
url = "https://opentdb.com/api.php"
params = {
"amount": 1,
"type": "multiple"
}
async with self.bot.session.get(url, params=params) as r:
data = await r.json()
embed = discord.Embed(title=html.unescape(data['results'][0]['question']), colour=0xffff00)
answers = data['results'][0]['incorrect_answers'] + [data['results'][0]['correct_answer']]
random.shuffle(answers)
correct_answer_index = answers.index(data['results'][0]['correct_answer'])
for emoji, ans in zip('ABCD', answers):
embed.add_field(name=emoji, value=ans)
message = await ctx.send(embed=embed)
reactions = ["🇦", "🇧", "🇨", "🇩"]
for i in reactions:
await message.add_reaction(i)
async with ctx.typing():
await asyncio.sleep(10)
message = await ctx.channel.fetch_message(message.id)
correct_reaction = [i for i in message.reactions if i.emoji == reactions[correct_answer_index]][0]
correctly_answering = [i for i in await correct_reaction.users().flatten() if not i.bot]
if correctly_answering:
await ctx.send(f"The correct answer is: `{data['results'][0]['correct_answer']}`! {', '.join([i.mention for i in correctly_answering])} got it right!")
else:
await ctx.send(f"The correct answer is: `{data['results'][0]['correct_answer']}`! Nobody got it right!")
def setup(bot):
x = Trivia(bot)
bot.add_cog(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment