Skip to content

Commit b33d0fe

Browse files
author
starpig1129
committed
Integrate all functions into slash command select action module to modularize
1 parent 7b88f75 commit b33d0fe

22 files changed

+805
-862
lines changed

bot.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
from motor.motor_asyncio import AsyncIOMotorClient
1515
from datetime import datetime
1616
from voicelink import VoicelinkException
17-
from gpt.choose_act import choose_act
17+
from gpt.choose_act import ActionHandler
1818
from gpt.sendmessage import gpt_message, load_and_index_dialogue_history, save_vector_store, vector_store
1919
from gpt.gpt_response_gen import get_model_and_tokenizer
2020
from logs import TimedRotatingFileHandler
@@ -52,7 +52,7 @@ def __init__(self, *args, **kwargs):
5252
sercet_key=func.tokens.sercet_key
5353
)
5454
self.loggers = {}
55-
55+
self.action_handler = ActionHandler(self)
5656
def setup_logger_for_guild(self, guild_name):
5757
if guild_name not in self.loggers:
5858
self.loggers[guild_name] = setup_logger(guild_name)
@@ -117,7 +117,7 @@ async def on_message(self, message: discord.Message, /) -> None:
117117

118118
message_to_edit = await message.reply("思考中...")
119119
try:
120-
execute_action = await choose_act(self,prompt, message, message_to_edit)
120+
execute_action = await self.action_handler.choose_act(prompt, message, message_to_edit)
121121
await execute_action(message_to_edit, self.dialogue_history, channel_id, prompt, message)
122122
except Exception as e:
123123
print(e)
@@ -152,7 +152,7 @@ async def on_message_edit(self, before: discord.Message, after: discord.Message)
152152
await msg.delete() # 删除之前的回复
153153

154154
message_to_edit = await after.reply("思考中...") # 创建新的回复
155-
execute_action = await choose_act(self,prompt, after, message_to_edit)
155+
execute_action = await self.action_handler.choose_act(prompt, after, message_to_edit)
156156
await execute_action(message_to_edit, self.dialogue_history, channel_id, prompt, after)
157157
except Exception as e:
158158
print(e)

choseAct_system_prompt.txt

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
Here is a list of tools that you have available to you:
2+
3+
def internet_search(query: str, search_type: str):
4+
"""
5+
Performs a web search based on the given query and search type
6+
If the conversation contains a URL, select url
7+
Args:
8+
query (str): Query to search the web with
9+
search_type (str): Type of search to perform (one of [general,eat,url, image, youtube])
10+
"""
11+
pass
12+
13+
def directly_answer(prompt:str):
14+
"""
15+
Calls a standard (un-augmented) AI chatbot to generate a response given the conversation history
16+
Args:
17+
prompt (str): prompt to generate the response with
18+
"""
19+
pass
20+
21+
def vqa_answer(prompt: str):
22+
"""
23+
Answers a question based on the given image
24+
Args:
25+
prompt (str): Prompt to generate the answer
26+
"""
27+
pass
28+
29+
def calculate(expression: str):
30+
"""
31+
Calculates the result of a mathematical expression with sympy
32+
Args:
33+
expression (str): Mathematical expression to calculate
34+
"""
35+
pass
36+
37+
def gen_img(prompt: str):
38+
"""
39+
Generates an image based on the given keyword and img using Stable Diffusion
40+
41+
Args:
42+
prompt (str): English keyword to generate the image
43+
"""
44+
pass
45+
46+
def query_schedule(user_name: str = None, query_type: str = 'next'):
47+
"""
48+
Queries the schedule information for the specified user
49+
50+
Args:
51+
user_name (str): If not provided, the command sender's ID will be used. Example: <@user_id>
52+
query_type (str): The type of query, can be 'next' (next class) or 'now' (current class)
53+
"""
54+
pass
55+
56+
def send_reminder(user_name: str = None, reminder_message, time_str):
57+
"""
58+
Queries the schedule information for the specified user
59+
60+
Args:
61+
user_name (str): If not provided, the command sender's ID will be used. Example: <@user_id>
62+
reminder_message (str): The reminder message to be sent.
63+
time_str (str): The reminder time in the format 'YYYY-MM-DD HH:MM:SS or a relative time like '10 minutes later'.
64+
"""
65+
pass
66+
67+
def manage_user_data(user_id: str, user_data: str = None, action: str = 'read'):
68+
"""
69+
Manages user data in a database.
70+
Example:
71+
User says: "User-related information"
72+
Action: Use manage_user_data with save action to update the address in the user's profile.
73+
User asks: "Ask users for relevant information"
74+
Action: Use manage_user_data with read action to retrieve and display the address.
75+
Args:
76+
user_id (str): If not provided, the command sender's ID will be used. Example: <@user_id>
77+
user_data (str): The data to be saved for the user. Required if action is 'save'.
78+
action (str): The action to perform. Can be 'read' or 'save'.
79+
"""
80+
pass
81+
82+
You are a multi-functional Discord bot assistant. Your role is to analyze user requests, choose the most appropriate tool(s) from the list above, and provide helpful responses. When using the gen_img tool, provide English prompts and add relevant tips.
83+
84+
To use a tool, write 'Action:' followed by a list of actions in JSON format, e.g.:
85+
Action:
86+
```json
87+
[
88+
{
89+
"tool_name": "tool name (one of [manage_user_data,vqa_answer,internet_search, directly_answer,calculate,gen_img,query_schedule,send_reminder])",
90+
"parameters": "the input to the tool"
91+
}
92+
]

cogs/Schedule.py

Lines changed: 50 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -1,106 +1,78 @@
11
import discord
2-
import discord.app_commands as app_commands
2+
from discord import app_commands
33
from discord.ext import commands
4-
from datetime import datetime, timedelta
4+
from datetime import datetime
55
import pytz
66
import json
77
import re
88

9-
weekday_map = {
10-
'Monday': '星期一',
11-
'Tuesday': '星期二',
12-
'Wednesday': '星期三',
13-
'Thursday': '星期四',
14-
'Friday': '星期五',
15-
'Saturday': '星期六',
16-
'Sunday': '星期日'
17-
}
18-
19-
20-
# 尋找下一節課的邏輯,考慮目前時間是第幾節課
21-
229
class ScheduleCog(commands.Cog):
2310
def __init__(self, bot):
2411
self.bot = bot
25-
def load_schedule_data(self, user_name):
12+
self.weekday_map = {
13+
'Monday': '星期一', 'Tuesday': '星期二', 'Wednesday': '星期三',
14+
'Thursday': '星期四', 'Friday': '星期五', 'Saturday': '星期六', 'Sunday': '星期日'
15+
}
16+
17+
@app_commands.command(name="schedule", description="查詢課表")
18+
@app_commands.describe(
19+
query_type="查詢類型(next: 下一節課,now: 當前課程)",
20+
user="要查詢的用戶(可選,默認為自己)"
21+
)
22+
async def schedule_command(self, interaction: discord.Interaction, query_type: str = 'next', user: discord.User = None):
23+
await interaction.response.defer(thinking=True)
24+
result = await self.query_schedule(user or interaction.user, query_type)
25+
await interaction.followup.send(result)
26+
27+
async def query_schedule(self, user: discord.User, query_type: str = 'next',message_to_edit: discord.Message = None) -> str:
28+
try:
29+
if message_to_edit :
30+
await message_to_edit.edit(content="看看課表")
31+
schedule = self.load_schedule_data(user.id)
32+
if schedule is None:
33+
return "找不到課表數據。"
34+
35+
tz = pytz.timezone('Asia/Taipei')
36+
now = datetime.now(tz)
37+
current_hour = now.hour
38+
current_weekday = now.strftime('%A')
39+
current_class_period = current_hour - 7 # 8點開始為第1節
40+
current_weekday_cn = self.weekday_map.get(current_weekday, "")
41+
42+
if query_type == 'next':
43+
return f'用戶 {user.name} 的課表:{self.find_next_class(schedule, current_weekday_cn, current_class_period)}'
44+
elif query_type == 'now':
45+
return f'用戶 {user.name} 的課表:{self.find_current_class(schedule, current_weekday_cn, current_class_period)}'
46+
else:
47+
return '無效的查詢類型'
48+
except Exception as e:
49+
return f'查詢課表時發生錯誤:{str(e)}'
50+
51+
def load_schedule_data(self, user_id: int) -> dict:
2652
try:
27-
match = re.search(r'\d+', user_name)
28-
user_id = match.group()
2953
with open(f'./data/schedule_data/{user_id}.json', 'r', encoding='utf-8') as f:
3054
return json.load(f)
3155
except FileNotFoundError:
3256
return None
33-
34-
def find_next_class_corrected(self,schedule, weekday, current_class_period):
35-
print('目前是',weekday,'第',current_class_period,'節')
57+
58+
def find_next_class(self, schedule: dict, weekday: str, current_class_period: int) -> str:
3659
if weekday not in schedule:
3760
return "今日無課程。"
38-
current_class_period = current_class_period if current_class_period > 0 else 0
39-
# 從目前節次開始搜尋下一節有安排的課
61+
current_class_period = max(current_class_period, 0)
4062
for period in range(current_class_period, len(schedule[weekday])):
41-
if schedule[weekday][period]: # 如果這個時間段有課
63+
if schedule[weekday][period]:
4264
class_info = schedule[weekday][period]
43-
4465
return f"下一節課是第 {period + 1}{period+8}:10開始,課名:{class_info['課名']},教授:{class_info['教授']},教室:{class_info['教室']}。"
4566
return "今日已無其他課程。"
46-
47-
def find_current_class(self, schedule, weekday, current_class_period):
48-
print('目前是',weekday,'第',current_class_period,'節')
49-
if schedule is None:
50-
return "找不到課表數據。"
51-
67+
68+
def find_current_class(self, schedule: dict, weekday: str, current_class_period: int) -> str:
5269
if weekday not in schedule:
5370
return "今日無課程。"
54-
# 檢查目前時間對應的課程
55-
if schedule[weekday][current_class_period-1]:
71+
if 0 <= current_class_period - 1 < len(schedule[weekday]) and schedule[weekday][current_class_period-1]:
5672
class_info = schedule[weekday][current_class_period-1]
5773
return f"目前是第 {current_class_period} 節,課名:{class_info['課名']},教授:{class_info['教授']},教室:{class_info['教室']}。"
5874
else:
5975
return "現在沒在上課。"
60-
61-
@commands.hybrid_command(name="課表")
62-
@app_commands.describe(user_name="@用戶名稱,用於查詢特定用戶的課表")
63-
async def query_schedule(self, ctx, user_name: str = None):
64-
if user_name is None:
65-
user_name = f"<@{ctx.author.id}>" # 若未提供ID,則使用命令發送者的ID
66-
schedule = self.load_schedule_data(str(user_name))
67-
if schedule is None:
68-
await ctx.send("找不到課表數據。")
69-
return
70-
# 獲取當前時間和星期
71-
tz = pytz.timezone('Asia/Taipei')
72-
now = datetime.now(tz)
73-
current_hour = now.hour
74-
current_weekday = now.strftime('%A')
75-
# 計算目前是第幾節課
76-
current_class_period = current_hour - 7 # 8點開始為第1節
77-
# 將英文星期轉換為中文
78-
current_weekday_cn = weekday_map.get(current_weekday, "")
79-
response = self.find_next_class_corrected(schedule, current_weekday_cn, current_class_period)
80-
await ctx.send(user_name+response)
81-
82-
@commands.hybrid_command(name="正在上")
83-
@app_commands.describe(user_name="@用戶名稱,用於查詢特定用戶的現在課程")
84-
async def query_current_class(self, ctx, user_name: str = None):
85-
if user_name is None:
86-
user_name = f"<@{ctx.author.id}>" # 若未提供ID,則使用命令發送者的ID
87-
schedule = self.load_schedule_data(str(user_name))
88-
if schedule is None:
89-
await ctx.send("找不到課表數據。")
90-
return
91-
# 獲取當前時間和星期
92-
tz = pytz.timezone('Asia/Taipei')
93-
now = datetime.now(tz)
94-
current_hour = now.hour
95-
current_weekday = now.strftime('%A')
96-
# 計算目前是第幾節課
97-
current_class_period = current_hour - 7 # 8點開始為第1節
98-
# 將英文星期轉換為中文
99-
current_weekday_cn = weekday_map.get(current_weekday, "")
100-
response = self.find_current_class(schedule, current_weekday_cn, current_class_period)
101-
await ctx.send(user_name+response)
102-
103-
10476

10577
async def setup(bot):
106-
await bot.add_cog(ScheduleCog(bot))
78+
await bot.add_cog(ScheduleCog(bot))

cogs/eatselect.py

Lines changed: 0 additions & 61 deletions
This file was deleted.

0 commit comments

Comments
 (0)