2
2
from discord .ext import commands
3
3
from discord import app_commands
4
4
import numpy as np
5
+ import asyncio
5
6
6
7
class Calculator (commands .Cog ):
7
8
def __init__ (self , bot ):
@@ -10,19 +11,30 @@ def __init__(self, bot):
10
11
@app_commands .command (name = "calculator" , description = "数式を計算します" )
11
12
@app_commands .describe (expression = "計算したい数式を入力してください" )
12
13
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
+ )
18
23
embed = discord .Embed (
19
24
title = "計算結果" ,
20
25
description = f"数式: `{ expression } `" ,
21
26
color = discord .Color .green ()
22
27
)
23
28
embed .add_field (name = "結果" , value = f"`{ result } `" , inline = False )
24
29
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 )
26
38
27
39
async def setup (bot ):
28
40
await bot .add_cog (Calculator (bot ))
0 commit comments