-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
93 lines (77 loc) · 2.78 KB
/
bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import os
import asyncio
import dotenv
import discord
from discord import app_commands
from discord.ext import commands
# ======================================================================
dotenv.load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
if TOKEN is None:
raise Exception("DISCORD_TOKEN is not set")
ASG_NAME = os.getenv("ASG_NAME")
if ASG_NAME is None:
raise Exception("ASG_NAME is not set")
BOT_OWNER_ID = os.getenv("BOT_OWNER_ID")
COMMAND_PREFIX = os.getenv("COMMAND_PREFIX") or "¥"
intents = discord.Intents.default()
intents.reactions = True
bot = commands.Bot(command_prefix=COMMAND_PREFIX, intents=intents)
bot.ASG_NAME = ASG_NAME # type: ignore
if BOT_OWNER_ID is None:
BOT_OWNER_ID = bot.owner_id
else:
BOT_OWNER_ID = int(BOT_OWNER_ID)
# ======================================================================
async def load_cogs() -> None:
for file in os.listdir(f"{os.path.realpath(os.path.dirname(__file__))}/cogs"):
if file.endswith(".py"):
extension = file[:-3]
try:
await bot.load_extension(f"cogs.{extension}")
# bot.logger.info(f"Loaded extension '{extension}'")
print(f"Loaded extension '{extension}'")
except Exception as e:
exception = f"{type(e).__name__}: {e}"
print(f"Failed to load extension {extension}\n{exception}")
# bot.logger.error(f"Failed to load extension {extension}\n{exception}")
# --------------------------------------------------
@bot.tree.command(
name="stop",
description="stop bot (only bot owner)",
)
# is bot owner
@app_commands.check(lambda interaction: interaction.user.id == bot.owner_id)
async def stop(interaction: discord.Interaction):
"""
stop bot
:param interaction: interaction
:return: None
"""
await interaction.response.send_message("Botを終了します。", ephemeral=True)
await bot.close()
# when error, notify to bot owner
@bot.event
async def on_command_error(ctx: commands.Context, error: commands.CommandError):
"""
when error, notify to bot owner
:param ctx: context
:param error: error
:return: None
"""
print(f"エラーが発生しました。\n{error}")
# await ctx.send(f"エラーが発生しました。\n{error}")
if BOT_OWNER_ID is int:
owner_user = bot.get_user(BOT_OWNER_ID)
if owner_user is not None:
await owner_user.send(f"エラーが発生しました。```\n{error}```")
@bot.event
async def on_ready():
if bot.user is not None:
await load_cogs()
await bot.tree.sync()
print(f"Logged in as {bot.user.name} - {bot.user.id}")
print("------")
# --------------------------------------------------
if __name__ == "__main__":
bot.run(TOKEN)