JishoBot/cogs/kanji.py

91 lines
2.7 KiB
Python
Raw Normal View History

2020-08-11 13:52:13 +00:00
import discord
from discord.ext import commands
2020-08-11 14:56:19 +00:00
from utils import jisho
2020-08-11 13:52:13 +00:00
2020-08-11 15:34:22 +00:00
class JishoKanjiObject():
2020-08-11 16:07:31 +00:00
def __init__(self, query, owner):
2020-08-11 15:34:22 +00:00
self.response = jisho.JishoKanji(query)
self.total_pages = self.response.entries
self.page = 0
2020-08-11 16:07:31 +00:00
self.owner = owner
2020-08-11 15:34:22 +00:00
def prev(self):
self.page -= 1
if self.page < 0:
self.page = self.total_pages - 1
def next(self):
self.page += 1
if self.page >= self.total_pages:
self.page = 0
2020-08-11 13:52:13 +00:00
class Kanji(commands.Cog):
def __init__(self, bot):
self.bot = bot
2020-08-11 15:34:22 +00:00
self.activeObject = None
self.latestMessage = 0
async def createEmbed(self):
response = self.activeObject.response
node = response.nodes[self.activeObject.page]
embed = discord.Embed(
title = node.kanji,
url = node.url,
2020-08-11 15:38:38 +00:00
description = node.meaning,
2020-08-11 15:34:22 +00:00
colour = 0x56d926
)
if node.kun:
2020-08-11 16:31:20 +00:00
embed.add_field(name="Kun", value="".join(node.kun), inline=False)
2020-08-11 15:34:22 +00:00
if node.on:
2020-08-11 16:31:20 +00:00
embed.add_field(name="On", value="".join(node.on), inline=False)
2020-08-11 15:34:22 +00:00
2020-08-11 16:31:20 +00:00
embed.add_field(name=f"Radical: {node.radical[0]}", value=node.radical[1], inline=False)
embed.set_footer(text=f"Jōyō kanji (Grade {node.grade}) | JLPT level {node.jlpt}\t\t{self.activeObject.page + 1}/{self.activeObject.total_pages}")
2020-08-11 15:34:22 +00:00
return embed
@commands.Cog.listener()
async def on_reaction_add(self, reaction, user):
message = reaction.message
if message.id != self.latestMessage:
return
if user == self.bot.user:
return
2020-08-11 16:07:31 +00:00
if user.id != self.activeObject.owner:
return
2020-08-11 15:34:22 +00:00
if reaction.me:
if reaction.emoji == "⬅️":
self.activeObject.prev()
await reaction.remove(user)
if reaction.emoji == "➡️":
self.activeObject.next()
await reaction.remove(user)
embed = await self.createEmbed()
await message.edit(embed=embed)
2020-08-11 13:52:13 +00:00
@commands.command(name="kanji", description="Performs a Kanji search", usage="<kanji>", aliases=["k"])
@commands.cooldown(1, 5)
2020-08-11 14:56:19 +00:00
async def kanji(self, ctx, *, kanji: str = None):
if kanji is None:
return
2020-08-11 16:07:31 +00:00
self.activeObject = JishoKanjiObject(kanji, ctx.author.id)
2020-08-11 15:34:22 +00:00
embed = await self.createEmbed()
message = await ctx.send(embed=embed)
self.latestMessage = message.id
if self.activeObject.total_pages > 1:
await message.add_reaction("⬅️")
await message.add_reaction("➡️")
2020-08-11 13:52:13 +00:00
def setup(bot):
bot.add_cog(Kanji(bot))