33import sys
44import asyncio
55from pymongo import MongoClient
6- from discord .ext import commands
6+ from discord .ext import commands , tasks
77import re
88
99# Add src directory to sys.path for imports
@@ -29,6 +29,9 @@ def __init__(self):
2929client_db = MongoClient (DB_DSN )
3030bot .db = client_db ["discord_analyzer" ]
3131
32+ STATUS_ROTATION_SECONDS = 30
33+ status_index = 0
34+
3235
3336def setup_db ():
3437 # メッセージコレクションのインデックス設定
@@ -65,10 +68,45 @@ def setup_db():
6568
6669@bot .event
6770async def on_ready ():
71+ if not rotate_status .is_running ():
72+ rotate_status .start ()
6873 await bot .tree .sync ()
6974 print (f"Logged in as { bot .user } " )
7075
7176
77+ async def _get_status_messages ():
78+ def collect_counts ():
79+ messages_count = bot .db .messages .estimated_document_count ()
80+ collected_user_count = len (bot .db .messages .distinct ("user_id" ))
81+ return messages_count , collected_user_count
82+
83+ messages_count , collected_user_count = await asyncio .to_thread (collect_counts )
84+ guild_count = len (bot .guilds )
85+
86+ return [
87+ f"{ messages_count :,} 件のメッセージを収集中" ,
88+ f"{ guild_count :,} サーバーに参加中" ,
89+ f"{ collected_user_count :,} ユーザー分を収集中" ,
90+ ]
91+
92+
93+ @tasks .loop (seconds = STATUS_ROTATION_SECONDS )
94+ async def rotate_status ():
95+ global status_index
96+ statuses = await _get_status_messages ()
97+ if not statuses :
98+ return
99+
100+ current_status = statuses [status_index % len (statuses )]
101+ status_index += 1
102+ await bot .change_presence (activity = discord .Game (name = current_status ))
103+
104+
105+ @rotate_status .before_loop
106+ async def before_rotate_status ():
107+ await bot .wait_until_ready ()
108+
109+
72110@bot .event
73111async def on_message (message ):
74112 if message .author .bot :
0 commit comments