AstrBot 4.13.2__py3-none-any.whl → 4.14.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. astrbot/builtin_stars/astrbot/main.py +0 -6
  2. astrbot/builtin_stars/session_controller/main.py +1 -2
  3. astrbot/cli/__init__.py +1 -1
  4. astrbot/core/agent/agent.py +2 -1
  5. astrbot/core/agent/handoff.py +14 -1
  6. astrbot/core/agent/runners/tool_loop_agent_runner.py +14 -1
  7. astrbot/core/agent/tool.py +5 -0
  8. astrbot/core/astr_agent_run_util.py +21 -3
  9. astrbot/core/astr_agent_tool_exec.py +178 -3
  10. astrbot/core/astr_main_agent.py +980 -0
  11. astrbot/core/astr_main_agent_resources.py +453 -0
  12. astrbot/core/computer/computer_client.py +10 -1
  13. astrbot/core/computer/tools/fs.py +22 -14
  14. astrbot/core/config/default.py +84 -58
  15. astrbot/core/core_lifecycle.py +43 -1
  16. astrbot/core/cron/__init__.py +3 -0
  17. astrbot/core/cron/events.py +67 -0
  18. astrbot/core/cron/manager.py +376 -0
  19. astrbot/core/db/__init__.py +60 -0
  20. astrbot/core/db/po.py +31 -0
  21. astrbot/core/db/sqlite.py +120 -0
  22. astrbot/core/event_bus.py +0 -1
  23. astrbot/core/message/message_event_result.py +21 -3
  24. astrbot/core/pipeline/process_stage/method/agent_sub_stages/internal.py +111 -580
  25. astrbot/core/pipeline/scheduler.py +0 -2
  26. astrbot/core/platform/astr_message_event.py +5 -5
  27. astrbot/core/platform/platform.py +9 -0
  28. astrbot/core/platform/platform_metadata.py +2 -0
  29. astrbot/core/platform/sources/dingtalk/dingtalk_adapter.py +1 -0
  30. astrbot/core/platform/sources/qqofficial/qqofficial_platform_adapter.py +1 -0
  31. astrbot/core/platform/sources/qqofficial_webhook/qo_webhook_adapter.py +1 -0
  32. astrbot/core/platform/sources/webchat/webchat_adapter.py +1 -0
  33. astrbot/core/platform/sources/wecom/wecom_adapter.py +1 -0
  34. astrbot/core/platform/sources/wecom_ai_bot/wecomai_adapter.py +1 -0
  35. astrbot/core/platform/sources/weixin_official_account/weixin_offacc_adapter.py +1 -0
  36. astrbot/core/provider/entities.py +1 -1
  37. astrbot/core/skills/skill_manager.py +9 -8
  38. astrbot/core/star/context.py +8 -0
  39. astrbot/core/star/filter/custom_filter.py +3 -3
  40. astrbot/core/star/register/star_handler.py +1 -1
  41. astrbot/core/subagent_orchestrator.py +96 -0
  42. astrbot/core/tools/cron_tools.py +174 -0
  43. astrbot/core/utils/history_saver.py +31 -0
  44. astrbot/core/utils/trace.py +4 -0
  45. astrbot/dashboard/routes/__init__.py +4 -0
  46. astrbot/dashboard/routes/cron.py +174 -0
  47. astrbot/dashboard/routes/log.py +36 -0
  48. astrbot/dashboard/routes/plugin.py +11 -0
  49. astrbot/dashboard/routes/skills.py +12 -37
  50. astrbot/dashboard/routes/subagent.py +117 -0
  51. astrbot/dashboard/routes/tools.py +41 -14
  52. astrbot/dashboard/server.py +3 -0
  53. {astrbot-4.13.2.dist-info → astrbot-4.14.1.dist-info}/METADATA +21 -2
  54. {astrbot-4.13.2.dist-info → astrbot-4.14.1.dist-info}/RECORD +57 -51
  55. astrbot/builtin_stars/astrbot/process_llm_request.py +0 -308
  56. astrbot/builtin_stars/reminder/main.py +0 -266
  57. astrbot/builtin_stars/reminder/metadata.yaml +0 -4
  58. astrbot/core/pipeline/process_stage/utils.py +0 -219
  59. {astrbot-4.13.2.dist-info → astrbot-4.14.1.dist-info}/WHEEL +0 -0
  60. {astrbot-4.13.2.dist-info → astrbot-4.14.1.dist-info}/entry_points.txt +0 -0
  61. {astrbot-4.13.2.dist-info → astrbot-4.14.1.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,376 @@
1
+ import asyncio
2
+ import json
3
+ from collections.abc import Awaitable, Callable
4
+ from datetime import datetime, timezone
5
+ from typing import TYPE_CHECKING, Any
6
+ from zoneinfo import ZoneInfo
7
+
8
+ from apscheduler.schedulers.asyncio import AsyncIOScheduler
9
+ from apscheduler.triggers.cron import CronTrigger
10
+ from apscheduler.triggers.date import DateTrigger
11
+
12
+ from astrbot import logger
13
+ from astrbot.core.agent.tool import ToolSet
14
+ from astrbot.core.cron.events import CronMessageEvent
15
+ from astrbot.core.db import BaseDatabase
16
+ from astrbot.core.db.po import CronJob
17
+ from astrbot.core.platform.message_session import MessageSession
18
+ from astrbot.core.provider.entites import ProviderRequest
19
+ from astrbot.core.utils.history_saver import persist_agent_history
20
+
21
+ if TYPE_CHECKING:
22
+ from astrbot.core.star.context import Context
23
+
24
+
25
+ class CronJobManager:
26
+ """Central scheduler for BasicCronJob and ActiveAgentCronJob."""
27
+
28
+ def __init__(self, db: BaseDatabase):
29
+ self.db = db
30
+ self.scheduler = AsyncIOScheduler()
31
+ self._basic_handlers: dict[str, Callable[..., Any]] = {}
32
+ self._lock = asyncio.Lock()
33
+ self._started = False
34
+
35
+ async def start(self, ctx: "Context"):
36
+ self.ctx: Context = ctx # star context
37
+ async with self._lock:
38
+ if self._started:
39
+ return
40
+ self.scheduler.start()
41
+ self._started = True
42
+ await self.sync_from_db()
43
+
44
+ async def shutdown(self):
45
+ async with self._lock:
46
+ if not self._started:
47
+ return
48
+ self.scheduler.shutdown(wait=False)
49
+ self._started = False
50
+
51
+ async def sync_from_db(self):
52
+ jobs = await self.db.list_cron_jobs()
53
+ for job in jobs:
54
+ if not job.enabled or not job.persistent:
55
+ continue
56
+ if job.job_type == "basic" and job.job_id not in self._basic_handlers:
57
+ logger.warning(
58
+ "Skip scheduling basic cron job %s due to missing handler.",
59
+ job.job_id,
60
+ )
61
+ continue
62
+ self._schedule_job(job)
63
+
64
+ async def add_basic_job(
65
+ self,
66
+ *,
67
+ name: str,
68
+ cron_expression: str,
69
+ handler: Callable[..., Any | Awaitable[Any]],
70
+ description: str | None = None,
71
+ timezone: str | None = None,
72
+ payload: dict | None = None,
73
+ enabled: bool = True,
74
+ persistent: bool = False,
75
+ ) -> CronJob:
76
+ job = await self.db.create_cron_job(
77
+ name=name,
78
+ job_type="basic",
79
+ cron_expression=cron_expression,
80
+ timezone=timezone,
81
+ payload=payload or {},
82
+ description=description,
83
+ enabled=enabled,
84
+ persistent=persistent,
85
+ )
86
+ self._basic_handlers[job.job_id] = handler
87
+ if enabled:
88
+ self._schedule_job(job)
89
+ return job
90
+
91
+ async def add_active_job(
92
+ self,
93
+ *,
94
+ name: str,
95
+ cron_expression: str | None,
96
+ payload: dict,
97
+ description: str | None = None,
98
+ timezone: str | None = None,
99
+ enabled: bool = True,
100
+ persistent: bool = True,
101
+ run_once: bool = False,
102
+ run_at: datetime | None = None,
103
+ ) -> CronJob:
104
+ # If run_once with run_at, store run_at in payload for later reference.
105
+ if run_once and run_at:
106
+ payload = {**payload, "run_at": run_at.isoformat()}
107
+ job = await self.db.create_cron_job(
108
+ name=name,
109
+ job_type="active_agent",
110
+ cron_expression=cron_expression,
111
+ timezone=timezone,
112
+ payload=payload,
113
+ description=description,
114
+ enabled=enabled,
115
+ persistent=persistent,
116
+ run_once=run_once,
117
+ )
118
+ if enabled:
119
+ self._schedule_job(job)
120
+ return job
121
+
122
+ async def update_job(self, job_id: str, **kwargs) -> CronJob | None:
123
+ job = await self.db.update_cron_job(job_id, **kwargs)
124
+ if not job:
125
+ return None
126
+ self._remove_scheduled(job_id)
127
+ if job.enabled:
128
+ self._schedule_job(job)
129
+ return job
130
+
131
+ async def delete_job(self, job_id: str) -> None:
132
+ self._remove_scheduled(job_id)
133
+ self._basic_handlers.pop(job_id, None)
134
+ await self.db.delete_cron_job(job_id)
135
+
136
+ async def list_jobs(self, job_type: str | None = None) -> list[CronJob]:
137
+ return await self.db.list_cron_jobs(job_type)
138
+
139
+ def _remove_scheduled(self, job_id: str):
140
+ if self.scheduler.get_job(job_id):
141
+ self.scheduler.remove_job(job_id)
142
+
143
+ def _schedule_job(self, job: CronJob):
144
+ if not self._started:
145
+ self.scheduler.start()
146
+ self._started = True
147
+ try:
148
+ tzinfo = None
149
+ if job.timezone:
150
+ try:
151
+ tzinfo = ZoneInfo(job.timezone)
152
+ except Exception:
153
+ logger.warning(
154
+ "Invalid timezone %s for cron job %s, fallback to system.",
155
+ job.timezone,
156
+ job.job_id,
157
+ )
158
+ if job.run_once:
159
+ run_at_str = None
160
+ if isinstance(job.payload, dict):
161
+ run_at_str = job.payload.get("run_at")
162
+ run_at_str = run_at_str or job.cron_expression
163
+ if not run_at_str:
164
+ raise ValueError("run_once job missing run_at timestamp")
165
+ run_at = datetime.fromisoformat(run_at_str)
166
+ if run_at.tzinfo is None and tzinfo is not None:
167
+ run_at = run_at.replace(tzinfo=tzinfo)
168
+ trigger = DateTrigger(run_date=run_at, timezone=tzinfo)
169
+ else:
170
+ trigger = CronTrigger.from_crontab(job.cron_expression, timezone=tzinfo)
171
+ self.scheduler.add_job(
172
+ self._run_job,
173
+ id=job.job_id,
174
+ trigger=trigger,
175
+ args=[job.job_id],
176
+ replace_existing=True,
177
+ misfire_grace_time=30,
178
+ )
179
+ asyncio.create_task(
180
+ self.db.update_cron_job(
181
+ job.job_id, next_run_time=self._get_next_run_time(job.job_id)
182
+ )
183
+ )
184
+ except Exception as e:
185
+ logger.error(f"Failed to schedule cron job {job.job_id}: {e!s}")
186
+
187
+ def _get_next_run_time(self, job_id: str):
188
+ aps_job = self.scheduler.get_job(job_id)
189
+ return aps_job.next_run_time if aps_job else None
190
+
191
+ async def _run_job(self, job_id: str):
192
+ job = await self.db.get_cron_job(job_id)
193
+ if not job or not job.enabled:
194
+ return
195
+ start_time = datetime.now(timezone.utc)
196
+ await self.db.update_cron_job(
197
+ job_id, status="running", last_run_at=start_time, last_error=None
198
+ )
199
+ status = "completed"
200
+ last_error = None
201
+ try:
202
+ if job.job_type == "basic":
203
+ await self._run_basic_job(job)
204
+ elif job.job_type == "active_agent":
205
+ await self._run_active_agent_job(job, start_time=start_time)
206
+ else:
207
+ raise ValueError(f"Unknown cron job type: {job.job_type}")
208
+ except Exception as e: # noqa: BLE001
209
+ status = "failed"
210
+ last_error = str(e)
211
+ logger.error(f"Cron job {job_id} failed: {e!s}", exc_info=True)
212
+ finally:
213
+ next_run = self._get_next_run_time(job_id)
214
+ await self.db.update_cron_job(
215
+ job_id,
216
+ status=status,
217
+ last_run_at=start_time,
218
+ last_error=last_error,
219
+ next_run_time=next_run,
220
+ )
221
+ if job.run_once:
222
+ # one-shot: remove after execution regardless of success
223
+ await self.delete_job(job_id)
224
+
225
+ async def _run_basic_job(self, job: CronJob):
226
+ handler = self._basic_handlers.get(job.job_id)
227
+ if not handler:
228
+ raise RuntimeError(f"Basic cron job handler not found for {job.job_id}")
229
+ payload = job.payload or {}
230
+ result = handler(**payload) if payload else handler()
231
+ if asyncio.iscoroutine(result):
232
+ await result
233
+
234
+ async def _run_active_agent_job(self, job: CronJob, start_time: datetime):
235
+ payload = job.payload or {}
236
+ session_str = payload.get("session")
237
+ if not session_str:
238
+ raise ValueError("ActiveAgentCronJob missing session.")
239
+ note = payload.get("note") or job.description or job.name
240
+
241
+ extras = {
242
+ "cron_job": {
243
+ "id": job.job_id,
244
+ "name": job.name,
245
+ "type": job.job_type,
246
+ "run_once": job.run_once,
247
+ "description": job.description,
248
+ "note": note,
249
+ "run_started_at": start_time.isoformat(),
250
+ "run_at": (
251
+ job.payload.get("run_at") if isinstance(job.payload, dict) else None
252
+ ),
253
+ },
254
+ "cron_payload": payload,
255
+ }
256
+
257
+ await self._woke_main_agent(
258
+ message=note,
259
+ session_str=session_str,
260
+ extras=extras,
261
+ )
262
+
263
+ async def _woke_main_agent(
264
+ self,
265
+ *,
266
+ message: str,
267
+ session_str: str,
268
+ extras: dict,
269
+ ):
270
+ """Woke the main agent to handle the cron job message."""
271
+ from astrbot.core.astr_main_agent import (
272
+ MainAgentBuildConfig,
273
+ _get_session_conv,
274
+ build_main_agent,
275
+ )
276
+ from astrbot.core.astr_main_agent_resources import (
277
+ PROACTIVE_AGENT_CRON_WOKE_SYSTEM_PROMPT,
278
+ SEND_MESSAGE_TO_USER_TOOL,
279
+ )
280
+
281
+ try:
282
+ session = (
283
+ session_str
284
+ if isinstance(session_str, MessageSession)
285
+ else MessageSession.from_str(session_str)
286
+ )
287
+ except Exception as e: # noqa: BLE001
288
+ logger.error(f"Invalid session for cron job: {e}")
289
+ return
290
+
291
+ cron_event = CronMessageEvent(
292
+ context=self.ctx,
293
+ session=session,
294
+ message=message,
295
+ extras=extras or {},
296
+ message_type=session.message_type,
297
+ )
298
+
299
+ # judge user's role
300
+ umo = cron_event.unified_msg_origin
301
+ cfg = self.ctx.get_config(umo=umo)
302
+ cron_payload = extras.get("cron_payload", {}) if extras else {}
303
+ sender_id = cron_payload.get("sender_id")
304
+ admin_ids = cfg.get("admins_id", [])
305
+ if admin_ids:
306
+ cron_event.role = "admin" if sender_id in admin_ids else "member"
307
+ if cron_payload.get("origin", "tool") == "api":
308
+ cron_event.role = "admin"
309
+
310
+ config = MainAgentBuildConfig(
311
+ tool_call_timeout=3600,
312
+ llm_safety_mode=False,
313
+ )
314
+ req = ProviderRequest()
315
+ conv = await _get_session_conv(event=cron_event, plugin_context=self.ctx)
316
+ req.conversation = conv
317
+ # finetine the messages
318
+ context = json.loads(conv.history)
319
+ if context:
320
+ req.contexts = context
321
+ context_dump = req._print_friendly_context()
322
+ req.contexts = []
323
+ req.system_prompt += (
324
+ "\n\nBellow is you and user previous conversation history:\n"
325
+ f"---\n"
326
+ f"{context_dump}\n"
327
+ f"---\n"
328
+ )
329
+ cron_job_str = json.dumps(extras.get("cron_job", {}), ensure_ascii=False)
330
+ req.system_prompt += PROACTIVE_AGENT_CRON_WOKE_SYSTEM_PROMPT.format(
331
+ cron_job=cron_job_str
332
+ )
333
+ req.prompt = (
334
+ "You are now responding to a scheduled task"
335
+ "Proceed according to your system instructions. "
336
+ "Output using same language as previous conversation."
337
+ "After completing your task, summarize and output your actions and results."
338
+ )
339
+ if not req.func_tool:
340
+ req.func_tool = ToolSet()
341
+ req.func_tool.add_tool(SEND_MESSAGE_TO_USER_TOOL)
342
+
343
+ result = await build_main_agent(
344
+ event=cron_event, plugin_context=self.ctx, config=config, req=req
345
+ )
346
+ if not result:
347
+ logger.error("Failed to build main agent for cron job.")
348
+ return
349
+
350
+ runner = result.agent_runner
351
+ async for _ in runner.step_until_done(30):
352
+ # agent will send message to user via using tools
353
+ pass
354
+ llm_resp = runner.get_final_llm_resp()
355
+ cron_meta = extras.get("cron_job", {}) if extras else {}
356
+ summary_note = (
357
+ f"[CronJob] {cron_meta.get('name') or cron_meta.get('id', 'unknown')}: {cron_meta.get('description', '')} "
358
+ f" triggered at {cron_meta.get('run_started_at', 'unknown time')}, "
359
+ )
360
+ if llm_resp and llm_resp.role == "assistant":
361
+ summary_note += (
362
+ f"I finished this job, here is the result: {llm_resp.completion_text}"
363
+ )
364
+
365
+ await persist_agent_history(
366
+ self.ctx.conversation_manager,
367
+ event=cron_event,
368
+ req=req,
369
+ summary_note=summary_note,
370
+ )
371
+ if not llm_resp:
372
+ logger.warning("Cron job agent got no response")
373
+ return
374
+
375
+
376
+ __all__ = ["CronJobManager"]
@@ -13,6 +13,7 @@ from astrbot.core.db.po import (
13
13
  CommandConfig,
14
14
  CommandConflict,
15
15
  ConversationV2,
16
+ CronJob,
16
17
  Persona,
17
18
  PersonaFolder,
18
19
  PlatformMessageHistory,
@@ -511,6 +512,65 @@ class BaseDatabase(abc.ABC):
511
512
  """Get paginated session conversations with joined conversation and persona details, support search and platform filter."""
512
513
  ...
513
514
 
515
+ # ====
516
+ # Cron Job Management
517
+ # ====
518
+
519
+ @abc.abstractmethod
520
+ async def create_cron_job(
521
+ self,
522
+ name: str,
523
+ job_type: str,
524
+ cron_expression: str | None,
525
+ *,
526
+ timezone: str | None = None,
527
+ payload: dict | None = None,
528
+ description: str | None = None,
529
+ enabled: bool = True,
530
+ persistent: bool = True,
531
+ run_once: bool = False,
532
+ status: str | None = None,
533
+ job_id: str | None = None,
534
+ ) -> CronJob:
535
+ """Create and persist a cron job definition."""
536
+ ...
537
+
538
+ @abc.abstractmethod
539
+ async def update_cron_job(
540
+ self,
541
+ job_id: str,
542
+ *,
543
+ name: str | None = None,
544
+ cron_expression: str | None = None,
545
+ timezone: str | None = None,
546
+ payload: dict | None = None,
547
+ description: str | None = None,
548
+ enabled: bool | None = None,
549
+ persistent: bool | None = None,
550
+ run_once: bool | None = None,
551
+ status: str | None = None,
552
+ next_run_time: datetime.datetime | None = None,
553
+ last_run_at: datetime.datetime | None = None,
554
+ last_error: str | None = None,
555
+ ) -> CronJob | None:
556
+ """Update fields of a cron job by job_id."""
557
+ ...
558
+
559
+ @abc.abstractmethod
560
+ async def delete_cron_job(self, job_id: str) -> None:
561
+ """Delete a cron job by its public job_id."""
562
+ ...
563
+
564
+ @abc.abstractmethod
565
+ async def get_cron_job(self, job_id: str) -> CronJob | None:
566
+ """Fetch a cron job by job_id."""
567
+ ...
568
+
569
+ @abc.abstractmethod
570
+ async def list_cron_jobs(self, job_type: str | None = None) -> list[CronJob]:
571
+ """List cron jobs, optionally filtered by job_type."""
572
+ ...
573
+
514
574
  # ====
515
575
  # Platform Session Management
516
576
  # ====
astrbot/core/db/po.py CHANGED
@@ -139,6 +139,37 @@ class Persona(TimestampMixin, SQLModel, table=True):
139
139
  )
140
140
 
141
141
 
142
+ class CronJob(TimestampMixin, SQLModel, table=True):
143
+ """Cron job definition for scheduler and WebUI management."""
144
+
145
+ __tablename__: str = "cron_jobs"
146
+
147
+ id: int | None = Field(
148
+ default=None,
149
+ primary_key=True,
150
+ sa_column_kwargs={"autoincrement": True},
151
+ )
152
+ job_id: str = Field(
153
+ max_length=64,
154
+ nullable=False,
155
+ unique=True,
156
+ default_factory=lambda: str(uuid.uuid4()),
157
+ )
158
+ name: str = Field(max_length=255, nullable=False)
159
+ description: str | None = Field(default=None, sa_type=Text)
160
+ job_type: str = Field(max_length=32, nullable=False) # basic | active_agent
161
+ cron_expression: str | None = Field(default=None, max_length=255)
162
+ timezone: str | None = Field(default=None, max_length=64)
163
+ payload: dict = Field(default_factory=dict, sa_type=JSON)
164
+ enabled: bool = Field(default=True)
165
+ persistent: bool = Field(default=True)
166
+ run_once: bool = Field(default=False)
167
+ status: str = Field(default="scheduled", max_length=32)
168
+ last_run_at: datetime | None = Field(default=None)
169
+ next_run_time: datetime | None = Field(default=None)
170
+ last_error: str | None = Field(default=None, sa_type=Text)
171
+
172
+
142
173
  class Preference(TimestampMixin, SQLModel, table=True):
143
174
  """This class represents preferences for bots."""
144
175
 
astrbot/core/db/sqlite.py CHANGED
@@ -15,6 +15,7 @@ from astrbot.core.db.po import (
15
15
  CommandConfig,
16
16
  CommandConflict,
17
17
  ConversationV2,
18
+ CronJob,
18
19
  Persona,
19
20
  PersonaFolder,
20
21
  PlatformMessageHistory,
@@ -33,6 +34,7 @@ from astrbot.core.db.po import (
33
34
 
34
35
  NOT_GIVEN = T.TypeVar("NOT_GIVEN")
35
36
  TxResult = T.TypeVar("TxResult")
37
+ CRON_FIELD_NOT_SET = object()
36
38
 
37
39
 
38
40
  class SQLiteDatabase(BaseDatabase):
@@ -1576,3 +1578,121 @@ class SQLiteDatabase(BaseDatabase):
1576
1578
  ),
1577
1579
  )
1578
1580
  return result.scalar_one_or_none()
1581
+
1582
+ # ====
1583
+ # Cron Job Management
1584
+ # ====
1585
+
1586
+ async def create_cron_job(
1587
+ self,
1588
+ name: str,
1589
+ job_type: str,
1590
+ cron_expression: str | None,
1591
+ *,
1592
+ timezone: str | None = None,
1593
+ payload: dict | None = None,
1594
+ description: str | None = None,
1595
+ enabled: bool = True,
1596
+ persistent: bool = True,
1597
+ run_once: bool = False,
1598
+ status: str | None = None,
1599
+ job_id: str | None = None,
1600
+ ) -> CronJob:
1601
+ async with self.get_db() as session:
1602
+ session: AsyncSession
1603
+ async with session.begin():
1604
+ job = CronJob(
1605
+ name=name,
1606
+ job_type=job_type,
1607
+ cron_expression=cron_expression,
1608
+ timezone=timezone,
1609
+ payload=payload or {},
1610
+ description=description,
1611
+ enabled=enabled,
1612
+ persistent=persistent,
1613
+ run_once=run_once,
1614
+ status=status or "scheduled",
1615
+ )
1616
+ if job_id:
1617
+ job.job_id = job_id
1618
+ session.add(job)
1619
+ await session.flush()
1620
+ await session.refresh(job)
1621
+ return job
1622
+
1623
+ async def update_cron_job(
1624
+ self,
1625
+ job_id: str,
1626
+ *,
1627
+ name: str | None | object = CRON_FIELD_NOT_SET,
1628
+ cron_expression: str | None | object = CRON_FIELD_NOT_SET,
1629
+ timezone: str | None | object = CRON_FIELD_NOT_SET,
1630
+ payload: dict | None | object = CRON_FIELD_NOT_SET,
1631
+ description: str | None | object = CRON_FIELD_NOT_SET,
1632
+ enabled: bool | None | object = CRON_FIELD_NOT_SET,
1633
+ persistent: bool | None | object = CRON_FIELD_NOT_SET,
1634
+ run_once: bool | None | object = CRON_FIELD_NOT_SET,
1635
+ status: str | None | object = CRON_FIELD_NOT_SET,
1636
+ next_run_time: datetime | None | object = CRON_FIELD_NOT_SET,
1637
+ last_run_at: datetime | None | object = CRON_FIELD_NOT_SET,
1638
+ last_error: str | None | object = CRON_FIELD_NOT_SET,
1639
+ ) -> CronJob | None:
1640
+ async with self.get_db() as session:
1641
+ session: AsyncSession
1642
+ async with session.begin():
1643
+ updates: dict = {}
1644
+ for key, val in {
1645
+ "name": name,
1646
+ "cron_expression": cron_expression,
1647
+ "timezone": timezone,
1648
+ "payload": payload,
1649
+ "description": description,
1650
+ "enabled": enabled,
1651
+ "persistent": persistent,
1652
+ "run_once": run_once,
1653
+ "status": status,
1654
+ "next_run_time": next_run_time,
1655
+ "last_run_at": last_run_at,
1656
+ "last_error": last_error,
1657
+ }.items():
1658
+ if val is CRON_FIELD_NOT_SET:
1659
+ continue
1660
+ updates[key] = val
1661
+
1662
+ stmt = (
1663
+ update(CronJob)
1664
+ .where(col(CronJob.job_id) == job_id)
1665
+ .values(**updates)
1666
+ .execution_options(synchronize_session="fetch")
1667
+ )
1668
+ await session.execute(stmt)
1669
+ result = await session.execute(
1670
+ select(CronJob).where(col(CronJob.job_id) == job_id)
1671
+ )
1672
+ return result.scalar_one_or_none()
1673
+
1674
+ async def delete_cron_job(self, job_id: str) -> None:
1675
+ async with self.get_db() as session:
1676
+ session: AsyncSession
1677
+ async with session.begin():
1678
+ await session.execute(
1679
+ delete(CronJob).where(col(CronJob.job_id) == job_id)
1680
+ )
1681
+
1682
+ async def get_cron_job(self, job_id: str) -> CronJob | None:
1683
+ async with self.get_db() as session:
1684
+ session: AsyncSession
1685
+ result = await session.execute(
1686
+ select(CronJob).where(col(CronJob.job_id) == job_id)
1687
+ )
1688
+ return result.scalar_one_or_none()
1689
+
1690
+ async def list_cron_jobs(self, job_type: str | None = None) -> list[CronJob]:
1691
+ async with self.get_db() as session:
1692
+ session: AsyncSession
1693
+ query = select(CronJob)
1694
+ if job_type:
1695
+ query = query.where(col(CronJob.job_type) == job_type)
1696
+ query = query.order_by(desc(CronJob.created_at))
1697
+ result = await session.execute(query)
1698
+ return list(result.scalars().all())
astrbot/core/event_bus.py CHANGED
@@ -54,7 +54,6 @@ class EventBus:
54
54
  event (AstrMessageEvent): 事件对象
55
55
 
56
56
  """
57
- event.trace.record("event_dispatch", config_name=conf_name)
58
57
  # 如果有发送者名称: [平台名] 发送者名称/发送者ID: 消息概要
59
58
  if event.get_sender_name():
60
59
  logger.info(
@@ -9,6 +9,7 @@ from astrbot.core.message.components import (
9
9
  AtAll,
10
10
  BaseMessageComponent,
11
11
  Image,
12
+ Json,
12
13
  Plain,
13
14
  )
14
15
 
@@ -117,9 +118,26 @@ class MessageChain:
117
118
  self.use_t2i_ = use_t2i
118
119
  return self
119
120
 
120
- def get_plain_text(self) -> str:
121
- """获取纯文本消息。这个方法将获取 chain 中所有 Plain 组件的文本并拼接成一条消息。空格分隔。"""
122
- return " ".join([comp.text for comp in self.chain if isinstance(comp, Plain)])
121
+ def get_plain_text(self, with_other_comps_mark: bool = False) -> str:
122
+ """获取纯文本消息。这个方法将获取 chain 中所有 Plain 组件的文本并拼接成一条消息。空格分隔。
123
+
124
+ Args:
125
+ with_other_comps_mark (bool): 是否在纯文本中标记其他组件的位置
126
+ """
127
+ if not with_other_comps_mark:
128
+ return " ".join(
129
+ [comp.text for comp in self.chain if isinstance(comp, Plain)]
130
+ )
131
+ else:
132
+ texts = []
133
+ for comp in self.chain:
134
+ if isinstance(comp, Plain):
135
+ texts.append(comp.text)
136
+ elif isinstance(comp, Json):
137
+ texts.append(f"{comp.data}")
138
+ else:
139
+ texts.append(f"[{comp.__class__.__name__}]")
140
+ return " ".join(texts)
123
141
 
124
142
  def squash_plain(self):
125
143
  """将消息链中的所有 Plain 消息段聚合到第一个 Plain 消息段中。"""