import os
import random
import time
from pathlib import Path
import discord
from dotenv import load_dotenv
load_dotenv(Path(__file__).with_name('.env'))
token = os.getenv('DISCORD_TOKEN', '').strip()
channel_text = os.getenv('BOT_CHANNEL_ID', '').strip()
if not token or not (channel_text.isascii() and channel_text.isdecimal()):
raise RuntimeError('.envのDISCORD_TOKENとBOT_CHANNEL_IDを確認してください')
channel_id = int(channel_text)
if channel_id <= 0:
raise RuntimeError('BOT_CHANNEL_IDが不正です')
intents = discord.Intents.none()
intents.guilds = True
intents.guild_messages = True
intents.message_content = True
client = discord.Client(intents=intents, allowed_mentions=discord.AllowedMentions.none())
last_reply = 0.0
@client.event
async def on_ready():
print(f'接続完了: {client.user}')
@client.event
async def on_message(message: discord.Message):
global last_reply
if message.guild is None or message.channel.id != channel_id:
return
if message.author.bot or message.webhook_id is not None:
return
command = message.content.strip()
if command not in {'!hello', '!omikuji'}:
return
now = time.monotonic()
if now - last_reply < 2:
return
last_reply = now
if command == '!hello':
name = discord.utils.escape_markdown(message.author.display_name)
text = f'{name}さん、こんにちは!'
else:
fortunes = ['大吉', '中吉', '小吉', '吉', '末吉', '凶', '大凶']
text = f'今回のおみくじは「{random.choice(fortunes)}」です。'
try:
await message.channel.send(text, suppress_embeds=True)
except discord.HTTPException as exc:
print(f'送信できませんでした: {type(exc).__name__}')
if __name__ == '__main__':
client.run(token)