Skip to content

Commit 39cc55c

Browse files
committed
feat: 計算処理を非同期に変更し、タイムアウトエラーハンドリングを追加
1 parent 2e61db9 commit 39cc55c

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

cogs/commands/calculator.py

+18-6
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from discord.ext import commands
33
from discord import app_commands
44
import numpy as np
5+
import asyncio
56

67
class Calculator(commands.Cog):
78
def __init__(self, bot):
@@ -10,19 +11,30 @@ def __init__(self, bot):
1011
@app_commands.command(name="calculator", description="数式を計算します")
1112
@app_commands.describe(expression="計算したい数式を入力してください")
1213
async def calculator(self, interaction: discord.Interaction, expression: str):
13-
await interaction.response.defer(thinking=True)
14-
allowed_names = {k: v for k, v in np.__dict__.items() if not k.startswith("__")}
15-
allowed_names.update({"abs": abs, "round": round})
16-
result = eval(expression, {"__builtins__": {}}, allowed_names)
17-
14+
await interaction.response.defer(thinking=True)
15+
allowed_names = {k: v for k, v in np.__dict__.items() if not k.startswith("__")}
16+
allowed_names.update({"abs": abs, "round": round})
17+
18+
try:
19+
result = await asyncio.wait_for(
20+
asyncio.to_thread(eval, expression, {"__builtins__": {}}, allowed_names),
21+
timeout=5.0
22+
)
1823
embed = discord.Embed(
1924
title="計算結果",
2025
description=f"数式: `{expression}`",
2126
color=discord.Color.green()
2227
)
2328
embed.add_field(name="結果", value=f"`{result}`", inline=False)
2429
embed.set_footer(text="計算完了 🎉")
25-
await interaction.followup.send(embed=embed)
30+
except asyncio.TimeoutError:
31+
embed = discord.Embed(
32+
title="エラー",
33+
description="計算がタイムアウトしました。5秒以内に完了しませんでした。",
34+
color=discord.Color.red()
35+
)
36+
37+
await interaction.followup.send(embed=embed)
2638

2739
async def setup(bot):
2840
await bot.add_cog(Calculator(bot))

0 commit comments

Comments
 (0)