mirror of
https://github.com/nonebot/nonebot2.git
synced 2025-07-28 08:41:29 +00:00
Update docs
This commit is contained in:
@ -5,7 +5,7 @@ from nonebot import on_command, CommandSession
|
||||
# 这里 weather 为命令的名字,同时允许使用别名「天气」「天气预报」「查天气」
|
||||
@on_command('weather', aliases=('天气', '天气预报', '查天气'))
|
||||
async def weather(session: CommandSession):
|
||||
# 从 Session 对象中获取城市名称(city),如果当前不存在,则询问用户
|
||||
# 从会话状态(session.state)中获取城市名称(city),如果当前不存在,则询问用户
|
||||
city = session.get('city', prompt='你想查询哪个城市的天气呢?')
|
||||
# 获取城市的天气预报
|
||||
weather_report = await get_weather_of_city(city)
|
||||
@ -19,13 +19,22 @@ async def weather(session: CommandSession):
|
||||
async def _(session: CommandSession):
|
||||
# 去掉消息首尾的空白符
|
||||
stripped_arg = session.current_arg_text.strip()
|
||||
if session.current_key:
|
||||
# 如果当前正在向用户询问更多信息(本例中只有可能是要查询的城市),则直接赋值
|
||||
session.args[session.current_key] = stripped_arg
|
||||
elif stripped_arg:
|
||||
# 如果当前没有在询问,但用户已经发送了内容,则理解为要查询的城市
|
||||
# 这种情况通常是用户直接将城市名跟在命令名后面,作为参数传入
|
||||
session.args['city'] = stripped_arg
|
||||
|
||||
if session.is_first_run:
|
||||
# 该命令第一次运行(第一次进入命令会话)
|
||||
if stripped_arg:
|
||||
# 第一次运行参数不为空,意味着用户直接将城市名跟在命令名后面,作为参数传入
|
||||
# 例如用户可能发送了:天气 南京
|
||||
session.state['city'] = stripped_arg
|
||||
return
|
||||
|
||||
if not stripped_arg:
|
||||
# 用户没有发送有效的城市名称(而是发送了空白字符),则提示重新输入
|
||||
# 这里 session.pause() 将会发送消息并暂停当前会话(该行后面的代码不会被运行)
|
||||
session.pause('要查询的城市名称不能为空呢,请重新输入')
|
||||
|
||||
# 如果当前正在向用户询问更多信息(例如本例中的要查询的城市),且用户输入有效,则放入会话状态
|
||||
session.state[session.current_key] = stripped_arg
|
||||
|
||||
|
||||
async def get_weather_of_city(city: str) -> str:
|
||||
|
Reference in New Issue
Block a user